DEV Community

loading...

Discussion on: how not to use reduce

Collapse
ycmjason profile image
Jason Yu Author • Edited

Try it out. Try to write code in a way so that "it explains itself" and doesn't require comments. Optimise only the complexity (big-O) of the code; not the performance perks of using for-loops / some other methods.

So if you are doing something like

xs.find(x => ys.includes(x))

This is O(n*m) and we can improve this to make it O(n + m) by doing:

const ySet = new Set(ys)
xs.find(x => ySet.has(x))

So this is the kind of things I optimise.

P.S. I use comments primarily for things that are uncommon. A good example I encounter recently is, in jest, expect(-0).toBe(0) will fail the test. So I needed to do expect(-0 === 0).toBe(true). I add comment for these kind of things explaining why I write like this.

Collapse
rkichenama profile image
Richard Kichenama

I believe you are right, though the implementation of Set in javascript should give O(1) or at most sublinear lookups with a hashing function. Based on that, I assume the following would be equivalent without the new data type.

const jObj = ys.reduce((t, c) => { t[c] = true; return t; });
xs.find(x => ( jObj[x] ));
Thread Thread
ycmjason profile image
Jason Yu Author

ya except I'd not use a reduce.