Created
July 5, 2019 15:05
-
-
Save guangtuan/fc7403bf8f49abba153349e7ecb84d4d to your computer and use it in GitHub Desktop.
makeItPointfree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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