macroable

A simple ES6 class that can be extended to provide macros and getters functionality

MIT 27 个版本
安装
npm install macroable
yarn add macroable
pnpm add macroable
bun add macroable
README

Macroable

Extend class prototype in style 😎

gh-workflow-image typescript-image npm-image license-image synk-image

Base class for exposing external API to extend the class prototype in a more declarative way.

Table of contents

Traditional approach

class Foo {}
module.exports = Foo

Someone 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'
  },
})

Using macroable

import { Macroable } from 'macroable'

class Foo extends Macroable {}

Foo.macros = {}
Foo.getters = {}

export default Foo
import Foo from './Foo'

Foo.macro('greet', function () {
  return 'Hello!'
})

Foo.getter('username', function () {
  return 'virk'
})

You can see the API is simpler and less verbose. However, there are couple of extra benefits of using Macroable.

Defining singleton getters

Singleton getters are evaluated only once and then cached value is returned.

Foo.getter('baseUrl', function () {
  return lazilyEvaluateAndReturnUrl()
}, true) 👈

Hydrating the class

Using the hydrate method, you can remove macros and getters added on a given class.

Foo.macro('greet', function (name) {
  return `Hello ${name}!`
})

Foo.getter('username', function () {
  return 'virk'
})

Foo.hydrate()  👈
Foo.greet // undefined
Foo.username // undefined
版本列表
7.0.2 2022-10-13
7.0.1 2022-04-04
7.0.0 2022-03-23
6.0.4 2022-03-23
6.0.3 2022-03-23
6.0.2 2022-03-23
6.0.1 2022-02-22
6.0.0 2021-12-17
5.1.4 2021-07-19
5.1.3 2021-05-31
5.1.2 2021-05-04
5.1.1 2021-03-22
5.1.0 2021-02-08
5.0.3 2020-09-21
5.0.2 2020-08-31
5.0.1 2020-07-18
5.0.0 2020-07-05
4.0.4 2020-04-12
4.0.3 2020-04-09
4.0.2 2020-02-07
4.0.1 2019-12-30
4.0.0 2019-12-19
3.0.0 2019-11-22
2.0.2 2019-03-23
2.0.1 2019-02-02
2.0.0 2018-10-28
1.0.0 2017-06-01