Skip to content

Instantly share code, notes, and snippets.

@ant1m4tt3r
Last active September 11, 2020 13:00
Show Gist options
  • Save ant1m4tt3r/6c101a3c706759913b50dcd2db906a8a to your computer and use it in GitHub Desktop.
Save ant1m4tt3r/6c101a3c706759913b50dcd2db906a8a to your computer and use it in GitHub Desktop.
Object as HOF
// HOFCreator.js -----------
const HOFCreator = {
createProxy(methods, dataContext) {
const handler = {
apply (_, __, property) {
return function (...args) {
return methods[property].call(dataContext, ...args)
}
},
}
return new Proxy(() => {}, handler)
}
}
// -------------------------
// Person.js ---------------
const PersonMethods = {
getFullName () {
return this.name + ' ' + this.lastName
},
setFirstName (name) {
this.name = name
},
setLastName (lastName) {
this.lastName = lastName
}
}
function Person (name, lastName) {
const PersonContext = {name, lastName}
return HOFCreator.createProxy(PersonMethods, PersonContext)
}
// -------------------------
// main.js -----------------
const person = Person('Hugo', 'Azevedo')
console.log(person('getFullName')()) // 'Hugo Azevedo'
person('setFirstName')('Me segue no twitter')
person('setLastName')('@hugoidont')
console.log(person('getFullName')()) // 'Me segue no twitter: @hugoidont'
// -------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment