Fixed map subtraction function + Added test on it

This commit is contained in:
Bruno Lemos
2017-03-16 12:54:40 -03:00
parent c31806c858
commit a469a0d911
3 changed files with 59 additions and 12 deletions

View File

@@ -74,6 +74,9 @@
"whatwg-fetch": "^2.0.3"
},
"jest": {
"preset": "jest-react-native"
"preset": "jest-react-native",
"moduleFileExtensions": ["js"],
"moduleDirectories": ["node_modules", "web/node_modules"],
"testRegex": "<rootDir>/(web/src|src)/.*\\.test\\.js$"
}
}

View File

@@ -159,31 +159,32 @@ export function getObjectFilteredByMap(object, map) {
}
export function getMapSubtractedByMap(mapA, mapB) {
if (mapB === true) return mapA === undefined ? false : mapA;
if (mapB === false) return mapA === undefined ? true : mapA;
if (mapA === undefined) return null;
if (mapB === undefined) return mapA;
if (mapB === true || mapB === false) return mapA === mapB ? null : mapA;
if (!isObjectOrMap(mapA) || !isObjectOrMap(mapB)) return null;
if (sizeOf(mapB) === 0) {
return null;
}
// avoid conflicts, e.g. both mapA and mapB has false items
// this way we avoid end up with both true and false values
if (sizeOf(mapA) > 0 && sizeOf(mapB) > 0) {
return mapA;
}
let newMap = mapA;
let removeAnyField = false;
forEach(mapB, (_value, field) => {
const value = getMapSubtractedByMap(get(mapA, field), get(mapB, field));
if (value === null || (isObjectOrMap(value) && sizeOf(value) === 0)) {
forEach(mapB, (mapBValue, field) => {
const value = getMapSubtractedByMap(get(mapA, field), mapBValue);
if (value === null || value === undefined) {
newMap = remove(newMap, field);
removeAnyField = true;
} else {
newMap = set(newMap, field, value);
}
});
if (removeAnyField && sizeOf(newMap) === 0) {
return null;
}
return newMap;
}

View File

@@ -0,0 +1,43 @@
import { getMapSubtractedByMap } from './helpers';
const mapA = {
a: {},
b: {},
c: undefined,
d: { d: false },
e: { e: false },
f: { f: true },
g: { g: true },
h: { h: true, hh: true },
i: {
i1: {},
i2: { '*': { a: false, b: false } },
},
};
const mapB = {
a: {},
b: undefined,
c: {},
d: { d: false },
e: { e: true },
f: { f: false },
g: { g: true },
h: { h: true },
i: {
i1: {},
i2: { '*': { c: false, d: false } },
},
};
test('It subtracts a map from another map', () => {
expect(getMapSubtractedByMap(mapA, mapB)).toEqual({
b: {},
e: { e: false },
f: { f: true },
h: { hh: true },
i: {
i2: { '*': { a: false, b: false } },
},
});
});