Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created February 17, 2023 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/4387036bf1f53f66db5a973f2ac49a3d to your computer and use it in GitHub Desktop.
Save dfkaye/4387036bf1f53f66db5a973f2ac49a3d to your computer and use it in GitHub Desktop.
lift parts out of a value using the Object constructor guard
// 17 February 2023
// lift parts out of a value
// using the Object constructor guard
function lift(v, key) {
var o = Object(v);
return Object.hasOwn(o, key)
? o[key]
: undefined;
}
function parts(v, keys = []) {
var p = {};
["valueOf", "toString"].concat(keys).forEach(function(key, _) {
_ = lift(v, key);
_ != null && (p[key] = _);
});
return p;
}
console.log(
lift(["hello, "])
);
console.log(
lift(["hello, "], 0) + "world"
);
console.log(
parts(["hello, "])[0]
);
console.log(
parts(["hello, "]).toString() + "world"
);
console.log(
parts(1, ['greet']).toString()
);
console.log(
parts({"greet": "hello, ", toString() { return this.greet; } }, ['greet']) + "world"
);
/*
undefined
hello, world
undefined
[object Object]world
[object Object]
hello, world
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment