Skip to content

Commit

Permalink
feat: implemented remove() operation
Browse files Browse the repository at this point in the history
  • Loading branch information
andres-kovalev committed Oct 20, 2019
1 parent 07c746d commit b72cf7d
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 11 deletions.
15 changes: 15 additions & 0 deletions src/common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = {
isNumber,
extractSubPath
};

function isNumber(value) {
return !Number.isNaN(+value);
}

function extractSubPath(path) {
return [
path.slice(0, -1),
path[path.length - 1]
];
}
21 changes: 19 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
const update = require('./update');
const set = require('./set');
const remove = require('./remove');

module.exports = {
set,
update
...mapValues({ update, set, remove }, preparePath)
};

function mapValues(object, map) {
return Object.entries(object)
.reduce(
(reduced, [ key, value ]) => Object.assign(reduced, {
[key]: map(value)
}), {}
);
}

function preparePath(fn) {
return (object, path, ...rest) => fn(
object,
Array.isArray(path) ? path : path.split('.'),
...rest
);
}
23 changes: 23 additions & 0 deletions src/remove/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const update = require('../update');
const { isNumber, extractSubPath } = require('../common');

module.exports = remove;

function remove(object, path) {
const [ itemPath, valuePath ] = extractSubPath(path);

return update(object, itemPath, (item) => {
if (Array.isArray(item) && isNumber(valuePath)) {
return item
.slice(0, valuePath)
.concat(item.slice(+valuePath + 1));
}

const {
[valuePath]: temp,
...newItem
} = item;

return newItem;
});
}
12 changes: 3 additions & 9 deletions src/update/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
const { isNumber } = require('../common');

module.exports = update;

function update(object, path, map) {
const pathArray = Array.isArray(path)
? path
: path.split('.');

return doUpdate(object, pathArray, 0, map);
return doUpdate(object, path, 0, map);
}

function doUpdate(object, path, index, map) {
Expand Down Expand Up @@ -34,10 +32,6 @@ function createSource(key) {
return isNumber(key) ? [] : {};
}

function isNumber(value) {
return !Number.isNaN(+value);
}

function setValue(source, key, value) {
if (!Array.isArray(source)) {
return Object.assign({}, source, {
Expand Down

0 comments on commit b72cf7d

Please sign in to comment.