all files / src/ index.js

97.92% Statements 47/48
100% Branches 12/12
100% Functions 9/9
100% Lines 22/22
5 statements, 3 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35       12× 12×                      
const _privates = []
 
export default function klass(target) {
  const proto = target.prototype
  const methodNames = Object.getOwnPropertyNames(proto)
  for (let k in proto) methodNames.push(k)
  const privatesForTarget = _privates.filter(e => e.target === target).map(e => e.name).reduce((all, k) => { all[k] = k; return all }, {})
 
  function Klass(...args) {
    const instance = new target(...args)
    const newProto = {}
    const methodMap = {}
 
    for (let methodName of methodNames) {
      const isPrivate = methodName in privatesForTarget
      if (isPrivate) continue
 
      const fn = proto[methodName]
 
      newProto[methodName] = {
        get() { return methodMap[methodName] || (methodMap[methodName] = fn.bind(instance)) },
        set(newFn) { methodMap[methodName] = newFn.bind(instance); instance[methodName] = newFn }
      }
    }
 
    Object.defineProperties(this, newProto)
  }
 
  return Klass
}
 
klass.private = function (target, name) {
  _privates.push({ target: target.constructor, name })
}