Skip to content
This repository has been archived by the owner on Dec 15, 2021. It is now read-only.

Commit

Permalink
feat(assocPath): Add module assocPath
Browse files Browse the repository at this point in the history
  • Loading branch information
adambrgmn committed Jan 16, 2018
1 parent 8ec319d commit 5409638
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/__tests__/assocPath.js
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' } },
});
});
36 changes: 36 additions & 0 deletions src/assocPath.js
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;
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import allPass from './allPass';
import anyPass from './anyPass';
import append from './append';
import assoc from './assoc';
import assocPath from './assocPath';
import compose from './compose';
import concat from './concat';
import curry from './curry';
Expand Down Expand Up @@ -34,6 +35,7 @@ export {
anyPass,
append,
assoc,
assocPath,
compose,
concat,
curry,
Expand Down

0 comments on commit 5409638

Please sign in to comment.