diff options
| author | jw255 | 2018-02-06 22:34:53 +0000 |
|---|---|---|
| committer | jw255 | 2018-02-06 22:34:53 +0000 |
| commit | 1520a13a7144e6a0569f589d3aa5fdddc8136b8c (patch) | |
| tree | 0494a51e42a1491621bdc33e3742e9b0f49619f7 /src/matcher/options.ts | |
| parent | Merge branch 'cjd24/stubsgres' into 'master' (diff) | |
| parent | testing merged with typechecking (diff) | |
| download | medicine-1520a13a7144e6a0569f589d3aa5fdddc8136b8c.tar.gz medicine-1520a13a7144e6a0569f589d3aa5fdddc8136b8c.zip | |
Merge branch ‘testing’
Diffstat (limited to 'src/matcher/options.ts')
| -rw-r--r-- | src/matcher/options.ts | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/matcher/options.ts b/src/matcher/options.ts new file mode 100644 index 0000000..1ffa24e --- /dev/null +++ b/src/matcher/options.ts @@ -0,0 +1,69 @@ +import { default as types } from './types'; + +type matchType<T = any> + = (boolean | ((T) => boolean)); + +export function match(template: Object, value?: Object): matchType<Object> { + if (value === undefined) { + return match.bind(null, template); + } + + for (let k of Object.keys(template)) { + if (!template[k](value[k])) { + return false; + } + } + return true; +} + +export function exact(template: Object, value?: Object): matchType<Object> { + if (value === undefined) { + return exact.bind(null, template); + } + + let k1 = Object.keys(template); + let k2 = Object.keys(value); + + return match(template, value) + && k2.every((x) => k1.indexOf(x) < 0); +} + +export function optional(template: Function, value?: any): matchType<any> { + if (value === undefined) { + return optional.bind(null, template); + } + + return types.undefined(value) + || template(value); +} + +export function alternative(templates: any[], value?: any): matchType<any> { + if (value === undefined) { + return alternative.bind(null, templates); + } + + if (templates.length === 0) { + return false; + } else { + let t = templates.map((x) => { + if (types.function(x)) { + return x; + } else if (types.object(x)) { + return match(x); + } else { + return (v) => x === v; + } + }); + return t.some((x) => x(value)); + } +} + +export function array(template: Object, values?: Array<Object>): +matchType<Array<Object>> { + if (values === undefined) { + return array.bind(null, template); + } + + let m = match(template) as ((Object) => boolean); + return values.every(m); +} |
