Skip to main content

Operations in JavaScript with immutable arrays

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

As mentioned many times before, I always try to keep my variables immutable when developing. Let's take a closer look at how we accomplish immutable arrays in JavaScript when adding, replacing or removing elements. We start with an array of birds:

const birds = ["Great tit", "Blue tit", "Pine grosbeak", "Stock dove"]

Format lists with Intl.ListFormat

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

Let's say we have this array of cities:

const cities = ["Uppsala", "Stockholm", "Lycksele", "Lund"]

And let's say we want to write the cities from the array in a sentence like this:

Uppsala, Stockholm, Lycksele and Lund are 4 nice cities in Sweden.

How?!

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.