Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

skava / chain-able-lego   js

Repository URL to install this package:

Version: 6.0.4 

/ src / Klass.ts

import {
  isFunction,
  props,
  getPrototypeOf,
  pipe,
  bind,
  curry,
} from 'chain-able-deps'
import { Class } from './_typings'

const getFunctions = (Klass: Class<any>) => {
  const methods = props(Klass)
  const names = []

  for (let index = 0; index < methods.length; index++) {
    const method = methods[index]
    if (isFunction(Klass[method])) {
      names.push(method)
    }
  }

  return names
}

// @TODO in wrap
// @TODO to avoid `new` errors
const constructIfNeeded = (Klass: Class<any>) => {
  const KlassConstructor = new Klass()
  return KlassConstructor
}

const constructAndCall = curry(2, (Klass: Class<any>, method: string) => {
  const instance = constructIfNeeded(Klass)
  return bind(instance[method], instance)
})

const hoistStatics = (Klass: Class<any>) => {
  const scopedMethod = constructAndCall(Klass)
  for (let method in Klass.prototype) {
    Klass[method] = scopedMethod(method)
  }

  return Klass
}

// @TODO just curry `mapObjVals` ?
const updateObjProps = curry(
  3,
  (Klass: Class<any>, methods: string[], fn: Function) => {
    // const destucturAble = {}
    // destucturAble[method]

    for (let index = 0; index < methods.length; index++) {
      const method = methods[index]
      Klass[method] = fn(Klass[method], method, index)
    }

    return Klass
  }
)

const overStaticMethods = curry(2, (Klass: Class<any>, fn: Function) => {
  const methods = getFunctions(Klass)
  return updateObjProps(Klass, methods, fn)
})

// @TODO safety
const getMethods = pipe(
  getPrototypeOf,
  getFunctions
)
const getStaticMethods = getFunctions
const overMethods = curry(2, (Klass: Class<any>, fn: Function) => {
  const methods = getMethods(Klass)
  return updateObjProps(Klass, methods, fn)
})

export {
  overStaticMethods,
  getFunctions,
  overMethods,
  getMethods,
  getStaticMethods,
  hoistStatics,
}