Idiomatic way looks pretty cool and shorter, but it is less efficient and hard to read.
If people familiar with the language find it hard to read, it’s not “idiomatic”. (You might be going by one definition of the word – “using many idiom¹s” – but this isn’t what people mean when they refer to idiomatic code, though it’s true that Array.from({length}, fn)
, for example, is an idiom¹ for filling an array based on a function in JavaScript. Rather, it’s code that’s written the way users of the language expect.) You could get it closer by naming some stuff:
const tagNumbers = Array.from(
{length: tagCount},
() => Math.floor(Math.random() * 10),
);
const uniqueTagNumbers = Array.from(new Set(tagNumbers));
const tagString =
uniqueTagNumbers
.map(n => 'tag' + n)
.join('|');
and by making use of the type of utility functions that would exist in practice:
import generate from '…';
import unique from '…';
const getRandomTag = () =>
Math.random() * 10 | 0;
const tags =
generate(tagCount, getRandomTag);
const tagString =
unique(tags)
.map(n => 'tag' + n)
.join('|');
There’s only so far you can go with toy examples, though.
As for performance: not everything has to be micro-optimized. Your two examples here have the same asymptotic time and space complexity, and that’s enough for many cases. You’re writing in JavaScript because its language features let you express yourself better² at the cost of performance, after all. And when it does come to optimization, you’ll probably want to write more accurate benchmarks (which is pretty hard in Node!) – e.g. try reordering those measurements.
¹ in the sense of being an expression that users of the language are aware means something without the expression itself conveying that clearly.
² or because someone else or some other group of people thought that and now you’re stuck working on their code, or maybe it was for some reason other than expressiveness per se, or the aforementioned people were in that same boat³, …
³ oh hey an idiom