diff --git a/striker-ui-api/src/lib/traverse.ts b/striker-ui-api/src/lib/traverse.ts new file mode 100644 index 00000000..994fefb1 --- /dev/null +++ b/striker-ui-api/src/lib/traverse.ts @@ -0,0 +1,28 @@ +type NestedObject = { + [key: number | string]: NestedObject | T; +}; + +export const traverse = , V = unknown>( + obj: O, + init: T, + onKey: (previous: T, obj: O, key: string) => { is: boolean; next: O }, + { + onEnd, + previous = init, + }: { + onEnd?: (previous: T, obj: O, key: string) => void; + previous?: T; + } = {}, +) => { + Object.keys(obj).forEach((key: string) => { + const { is: proceed, next } = onKey(previous, obj, key); + + if (proceed) { + traverse(next, init, onKey, { previous }); + } else { + onEnd?.call(null, previous, obj, key); + } + }); + + return previous; +};