Extend
classprototype in style 😎
Macroable is a simple class that your classes can extend in order to expose an API for extending the class. Let's see how a class can be extended without Macroable first.
class Foo {}
module.exports = FooSomeone can extend it follows.
const Foo = require('./Foo')
Foo.prototype.greet = function () {
return 'Hello!'
}
// or add getter as follow
Object.defineProperty(Foo.prototype, 'username', {
get: function () {
return 'virk'
}
})const { Macroable } from 'macroable'
class Foo extends Macroable {
}
Foo._macros = {}
Foo._getters = {}
module.exports = Fooconst Foo = require('./Foo')
Foo.macro('greet', function () {
return 'Hello!'
})
Foo.getter('username', function () {
return 'virk'
})You can see the API is simpler and less verbose. However, their are couple more benefits to using Macroable.
- You can add singleton getters, which are evaluated only once and then cached value is returned.
- Cleanup all
macrosandgettersadded using Macroable.
npm i macroableconst { Macroable } from 'macroable'
class Foo extends Macroable {
}
Foo._macros = {}
Foo._getters = {}
module.exports = FooAdd a function to the prototype
Foo.macro('greet', function (name) {
return `Hello ${name}!`
})Find if macro exists.
Foo.hasMacro('greet')Add getter to the prototype and optionally make it singleton.
Foo.getter('username', function () {
return 'virk'
}, true)Find if getter exists.
Foo.hasGetter('greet')Remove all macros and getters added using Macroable.
Foo.getter('username', function () {
return 'virk'
}, true)
Foo.hydrate()
Foo.hasGetter('username') // falseThe change log can be found in the CHANGELOG.md file.
Everyone is welcome to contribute. Please go through the following guides, before getting started.
thetutlage and contributors.
MIT License, see the included MIT file.