VitorLuizC / uncouple

📂 Uncouple constructors and classes methods into functions.
MIT License
14 stars 1 forks source link

Reduce iterations #3

Closed VitorLuizC closed 6 years ago

VitorLuizC commented 6 years ago

I was reading it again and seems like it's pretty shit.

It getOwnPropertyDescriptions, then map to entries Array<[ string, PropertyDescriptor ]>, then map again to Array< PropertyDescriptor & { name: string } >, filter only methods and reduce to an object.

I shoud use getOwnPropertyNames which gives me an Array<string> and reduce it, on reduce i can get PropertyDescriptor check if is method and merge to object.

const isMethod = ({ name, value }) => (
  name !== 'constructor' &&
  typeof name === 'string' &&
  typeof value === 'function'
);

const uncouple = (object) => {
  const properties = Object.getOwnPropertyNames(object.prototype || object);
  const methods = properties.reduce((methods, property) => {
    const { value } = Object.getOwnPropertyDescriptor(object, property);
    if (!isMethod({ value, name: property }))
      return methods;
    return Object.assign({}, methods, { [property]: Function.call.bind(value) });
  }, {});
  return methods;
};

Both Object.getOwnPropertyNames and Object.getOwnPropertyDescriptor have a good support, so don't need object.getownpropertydescriptors and object.entries polyfills.

VitorLuizC commented 6 years ago

https://gist.github.com/VitorLuizC/6ee5bd45ea65c7d63168d70ff432c75b