Skip to content

Instantly share code, notes, and snippets.

@jpitchardu
Created May 23, 2018 16:40
Show Gist options
  • Save jpitchardu/aa79bc49214a5d404073fd52b8bbea29 to your computer and use it in GitHub Desktop.
Save jpitchardu/aa79bc49214a5d404073fd52b8bbea29 to your computer and use it in GitHub Desktop.

Revisions

  1. jpitchardu created this gist May 23, 2018.
    19 changes: 19 additions & 0 deletions optional.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    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 }