Rebuilding the Branch-Name Helper
In this lesson, you rebuild the team’s branch-name helper in JavaScript, from pieces you’ve already practiced in this course. Remember what broke: an emoji cut in half, two look-alike titles giving two names, and names over the host’s 32-byte limit.
The team lead’s Python version is the reference the port has to match. branch_name() cleans the title
into a slug and puts the ticket key in front, fit_bytes() keeps the name within the limit, and show()
prints each name with its size in bytes, for four tickets:
import re
import unicodedata as ud
def fit_bytes(text, limit):
result = ""
for point in text:
candidate = result + point
if len(candidate.encode("utf-8")) > limit:
break
result = candidate
return result
def branch_name(key, title, limit=32):
text = ud.normalize("NFC", title).lower()
slug = "".join(c if ud.category(c)[0] in "LN" else "-"
for c in text)
slug = re.sub("-+", "-", slug).strip("-")
branch = f"{key.lower()}-{slug}"
return fit_bytes(branch, limit).rstrip("-")
def show(key, title):
branch = branch_name(key, title)
print(branch, len(branch.encode("utf-8")))
show("PAY-2401", "Zoë's 😀 refund fix")
show("PAY-2402", "café receipts")
show("PAY-2402", "cafe\u0301 receipts")
show("PAY-2403", "東京 refund approval")
In fit_bytes(), Python calls encode() on each string. In JavaScript, TextEncoder is built in, with
no import: you make one at the top of the file and reuse it.