Skip to content

Instantly share code, notes, and snippets.

@guangtuan
Created July 5, 2019 15:05
Show Gist options
  • Save guangtuan/fc7403bf8f49abba153349e7ecb84d4d to your computer and use it in GitHub Desktop.
Save guangtuan/fc7403bf8f49abba153349e7ecb84d4d to your computer and use it in GitHub Desktop.
makeItPointfree
const pointfree = prototypeOrFunc => {
if (typeof prototypeOrFunc === 'function') {
if (isConstructor(prototypeOrFunc)) {
return (...args) => new prototypeOrFunc(...args);
} else {
return (...args) => prototypeOrFunc.bind(args.shift())(...args);
}
}
const Type = {};
Object.getOwnPropertyNames(prototypeOrFunc).forEach(func => {
if ('constructor' === func) {
Type.new = (...args) => new prototypeOrFunc.constructor(...args);
} else {
Type[func] = (...args) => args.shift()[func](...args);
}
});
return Type;
};
function isConstructor(f) {
try {
new f();
} catch (err) {
return false;
}
return true;
}
module.exports = {
pointfree
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment