-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathgetSubtree.ts
More file actions
64 lines (60 loc) · 1.8 KB
/
getSubtree.ts
File metadata and controls
64 lines (60 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { Dictionary, DictionaryEntry } from '../types/types';
import { get, set } from './indexDict';
/**
* @description A function that gets a subtree from a dictionary
* @param dictionary - dictionary to get the subtree from
* @param id - id of the subtree to get
* @returns
*/
export function getSubtree<T extends Dictionary>({
dictionary,
id,
}: {
dictionary: T;
id: string;
}): Dictionary | DictionaryEntry | undefined {
if (id === '') {
return dictionary;
}
let current: Dictionary | DictionaryEntry = dictionary;
const dictionaryPath = id.split('.');
for (const key of dictionaryPath) {
current = get(current as Dictionary, key);
}
return current;
}
/**
* @description A function that gets a subtree from a dictionary
* @param dictionary - new dictionary to get the subtree from
* @param id - id of the subtree to get
* @param sourceDictionary - source dictionary to model off of
* @returns
*/
export function getSubtreeWithCreation<T extends Dictionary>({
dictionary,
id,
sourceDictionary,
}: {
dictionary: T;
id: string;
sourceDictionary: T;
}): Dictionary | DictionaryEntry | undefined {
if (id === '') {
return dictionary;
}
let current: Dictionary | DictionaryEntry = dictionary;
const sourceCurrent: Dictionary | DictionaryEntry = sourceDictionary;
const dictionaryPath = id.split('.');
for (const key of dictionaryPath) {
if (get(current as Dictionary, key) === undefined) {
// We know this wont be type Dictionary because we should have already checked for that
if (Array.isArray(get(sourceCurrent as Dictionary, key))) {
set(current as Dictionary, key, [] as Dictionary);
} else {
set(current as Dictionary, key, {} as Dictionary);
}
}
current = get(current as Dictionary, key);
}
return current;
}