Collected · clsx · MIT

Temporary exhibition · Hall of the Commons

The Same Idea, Four Years Later

JavaScript·2018·43 lines·704 bytes

Curator’s note

Hanging next to classnames on purpose. The same problem, solved again four years later by someone who thought the first answer was too big.

Both take any mixture of strings, arrays and objects and produce one class attribute. Both are the sort of thing you would write in ten minutes and never think about again, except that between them they are downloaded tens of millions of times a week, which makes ten minutes' work into infrastructure.

The differences are all about size, and none of them is an accident. var rather than let, because it minifies to the same thing and compresses marginally better. Assignment inside a condition — if (y = toVal(mix[k])) — which does the call and the truthiness test in one expression, and which most linters will flag. arguments instead of a rest parameter, because a rest parameter allocates an array. None of this is how you would write application code. All of it is how you write a library that half the ecosystem loads on every page.

The recursion is the interesting part. toVal calls itself on array elements, so an array may contain arrays containing objects to any depth, and the whole thing is handled by four lines that were not written with nesting particularly in mind. It falls out of the shape.

What the pair really exhibits is a fact about the ecosystem rather than about either library. The problem was solved, correctly, in 2014. It was solved again in 2018, correctly, and slightly smaller. Both are still maintained, both are still growing, and the second did not replace the first.

Elsewhere in the museum