Created
June 19, 2018 10:12
-
-
Save denisdubovitskiy/4d86bf0e1d47692d07bdbec7198f764b to your computer and use it in GitHub Desktop.
Function parameter type checker example
This file contains hidden or 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 add = (a, b) => a + b; | |
| /** | |
| * Ensure that input is a Number | |
| * @param input {*} | |
| */ | |
| const typeNumber = (input) => { | |
| if (typeof input !== 'number') { | |
| throw new Error(`${input} is not a number`); | |
| } | |
| }; | |
| /** | |
| * Type checker decorator | |
| * @param originalFunction {function} | |
| * @param types {Array} | |
| * @returns {function} | |
| */ | |
| const typeChecked = (originalFunction, types) => { | |
| const wrapped = (...args) => { | |
| types.forEach((argType, index) => argType(args[index])); | |
| return originalFunction(...args); | |
| }; | |
| // Preserve original function name | |
| Object.defineProperty(wrapped, 'name', { value: originalFunction.name }); | |
| return wrapped; | |
| }; | |
| const addChecked = typeChecked(add, [typeNumber, typeNumber]); | |
| console.log(addChecked.name); | |
| console.log(addChecked(1, 2)); | |
| console.log(addChecked('s', 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment