Skip to content

Instantly share code, notes, and snippets.

@gapurov
Created February 24, 2023 14:32
Show Gist options
  • Save gapurov/b19c950cc5e5db4b69ec99939e216c26 to your computer and use it in GitHub Desktop.
Save gapurov/b19c950cc5e5db4b69ec99939e216c26 to your computer and use it in GitHub Desktop.
Functionality to migrate props
const transformObj = (obj, predicate) => {
return Object.keys(obj).reduce((acc, key) => {
if (predicate(obj[key], key)) {
acc[key] = obj[key];
}
return acc;
}, {});
};
type Topic = Record<string, string | number | boolean>;
// pass list of props to be removed
const removeProps = (propsToRemove: string[]) => (obj: Topic) =>
transformObj(obj, (_, key) => !propsToRemove.includes(key));
const adjustProps = (props: Topic) => ({
// rename showInAgenda to hideInAgenda props if prop exists
...(props.showInAgenda !== undefined
? { hideInAgenda: !props.showInAgenda }
: {}),
...props,
});
const pipe =
(...fns: Function[]) =>
(t: Topic) =>
fns.reduce((v, f) => f(v), t);
// this function renames 'showInAgenda' to 'hideInAgenda' and removes
// 'showInAgenda' and 'anotherPropToRemove'
export const migrate = (topic: Topic) =>
pipe(
adjustProps,
removeProps(['showInAgenda', 'anotherPropToRemove'])
)(topic);
//
// usage:
//
migrate({
id: '1',
title: 'Example Title',
description: 'Example Description',
showInAgenda: true,
anotherPropToRemove: true,
});
//
// returns:
//
// {
// id: "1",
// title: "Example Title",
// description: "Example Description",
// hideInAgenda: false,
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment