Last active
April 7, 2023 08:51
-
-
Save bitsmanent/71096c3eb4fff3fc54a1bd1944f06f82 to your computer and use it in GitHub Desktop.
interfaces.js
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
/* quick-and-dirty */ | |
const Types = { | |
string: x => typeof x == "string", | |
number: x => typeof x == "number" | |
}; | |
const Interface = model => { | |
const check = scope => { | |
let fails = 0; | |
Object.keys(model).forEach(prop => { | |
if(scope[prop] === undefined) { | |
console.error(`${prop}: field is required`); | |
++fails; | |
} | |
}); | |
return fails; | |
}; | |
const newscope = () => { | |
return new Proxy({}, { | |
set(target, prop, value) { | |
const type = model[prop]; | |
const typecheck = type ? Types[type] : null; | |
if(type) { | |
if(!typecheck) | |
console.warn(`${type}: unknown type`); | |
else if(!typecheck(value)) | |
console.error(`${prop}: expect a ${type}`); | |
} | |
target[prop] = value; | |
return true; | |
} | |
}); | |
}; | |
const concretizes = fn => { | |
const scope = newscope(); | |
fn(scope); | |
return check(scope) ? null : scope; | |
} | |
return concretizes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage