Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Rebuilding the Branch-Name Helper

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:

Language: Python
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.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 In this lesson, you’ll rebuild the team’s branch-name helper in JavaScript, from pieces you’ve already practiced. Remember what broke: an emoji cut in half, two look-alike titles giving two names, and names over the host’s 32-byte limit.

00:16 Here’s the team lead’s Python version, the reference your port has to match. branch_name() cleans the title into a slug and puts the ticket key in front.

00:26 fit_bytes() keeps the name within the limit. And show() prints each name with its size in bytes, for four tickets: Zoë’s, two café titles, one with a separate accent mark, and a Tokyo one.

00:40 Start with fit_bytes(). Python calls encode() on every string. In JavaScript, TextEncoder is built in: you make one at the top and reuse it.

00:51 The loop ports line for line. for...of goes through the text one code point at a time, as Python’s for does, so no code point, not even an emoji’s, is cut in half.

01:03 Each pass measures the candidate, the result plus the next code point, in UTF-8 bytes: the encoded array’s length, not the string’s. Over the limit, break; otherwise the candidate becomes the result.

01:18 That’s the right cut for a branch name, a machine identifier, even inside an emoji built from several code points. For a title a person reads, you’d cut by grapheme with Intl.Segmenter instead.

01:32 Next, the slug. .normalize() with NFC, then .toLowerCase(), port Python’s first line, so both café titles become the same text before the pattern runs; otherwise the separate accent, not a letter, would be lost.

01:48 Python’s re has no property escapes. So the script asks unicodedata.category() about each character and keeps L and N, letters and numbers.

01:59 Everything else becomes a hyphen, and re.sub() replaces each run of hyphens with one. JavaScript does both in one .replace(). The class matches anything that’s not a letter or number, the u flag makes \p a property escape, and g replaces every match, as re.sub() does.

02:20 A second .replace() trims hyphens from both ends, as strip() does.

02:27 Try it on Zoë’s title. The emoji sits between two spaces. How many hyphens does the first .replace() put between s and refund?

02:36 Your turn: pause the video and predict.

02:45 One: the space, emoji and space are a single run, and the plus takes the whole run.

02:53 The script gets there in two passes: three hyphens, then re.sub() makes them one. Python’s [\W_]+ could do it in one pass, since its \w knows Unicode.

03:07 JavaScript’s \w doesn’t, even with u, so the port names the categories.

03:14 The rest of branch_name() ports line for line. A template literal puts the lowercased key in front of the slug, where Python uses an f-string.

03:24 limit = 32 is a default parameter, as in Python, with spaces around the equals sign. fitBytes() could stop right after a hyphen, so a last .replace() trims any trailing hyphens, like rstrip().

03:40 Last, show() logs each name with its byte count, from the same encoder. The four calls use Python’s four keys and titles. Now run both scripts.

03:51 JavaScript prints four lines, and Python’s four match them, character for character. Zoë’s emoji is gone, since it’s neither a letter nor a number. Both café titles give one branch, because both were normalized first.

04:06 And the Tokyo name has 27 code points but 31 bytes, one under the limit, so it stays whole.

04:15 So the JavaScript helper normalizes to NFC first, builds the slug with one Unicode-aware pattern, and fits the name by UTF-8 bytes, whole code points at a time.

04:26 Every step does what a step of the Python does, and every line of output matches.

04:32 Next up is the quiz, JavaScript Unicode, Bytes, and Advanced Regular Expressions (Quiz). It checks code units, code points and graphemes, normalization, UTF-8 byte budgets, typed-array views, and the Unicode and sticky regex flags, on fresh cases.

Become a Member to join the conversation.