Skip to content

Commit

Permalink
Merge pull request #5 from guillotinaweb/issue-ONNA-1563
Browse files Browse the repository at this point in the history
Don't overwrite full object on Update
  • Loading branch information
Mathilde Pellerin authored Oct 3, 2019
2 parents 0346d34 + 26ed289 commit 11bdeca
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 1.0.4 (2019-10-03)

- Don't overwrite full object on Update

# 1.0.3 (2019-09-30)

- Prevent pending contexts to be sent by TraverseTo selector
Expand Down
2 changes: 1 addition & 1 deletion projects/ngx-state-traverser/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ngx-state-traverser",
"version": "1.0.3",
"version": "1.0.4",
"peerDependencies": {
"@angular/common": "^8.1.1",
"@angular/core": "^8.1.1",
Expand Down
32 changes: 31 additions & 1 deletion projects/ngx-state-traverser/src/lib/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
import { initialState, TraversingState } from './state';
import { TraverserActions } from './actions';

/**
* Performs a deep merge of `source` into `target`.
* Mutates `target` only but not its objects and arrays.
*
* @author inspired by [jhildenbiddle](https://stackoverflow.com/a/48218209).
* @source https://gist.github.com/ahtcx/0cd94e62691f539160b32ecda18af3d6#gistcomment-2930530
*/
function mergeDeep(target, source) {
const isObject = (obj) => obj && typeof obj === 'object';

if (!isObject(target) || !isObject(source)) {
return source;
}

Object.keys(source).forEach(key => {
const targetValue = target[key];
const sourceValue = source[key];

if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
target[key] = targetValue.concat(sourceValue);
} else if (isObject(targetValue) && isObject(sourceValue)) {
target[key] = mergeDeep(Object.assign({}, targetValue), sourceValue);
} else {
target[key] = sourceValue;
}
});

return target;
}

export function reducer(state = initialState, action: TraverserActions.Actions): TraversingState {
switch (action.type) {
case TraverserActions.Types.ResolveContext: {
Expand Down Expand Up @@ -48,7 +78,7 @@ export function reducer(state = initialState, action: TraverserActions.Actions):
...state,
collection: {
...state.collection,
[action.payload.path]: {...state.collection[action.payload.path], ...action.payload.changes},
[action.payload.path]: mergeDeep({...state.collection[action.payload.path]}, action.payload.changes),
}
};
}
Expand Down

0 comments on commit 11bdeca

Please sign in to comment.