Skip to content

Instantly share code, notes, and snippets.

@galabra
Created January 8, 2021 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galabra/57bea6bc88dbb48696ce52f9e5c2e1bc to your computer and use it in GitHub Desktop.
Save galabra/57bea6bc88dbb48696ce52f9e5c2e1bc to your computer and use it in GitHub Desktop.
These three versions of equivalent code demonstrates how code should be self-explainable
dataArray.reduce((a, b) => [...a,
...(b.data && b.data.isImportant && b.data.value ? [b.data.value] : [])
], []);
/**
* Thwe horrific JavaScript snippet above is equivalent to the following
*/
dataArray
.filter((x) => x.data && x.data.isImportant && x.data.value)
.map((x) => x.data.value);
/**
* And if you really insist on a single iteration, meaningful names
* improve readability significantly
*/
dataArray.reduce((result, element) => {
if (element.data) {
const { isImportant, value } = element.data;
if (isImportant && value) return [...result, value];
}
return result;
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment