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

Commit

Permalink
fix(assocPath): Fix nested arrays and objects
Browse files Browse the repository at this point in the history
  • Loading branch information
adambrgmn committed Jan 16, 2018
1 parent 5409638 commit 1a2e7ff
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 12 deletions.
40 changes: 38 additions & 2 deletions src/__tests__/assocPath.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,49 @@
import assocPath from '../assocPath';

test('Core.assocPath', () => {
const origin = { a: 1, b: 2 };
const origin = { a: 1, b: { c: 1 } };
const result = assocPath(['a'], 2, origin);
expect(result).toEqual({ a: 2, b: 2 });
expect(result).toEqual({ a: 2, b: { c: 1 } });
expect(result).not.toBe(origin);
expect(result.b).toBe(origin.b);

expect(assocPath(['a', 0], 1, { a: [0] })).toEqual({ a: [1] });
expect(assocPath([], 0, {})).toBe(0);
expect(assocPath(['a', 'b', 'c'], 'hidden', {})).toEqual({
a: { b: { c: 'hidden' } },
});

expect(assocPath(['a', 1, 'b'], 'foo', { a: [null, { b: 'bar' }] })).toEqual({
a: [null, { b: 'foo' }],
});

{
const obj1 = {
a: { b: 1, c: 2, d: { e: 3 } },
f: { g: { h: 4, i: [5, 6, 7], j: { k: 6, l: 7 } } },
m: 8,
};
const obj2 = assocPath(['f', 'g', 'i', 1], 42, obj1);
expect(obj2.f.g.i).toEqual([5, 42, 7]);
}

{
const obj1 = { a: 1, b: { c: 2, d: 3 }, e: 4, f: 5 };
const obj2 = assocPath(['x', 0, 'y'], 42, obj1);
expect(obj2).toEqual({
a: 1,
b: { c: 2, d: 3 },
e: 4,
f: 5,
x: [{ y: 42 }],
});
}

expect(assocPath(['foo', 'bar', 'baz'], 42, { foo: undefined })).toEqual({
foo: { bar: { baz: 42 } },
});

expect(assocPath(['foo', 'bar', 'baz'], 42, { foo: null })).toEqual({
foo: { bar: { baz: 42 } },
});
});
20 changes: 10 additions & 10 deletions src/assocPath.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import length from './length';
import slice from './slice';
import assoc from './assoc';
import has from './has';
import head from './head';
import prop from './prop';
import isNil from './isNil';
import isArray from './isArray';
import isNil from './isNil';
import isNumber from './isNumber';
import has from './has';
import assoc from './assoc';
import length from './length';
import prop from './prop';
import slice from './slice';

const assocPath = (path, value, obj) => {
if (length(path) < 1) return value;

const idx = head(path);
const nextPath = slice(1, Infinity, path);
let val = value;
const idx = head(path);

if (length(path) > 0) {
if (length(path) > 1) {
const nextPath = slice(1, Infinity, path);
const nextObj =
!isNil(obj) && has(idx, obj) // eslint-disable-line no-nested-ternary
? prop(idx, obj)
: isNumber(path[1]) ? [] : {};
: isNumber(head(nextPath)) ? [] : {};

val = assocPath(nextPath, val, nextObj);
}
Expand Down

0 comments on commit 1a2e7ff

Please sign in to comment.