Created
May 23, 2018 16:40
-
-
Save jpitchardu/aa79bc49214a5d404073fd52b8bbea29 to your computer and use it in GitHub Desktop.
Optional functionality in js using proxies
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
function optional(obj, evalFunc, def) { | |
const handler = { | |
get: function(target, prop, receiver) { | |
const res = Reflect.get(...arguments); | |
return typeof res === "object" ? proxify(res) : res != null ? res : def; | |
} | |
}; | |
const proxify = target => { | |
return new Proxy(target, handler); | |
}; | |
return evalFunc(proxify(obj, handler)); | |
} | |
const obj = { | |
items: [{ hello: "Hello" }] | |
}; | |
console.log(optional(obj, target => target.items[0].hello, "def")); // => Hello | |
console.log(optional(obj, target => target.items[0].hell, { a: 1 })); // => { a: 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment