Last active
August 29, 2015 14:02
-
-
Save totherik/dc2323dde8e76b9ee681 to your computer and use it in GitHub Desktop.
Naïve approximation of Swift's nil-safe property access operator `?` - based on Zakas' "Defensive Objects", but kinder.
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
import nil from 'optionil' | |
let obj = { | |
str: 'literal', | |
obj: { | |
num: 5 | |
} | |
}; | |
obj = nil(obj); | |
obj.str; // literal | |
obj.obj; // [object Object] | |
obj.obj.foo.bar.baz; // undefined (does not throw) |
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
export default function optionil(target) { | |
var value; | |
value = target; | |
if (target === undefined || target === null || target !== Object(target)) { | |
target = {}; | |
} | |
return new Proxy(target, { | |
get: function (target, prop) { | |
switch (prop) { | |
case 'toString': | |
return function toString() { | |
if (value === undefined || value === null) { | |
return String(value); | |
} | |
return value.toString(); | |
} | |
case 'valueOf': | |
return function valueOf() { | |
if (value === undefined || value === null) { | |
return value; | |
} | |
return value.valueOf(); | |
} | |
default: | |
return optionil(target[prop]); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment