all files / util/ PathObject.js

59.38% Statements 19/32
58.33% Branches 14/24
71.43% Functions 5/7
59.38% Lines 19/32
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100                                    94× 93×                 111× 109×                               43×     43×     43×     43×     43×       52×     52×     52×         16×   16× 15×                                        
import isString from './isString'
import isArray from './isArray'
import { get, setWith, unset } from 'lodash-es'
 
/*
  An object that can be access via path API.
 
  @example
 
  var obj = new PathObject({a: "aVal", b: {b1: 'b1Val', b2: 'b2Val'}})
*/
 
class PathObject {
 
  /*
    @param {object} [root] An object to operate on
  */
  constructor(root) {
    if (root) {
      this.__root__ = root
    }
  }
 
  contains(id) {
    return Boolean(this.getRoot()[id])
  }
 
  getRoot() {
    if (this.__root__) {
      return this.__root__
    } else {
      return this
    }
  }
 
  /**
    Get value at path
 
    @return {object} The value stored for a given path
 
    @example
 
    obj.get(['b', 'b1'])
    => b1Val
  */
  get(path) {
    Iif (!path) {
      return undefined
    }
    Iif (isString(path)) {
      return this.getRoot()[path]
    }
    Iif (arguments.length > 1) {
      path = Array.prototype.slice(arguments, 0)
    }
    Iif (!isArray(path)) {
      throw new Error('Illegal argument for PathObject.get()')
    }
    return get(this.getRoot(), path)
  }
 
  set(path, value) {
    Iif (!path) {
      throw new Error('Illegal argument: PathObject.set(>path<, value) - path is mandatory.')
    }
    Iif (isString(path)) {
      this.getRoot()[path] = value
    } else {
      setWith(this.getRoot(), path, value)
    }
  }
 
  delete(path) {
    Iif (isString(path)) {
      delete this.getRoot()[path]
    } else if (path.length === 1) {
      delete this.getRoot()[path[0]]
    } else {
      var success = unset(this.getRoot(), path)
      Iif (!success) {
        throw new Error('Could not delete property at path' + path)
      }
    }
  }
 
  clear() {
    var root = this.getRoot()
    for (var key in root) {
      if (root.hasOwnProperty(key)) {
        delete root[key]
      }
    }
  }
 
}
 
PathObject.prototype._isPathObject = true
 
export default PathObject