Last active
July 16, 2024 14:21
-
-
Save jonrandy/3c5443af2c522e211cdb28769eaec1e4 to your computer and use it in GitHub Desktop.
Add parameterised methods safely to prototypes etc.
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
function add(target, f, outerSyntax=false){ | |
return f.length ? | |
outerSyntax ? | |
addProperty(target, f) | |
: | |
addWithParams(target, f) | |
: | |
addSimple(target, f) | |
} | |
function addProperty(target, f) { | |
const s = Symbol() | |
target[s] = f | |
return s | |
} | |
function addWithParams(target, f) { | |
return(function(...args) { | |
const s = Symbol() | |
Object.defineProperty(target, s, { | |
get: function() { | |
delete target[s] | |
return f.apply(this, args) | |
} | |
}) | |
return s | |
}) | |
} | |
function addSimple(target, f) { | |
const s = Symbol() | |
Object.defineProperty(target, s, {get: f}) | |
return s | |
} | |
to = add(Number.prototype, function(toNumber) { | |
return this + '--' + toNumber | |
}) | |
to2 = add(Number.prototype, function(toNumber) { | |
return this + '--' + toNumber | |
}, true) | |
half = add(Number.prototype, function() { return this/2 }) | |
triple = add(Number.prototype, function() { return this*3 }) | |
hex = add(Number.prototype, function() { return this.toString(16) }) | |
bin = add(Number.prototype, function() { return this.toString(2) }) | |
upper = add(String.prototype, function() { return this.toUpperCase() }) | |
reverse = add(String.prototype, function() { return [...this].reverse().join('')}) | |
console.log(14[to(16)]) | |
console.log(14[to2](16)) | |
console.log('Jonathan'[reverse][upper]) | |
// may well need the ability to add descriptions for these Symbols that are flying around | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment