Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

skava / chain-able-deps   js

Repository URL to install this package:

Version: 6.0.4 

/ src / dot / get.ts

import { AnyArrayOrObj } from '../_typings'
import { isEnumerable, isNullOrUndefined, isUndefined } from '../is'
import lengthMinusOne from '../util/lengthMinusOne'
import getPathSegments from './segments'
import isDottable from './dottable'

/**
 * @desc dot-prop get at path
 * @namespace dot
 * @memberOf dot
 * @since 3.0.0
 *
 * @alias dotGet
 * @alias get
 *
 * @param obj the object to retrieve the nested property from.
 * @param path dot-prop-path to use
 * @param fallback use when there is no value at specified path
 * @return value at path or fallback
 *
 * @func
 * @extends dot/getPathSegments
 *
 * {@link https://github.com/jashkenas/underscore/blob/master/underscore.js#L150 underscore-deep-get}
 * @see {@link underscore-deep-get}
 *
 * @example
 *
 *    dot.get({a: {b: 2}}, 'a.b')      //=> 2
 *    dot.get({a: {b: 2}}, ['a', 'b']) //=> 2
 *    dot.get({c: {b: 2}}, ['a', 'b']) //=> undefined
 *
 */
export default <Value = any>(obj: AnyArrayOrObj, path: string | string[], fallback: Value): Value | AnyArrayOrObj => {
  // if (pathArray.length === 1 && hasOwnProperty(dot, path[0]))
  //   return dot[path[0]]
  // else if (isString(path) && path.includes('.') === false && hasOwnProperty(dot, path))
  //   return dot[path]

  if (!isDottable(obj, path)) {
    return isUndefined(fallback) ? obj : fallback
  }

  const pathArray = getPathSegments(path)

  for (let i = 0; i < pathArray.length; i++) {
    if (!isEnumerable(obj, pathArray[i])) {
      return fallback
    }

    obj = obj[pathArray[i]]

    if (isNullOrUndefined(obj)) {
      /*
       * `obj` is either `undefined` or `null` so we want to stop the loop, and
       * if this is not the last bit of the path, and
       * if it did't return `undefined`
       * it would return `null` if `obj` is `null`
       * but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied fallback, not `null`
       */
      if (i !== lengthMinusOne(pathArray)) {
        return fallback
      }

      break
    }
  }

  return obj
}