Last active
January 10, 2019 09:15
-
-
Save jakewtaylor/392571febb43167cf5cf23fc81d7bc92 to your computer and use it in GitHub Desktop.
Maybe function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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