Skip to content

Instantly share code, notes, and snippets.

@jakewtaylor
Last active January 10, 2019 09:15
Show Gist options
  • Save jakewtaylor/392571febb43167cf5cf23fc81d7bc92 to your computer and use it in GitHub Desktop.
Save jakewtaylor/392571febb43167cf5cf23fc81d7bc92 to your computer and use it in GitHub Desktop.
Maybe function
const maybe = (item, fallback = null) => item ? item : new Proxy({}, {
get () {
return fallback;
}
});
// Usage:
const items = [{ id: 1, value: 'a' }, { id: 2, value: 'b' }];
maybe(items.find(itm => itm.id === 1)).value; // 'a'
maybe(items.find(itm => itm.id === 3)).value; // null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment