Created
February 17, 2023 22:25
-
-
Save dfkaye/4387036bf1f53f66db5a973f2ac49a3d to your computer and use it in GitHub Desktop.
lift parts out of a value using the Object constructor guard
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
// 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