Skip to main content

Flatten array and count occurrences

· 4 min read
Filip Tammergård
Software Engineer at Frilans Finans

I recently added support for filtering blog posts by categories. (I've since replaced that with category and author pages, so this functionality is no longer used.) Next to each category in the filter view, the number of posts in that category was also shown. In this post I'll walk through what I was trying to accomplish and how I solved it.

Disco generator

· 3 min read
Filip Tammergård
Software Engineer at Frilans Finans

It's Friday disco time!

TL;DR

  • A grid of cells each get a random rgb(...) color, and the useInterval custom hook reassigns every color on each beat.
  • The frequency in hertz maps to the interval delay as 1000 / frequency; dropping below 1 Hz passes null and pauses the disco.
  • The CSS grid layout and each cell's color are set with inline styles, which suit values that change on every render better than CSS classes.

Alphabet game

· One min read
Filip Tammergård
Software Engineer at Frilans Finans

In this game, you're supposed to write the alphabet as fast as you can. Click the box and start the game by typing the first letter of the alphabet. My highscore is 2.95 seconds. Beat that if you can!

Custom hook: useInterval

· 4 min read
Filip Tammergård
Software Engineer at Frilans Finans

setInterval runs a callback at a fixed cadence. Using it in React means remembering to call clearInterval on unmount, and reaching for extra state any time the interval should pause or restart. This post wraps both concerns in a small custom hook called useInterval.

TL;DR

  • useEffect starts the interval and returns a cleanup that calls clearInterval — no manual unmount handling.
  • The latest callback is kept in a ref, so the interval keeps ticking at a steady rate even when the component re-renders for unrelated reasons.
  • Passing null as the delay pauses the interval, so you can derive "running" straight from props or state instead of tracking it separately.
  • Changing the delay restarts the interval automatically, so a dynamic value "just works".

What have I copied?

· 3 min read
Filip Tammergård
Software Engineer at Frilans Finans

Have you ever copied something and immediately forgotten what it was?

TL;DR

  • navigator.clipboard.readText() returns a Promise<string> with the current clipboard text.
  • It is only available in a secure context (HTTPS or localhost), and the read has to happen during a user activation — that's why it's wired up to a button click rather than running on mount.
  • The call can reject (permission denied, document not focused, no clipboard support, …), so it always belongs in a try/catch.

Letter game

· 4 min read
Filip Tammergård
Software Engineer at Frilans Finans

Start the game by clicking the box and typing the letter shown. The clock starts and you get a new random letter to type as fast as you can. Each correct letter is followed by a new random letter, and if you type the wrong letter, the game ends. Go for it!

TL;DR

  • A small typing game built in React with TypeScript.
  • useReducer keeps the game state in one place, with the current mode as idle or running.
  • useEffect reads the saved high score from local storage and picks the first random letter on mount.
  • A custom useInterval hook drives the running clock.

Index of the biggest value in an array

· 4 min read
Filip Tammergård
Software Engineer at Frilans Finans

Finding the index of the largest value in an array is one of those tasks that looks trivial but has a few different shapes — each with its own trade-offs around readability, performance and pitfalls.

TL;DR

  • A for-loop works but requires several mutable variables.
  • A reduce can do the job in a single pass, but it isn't very readable.
  • In practice years.indexOf(Math.max(...years)) is usually the best choice — readable and compact, even though it walks the array three times under the hood.

Birthday maths

· 11 min read
Filip Tammergård
Software Engineer at Frilans Finans

Have you ever wondered how old you are…in milliseconds? Or exactly how many weeks there are between two moments in time? Don't worry, in this post you can get the answer to all your "How many [unit] is it between [moment] and [moment]?" questions!

TL;DR

  • Milliseconds, seconds, minutes, hours, days and weeks between two moments are trivial to compute — just divide the millisecond difference by the right constant.
  • Months and years are trickier because their length varies. The trick is to count full periods forward from the start date and add the fraction of the next period we've reached — the same anchor-based model the Temporal API uses.
  • If you just want the answer, call Temporal.Duration.prototype.total directly instead of writing the math yourself.

Robber language generator

· 11 min read
Filip Tammergård
Software Engineer at Frilans Finans

Robber language (Swedish: rövarspråket) is said to have been invented by Sture Lindgren — husband of the author Astrid Lindgren — when he played with his friends as a child. Astrid Lindgren's books about Kalle Blomkvist made the language popular in Sweden.

Robber language is a spoken code where every consonant is replaced by the consonant + "o" + the consonant again. From that simple rule, building a robber language generator should be dead easy. When it comes to written robber language, however, there are a few more aspects to consider. So this post is really about a written robber language generator.

note

Robber language was designed for Swedish and doesn't translate cleanly to English. Swedish has a clean consonant/vowel split — the letter "y" is a vowel, and "x" is always pronounced "ks" — which is what makes the rule "consonant + o + consonant" work consistently. English is messier: "y" flips between consonant and vowel ("yes" vs "happy"), "x" can sound like "ks" ("ax") or "z" ("xylophone"), and digraphs like "sh", "ch" and "th" represent single sounds that the letter-by-letter rule splits apart.

Spoken English actually works fine if you treat a consonant as a consonant sound rather than a letter — "ship" then becomes one consonant sound + vowel + consonant sound, not s-h-i-p. By sound, "ship" translates to "shoshipop"; a letter-by-letter generator would instead spit out "soshohipop", which doesn't match how the word is pronounced. Doing it by sound puts the burden on the speaker to do the phonetic analysis on the fly, and writing a generator for it would mean shipping a pronunciation dictionary or grapheme-to-phoneme model rather than the simple letter-by-letter substitution this post is about. So the Swedish examples are the ones that actually sound right when spoken — though even Swedish isn't perfectly clean: digraphs like "sj", "sch" and "tj" are single sounds that the letter-by-letter rule splits apart, just accepted by convention rather than worked around.

TL;DR

  • The simple spoken rule (consonant + "o" + consonant) needs a few additions to work in writing — mainly handling "x" and uppercase.
  • This post walks through two strategies for building a generator in JavaScript: looping over the consonants, and looping over the text to translate.
  • A regex with a callback can collapse the whole thing into two lines, shown as the final alternative.

Calendar maths

· 14 min read
Filip Tammergård
Software Engineer at Frilans Finans

You might think week numbers are dead simple. Surely you just start at week 1 and go up to week 52, then start over? Unfortunately it's not that easy. It turns out to be surprisingly complicated!

note

This article describes week numbering according to ISO 8601, which Sweden and most European countries follow. Other conventions exist — the United States, for example, uses Sunday as the first day of the week and treats week 1 as the week containing January 1 — so the model looks different there. The "53-week year" phenomenon explored below is specific to ISO 8601: ISO requires full seven-day weeks, while the US convention simply truncates the first and last weeks of the year to fit.

TL;DR

  • Most years have 52 weeks, but some have 53.
  • Whether a year has 53 weeks depends on what day of the week January 1 of the following year falls on, and whether the current year is a leap year.
  • Leap years occur slightly less than every four years on average, which makes the model for when 53 weeks appear tricky.