Skip to content

Instantly share code, notes, and snippets.

@alexreardon
Last active October 1, 2019 19:31
Show Gist options
  • Save alexreardon/17ce55a4cc635d725f85f8ad81952318 to your computer and use it in GitHub Desktop.
Save alexreardon/17ce55a4cc635d725f85f8ad81952318 to your computer and use it in GitHub Desktop.
Lazy lookup
const getIdMap = memoizeOne((array) => {
return array.reduce((previous, current) => {
previous[current.id] = array[current];
return previous;
}, {});
});
const foo = { id: 'foo' };
const bar = { id: 'bar' };
// our lovely ordered structure
const ordered = [ foo, bar ];
// lazily computed map for fast lookups
const map1 = getMap(ordered);
map1['foo'] === foo; // true
map1['bar'] === bar; // true
map1['baz'] === undefined; // true
const map2 = getMap(ordered);
// returned the same map as before - no recomputation required
const map1 === map2;
@emersonlaurentino
Copy link

Interesting, just a caveat: you declare getIdMap, but does call to getMap.

@rkrupinski
Copy link

Also:

- return array.reduce((previous, current) => {
-   previous[current.id] = array[current];
+ return array.reduce((previous, current, index) => {
+   previous[current.id] = array[index];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment