Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active February 15, 2017 16:33
Show Gist options
  • Save ryasmi/fb6372741fdf03f9c97c3901fe0914df to your computer and use it in GitHub Desktop.
Save ryasmi/fb6372741fdf03f9c97c3901fe0914df to your computer and use it in GitHub Desktop.
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);
@ryasmi
Copy link
Author

ryasmi commented Dec 31, 2016

modifySchema({
  foo: defaultValue('hello')
})({}, [])
// Object {foo: "hello"}

modifySchema({
  foo: defaultValue('hello')
})({foo: 'bar'}, [])
// Object {foo: "bar"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment