Skip to content

Instantly share code, notes, and snippets.

@wshager
Last active June 22, 2018 20:44
Show Gist options
  • Save wshager/9e8bb195f249e5c9dc2a1383baf554f7 to your computer and use it in GitHub Desktop.
Save wshager/9e8bb195f249e5c9dc2a1383baf554f7 to your computer and use it in GitHub Desktop.
// when applied, this function should check each of the items in s against the input arguments,
// and the result to r
// when the original is applied, this will simply return the input if valid, or throw if invalid
// for higher-order functions
// the function is not yet evaluated, but we pass a validator and wrap the function
// this will be inspected when provided function is called
const func = (s,r) => fn => {
const f = (...args) => {
const ret = fn(...args.map((a,i) => {
const t = s[i](a);
if(typeof t == "function" && t.hasOwnProperty("__wraps")) {
if(t.__wraps !== a) throw new Error("unknown function found");
} else {
if(t !== a) throw new Error("incorrect input type");
}
return t;
}));
if(r(ret) !== ret) throw new Error("incorrect output type");
return ret;
};
f.__wraps = fn;
return f;
};
// array test
const array = (a) => !Array.isArray(a) || a;
var add = (a,b) => a + b;
var addOne = add.bind(null,1);
var map = (a,f) => a.map(x => f(x));
var typed = func([array,func([Number],Number)],array);
// apply function with test (should fail):
typed(map)(["1",2,3],addOne);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment