Skip to content

Instantly share code, notes, and snippets.

@jonrandy
Last active July 16, 2024 14:21
Show Gist options
  • Save jonrandy/3c5443af2c522e211cdb28769eaec1e4 to your computer and use it in GitHub Desktop.
Save jonrandy/3c5443af2c522e211cdb28769eaec1e4 to your computer and use it in GitHub Desktop.
Add parameterised methods safely to prototypes etc.
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