Last active
February 15, 2017 16:33
-
-
Save ryasmi/fb6372741fdf03f9c97c3901fe0914df to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export type Path = string[]; | |
export type Modifier = (data: any, path: Path) => any; | |
export type Schema = { [key: string]: Modifier }; | |
export const defaultValue = (value: any): Modifier => | |
(data) => | |
data === undefined ? value : data; | |
export const overrideValue = (value: any): Modifier => () => value; | |
export const modifyType = (type: any, modifier: Modifier): Modifier => | |
(data, path) => ( | |
data !== undefined && data !== null && data.constructor === type ? | |
modifier(data, path) : | |
data | |
); | |
export const modifySchema = (schema: Schema) => | |
modifyType(Object, (data, path) => | |
Object.keys(schema).reduce((newData, key) => ({ | |
...newData, | |
[key]: schema[key](data[key], [...path, key]), | |
}), {}) | |
); | |
export const modifyCollection = (modifier: (index: number) => Modifier) => | |
modifyType(Array, (data, path) => | |
data.map((elem: any, index: number) => | |
modifier(index)(elem, [...path, index.toString()]) | |
) | |
); | |
export const composeModifiers = (modifiers: Modifier[]): Modifier => | |
(data, path) => | |
modifiers.reduce((result: any, modifier: Modifier) => | |
modifier(result, path) | |
, data); |
Author
ryasmi
commented
Dec 31, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment