This repository has been archived by the owner on Dec 15, 2021. It is now read-only.
-
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.
feat(assocPath): Add module assocPath
- Loading branch information
Showing
3 changed files
with
51 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,13 @@ | ||
import assocPath from '../assocPath'; | ||
|
||
test('Core.assocPath', () => { | ||
const origin = { a: 1, b: 2 }; | ||
const result = assocPath(['a'], 2, origin); | ||
expect(result).toEqual({ a: 2, b: 2 }); | ||
expect(result).not.toBe(origin); | ||
|
||
expect(assocPath(['a', 0], 1, { a: [0] })).toEqual({ a: [1] }); | ||
expect(assocPath(['a', 'b', 'c'], 'hidden', {})).toEqual({ | ||
a: { b: { c: 'hidden' } }, | ||
}); | ||
}); |
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,36 @@ | ||
import length from './length'; | ||
import slice from './slice'; | ||
import head from './head'; | ||
import prop from './prop'; | ||
import isNil from './isNil'; | ||
import isArray from './isArray'; | ||
import isNumber from './isNumber'; | ||
import has from './has'; | ||
import assoc from './assoc'; | ||
|
||
const assocPath = (path, value, obj) => { | ||
if (length(path) < 1) return value; | ||
|
||
const idx = head(path); | ||
const nextPath = slice(1, Infinity, path); | ||
let val = value; | ||
|
||
if (length(path) > 0) { | ||
const nextObj = | ||
!isNil(obj) && has(idx, obj) // eslint-disable-line no-nested-ternary | ||
? prop(idx, obj) | ||
: isNumber(path[1]) ? [] : {}; | ||
|
||
val = assocPath(nextPath, val, nextObj); | ||
} | ||
|
||
if (isNumber(idx) && isArray(obj)) { | ||
const arr = [...obj]; | ||
arr[idx] = val; | ||
return arr; | ||
} | ||
|
||
return assoc(idx, val, obj); | ||
}; | ||
|
||
export default assocPath; |
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