-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import flatten from './flatten'; | ||
|
||
describe('flatten', () => { | ||
it('flattens the given object', () => { | ||
const nestedObject = { | ||
hello: { | ||
yes: 'true', | ||
}, | ||
flat: 'yes', | ||
nested: { | ||
array: [1, 2], | ||
}, | ||
}; | ||
|
||
const result = flatten(nestedObject); | ||
|
||
expect(result).toEqual({ | ||
'hello.yes': 'true', | ||
flat: 'yes', | ||
'nested.array': [1, 2], | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
function _flatten<Result extends object>( | ||
obj: Record<string, unknown>, | ||
recursiveContext?: { parentKey: string; result: Result } | ||
): Result { | ||
const initialResult = recursiveContext?.result ?? ({} as unknown as Result); | ||
const parentKey = recursiveContext?.parentKey; | ||
|
||
return Object.entries(obj).reduce<Result>((acc, [key, value]) => { | ||
const newKey = parentKey != null ? `${parentKey}.${key}` : key; | ||
if (typeof value !== 'object') return { ...acc, [newKey]: value }; | ||
if (Array.isArray(value)) return { ...acc, [newKey]: value }; | ||
|
||
return _flatten(value as Record<string, unknown>, { | ||
parentKey: newKey, | ||
result: acc, | ||
}); | ||
}, initialResult); | ||
} | ||
|
||
function flatten<Result extends object>(obj: Record<string, unknown>): Result { | ||
return _flatten(obj); | ||
} | ||
|
||
export default flatten; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from './omit'; | ||
export * from './omitBy'; | ||
export * from './flatten'; |