Skip to content

Instantly share code, notes, and snippets.

@Avaq
Last active October 12, 2021 04:13
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Avaq/b9cff9b617e54488a5c7c55df00e44a7 to your computer and use it in GitHub Desktop.
Save Avaq/b9cff9b617e54488a5c7c55df00e44a7 to your computer and use it in GitHub Desktop.
Dangerous Promises
//
// utils
//
const thrush = x => f => f(x);
const indexBy = k => xs => xs.reduce((index, x) => {
if(index[x[k]] != null) index[x[k]].push(x);
else index[x[k]] = [x];
return index;
}, {});
const mapObject = f => o => Object.keys(o).reduce((mapped, k) => {
mapped[k] = f(o[k]);
return mapped;
}, {});
//
// program
//
const fetchUsers = _ => Promise.resolve([
{id: 1, name: 'bob'},
{id: 2, name: 'frank'},
{id: 3, name: 'bob'},
]);
const isLongerThan = xs => n => xs.length > n;
fetchUsers()
.then(indexBy('name'))
.then(mapObject(isLongerThan))
.then(mapObject(thrush(1)))
.then(console.log, console.error);
@Avaq
Copy link
Author

Avaq commented Aug 22, 2017

This somewhat-contrived-but-not-unthinkable program loads a list of users and writes to the terminal, for every user name, whether there exist more than one users with this name.

Now what happens when one of the users names themselves then?

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