Skip to content

Commit

Permalink
feat(del): add del function
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Hamilton committed Nov 30, 2018
1 parent 3113bf9 commit e66037b
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/del.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// o
import is from './is';
import empty from './empty';
import clone from './clone';
import { getPathParts } from './internals';

/**
* Delete the specified path from the object
*
* @param {object} object The object to delete from
* @param {string} path The path to delete
*
* @returns {object} The result object
*/
function del(object, path) {
// check if the object is an object and isn't empty
if (is(object) && !empty(object)) {
// clone the object
let cloned = clone(object);

// set the new value for the cloned object so we
// can manipulate it
const result = cloned;

// get the path parts
const pathParts = getPathParts(path);

// loop over all the path parts
for (let index = 0; index < pathParts.length; index += 1) {
// get the current key
const key = pathParts[index];

// check if the current path is the last key
if (index === pathParts.length - 1) {
// if it is the last key delete the value from the object
delete cloned[key];
}

// set the modified values to the object
cloned = cloned[key];
}

// return the result
return result;
}

// if the object isn't an object or is empty return
// an empty object this will keep the return immutable
return {};
}

export default del;

0 comments on commit e66037b

Please # to comment.