Skip to content

Instantly share code, notes, and snippets.

@jpitchardu
Created May 23, 2018 16:17
Show Gist options
  • Save jpitchardu/e29ae7970285b91ce91fc21c7991ea96 to your computer and use it in GitHub Desktop.
Save jpitchardu/e29ae7970285b91ce91fc21c7991ea96 to your computer and use it in GitHub Desktop.
Code blocks for *Optional (null-safe) in Javascript* Medium article
const evaluation = obj && obj.prop1 && obj.prop1.prop2 && obj.prop1.prop2.prop3;
console.log( evaluation != null ? evaluation : "SomeDefaultValue" );
console.log( obj && obj.prop1 && obj.prop1.prop2 && obj.prop1.prop2.prop3 );
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c'); // => 3
_.get(object, ['a', '0', 'b', 'c']); // => 3
_.get(object, 'a.b.c', 'default'); // => 'default'
SomeClass obj;
obj?.prop1?.prop2?.prop3 ?? "SomeDefaultValue";
SomeClass object;
Optional.ofNullable(object)
.map(obj -> obj.prop1)
.map(obj -> obj.prop2)
.map(obj -> obj.prop3)
.orElse("SomeDefaultValue");
val obj: SomeClass?
obj?.prop1?.prop2?.prop3 ?: "SomeDefaultValue";
let obj;
console.log(obj && obj.someProp); // Prints undefined
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" }]
};
optional(obj, target => target.items[0].hello, "def")); // => Hello
optional(obj, target => target.items[0].hell, { a: 1 })); // => { a: 1 }
function optionalAccess(obj, path, def) {
const propNames = path.replace(/\]|\)/, "").split(/\.|\[|\(/);
return propNames.reduce((acc, prop) => acc[prop] || def, obj);
}
const obj = {
items: [{ hello: "Hello" }]
};
optionalAccess(obj, "items[0].hello", "def"); // => Hello
optionalAccess(obj, "items[0].he", "def"); // => def
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment