Last active
June 22, 2018 20:44
-
-
Save wshager/9e8bb195f249e5c9dc2a1383baf554f7 to your computer and use it in GitHub Desktop.
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
// 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