DEV Community

Discussion on: how not to use reduce

Collapse
 
rkichenama profile image
Richard Kichenama

Thank you for the post. I struggle with understanding how important readability is, coming from a 'use descriptive variables' and 'comment complex code' background. You have given me stuff to think about, but I feel more comfortable with explaining wha tthe code does and advocating for the more efficient and maintainable code. My gut reaction to the term 'readability', with the absence of those two axioms, makes me feel less like a solution architect and more paint by numbers.

Collapse
 
ycmjason profile image
YCM Jason • 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
YCM Jason

ya except I'd not use a reduce.