Skip to content

Commit

Permalink
Handle non-trees gracefully
Browse files Browse the repository at this point in the history
  • Loading branch information
papb committed Sep 19, 2020
1 parent f856ccb commit 31e345c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
7 changes: 4 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ console.log(newTree);

#### tree

Type: Array or plain object
Type: Anything

The tree to be copied and modified.
If it is indeed a tree (i.e. an array or plain object), it will be copied and modified with the shortcut. Otherwise, it will be returned unchanged.

#### shortcutTriggerProp

Expand All @@ -96,9 +96,10 @@ The name of the new prop to replace the `shortcutTriggerProp` in the parent obje

The `treeShortcut(tree, shortcutTriggerProp, shortcutTargetProp, shortcutName)` will do the following:

* If it is not an array nor a plain object, just return the input. Otherwise:
* Shallow-clone the `tree` object/array
* For each (shallow) property in the `tree`:
* If its value is not an object (nor an array), do nothing;
* If its value is not a plain object (nor an array), do nothing;
* Otherwise:
* If its name is `shortcutTriggerProp`:
* Change the property name to `shortcutName`
Expand Down
2 changes: 1 addition & 1 deletion source/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function treeShortcutHelper(tree: any, from: string, to: string, name: string):
}

export function treeShortcut<
Tree extends AnyArray | AnyPlainObject,
Tree,
ShortcutTriggerProp extends string,
ShortcutTargetProp extends string,
ShortcutName extends string,
Expand Down
23 changes: 23 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,26 @@ test('Does not mess with non-plain objects', t => {
expected,
);
});

test('Leaves non-trees untouched', t => {
expectTypeOf<TreeShortcut<Date, 'foo', 'bar', 'baz'>>()
.toEqualTypeOf<Date>();

expectTypeOf<TreeShortcut<number, 'foo', 'bar', 'baz'>>()
.toEqualTypeOf<number>();

expectTypeOf<TreeShortcut<null, 'foo', 'bar', 'baz'>>()
.toEqualTypeOf<null>();

expectTypeOf<TreeShortcut<undefined, 'foo', 'bar', 'baz'>>()
.toEqualTypeOf<undefined>();

const date = new Date();
t.is(treeShortcut(date, 'a', 'b', 'c'), date);

t.is(treeShortcut(true, 'a', 'b', 'c'), true);
t.is(treeShortcut(null, 'a', 'b', 'c'), null);
t.is(treeShortcut(undefined, 'a', 'b', 'c'), undefined);
t.is(treeShortcut(0, 'a', 'b', 'c'), 0);
t.is(treeShortcut('hello', 'a', 'b', 'c'), 'hello');
});

0 comments on commit 31e345c

Please sign in to comment.