all files / scour/utilities/ del.js

100% Statements 18/18
100% Branches 8/8
100% Functions 1/1
100% Lines 18/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42                          14×           11×            
'use strict'
 
const clone = require('./clone')
const cloneWithout = require('./clone_without')
 
/**
 * Deletes a `keypath` from an `object` immutably.
 *
 *     data = { users: { bob: { name: 'robert' } } }
 *     result = del(data, ['users', 'bob', 'name'])
 *
 *     result = { users: { bob: {} } }
 */
 
module.exports = function del (object, keypath) {
  let results = {}
  let parents = {}
 
  for (let i = 0, len = keypath.length; i < len; i++) {
    if (i === 0) {
      parents[i] = object
    } else {
      parents[i] = parents[i - 1][keypath[i - 1]]
      if (!parents[i] || typeof parents[i] !== 'object') {
        return object
      }
    }
  }
 
  for (let i = keypath.length - 1; i >= 0; i--) {
    if (i === keypath.length - 1) {
      results[i] = cloneWithout(parents[i], keypath[i])
      delete results[i][keypath[i]]
    } else {
      results[i] = clone(parents[i])
      results[i][keypath[i]] = results[i + 1]
    }
  }
 
  return results[0]
}