Skip to content

Instantly share code, notes, and snippets.

@denisdubovitskiy
Created June 19, 2018 10:12
Show Gist options
  • Select an option

  • Save denisdubovitskiy/4d86bf0e1d47692d07bdbec7198f764b to your computer and use it in GitHub Desktop.

Select an option

Save denisdubovitskiy/4d86bf0e1d47692d07bdbec7198f764b to your computer and use it in GitHub Desktop.
Function parameter type checker example
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