PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/lodash/object/result.js

http://github.com/DarthFubuMVC/fubumvc
JavaScript | 49 lines | 19 code | 2 blank | 28 comment | 7 complexity | 62bf6ae32299187cd2426a74e67e1222 MD5 | raw file
Possible License(s): JSON, 0BSD, Apache-2.0, WTFPL, BSD-3-Clause, MIT, BSD-2-Clause
  1. var baseGet = require('../internal/baseGet'),
  2. baseSlice = require('../internal/baseSlice'),
  3. isFunction = require('../lang/isFunction'),
  4. isKey = require('../internal/isKey'),
  5. last = require('../array/last'),
  6. toPath = require('../internal/toPath');
  7. /**
  8. * This method is like `_.get` except that if the resolved value is a function
  9. * it is invoked with the `this` binding of its parent object and its result
  10. * is returned.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @category Object
  15. * @param {Object} object The object to query.
  16. * @param {Array|string} path The path of the property to resolve.
  17. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
  18. * @returns {*} Returns the resolved value.
  19. * @example
  20. *
  21. * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
  22. *
  23. * _.result(object, 'a[0].b.c1');
  24. * // => 3
  25. *
  26. * _.result(object, 'a[0].b.c2');
  27. * // => 4
  28. *
  29. * _.result(object, 'a.b.c', 'default');
  30. * // => 'default'
  31. *
  32. * _.result(object, 'a.b.c', _.constant('default'));
  33. * // => 'default'
  34. */
  35. function result(object, path, defaultValue) {
  36. var result = object == null ? undefined : object[path];
  37. if (result === undefined) {
  38. if (object != null && !isKey(path, object)) {
  39. path = toPath(path);
  40. object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
  41. result = object == null ? undefined : object[last(path)];
  42. }
  43. result = result === undefined ? defaultValue : result;
  44. }
  45. return isFunction(result) ? result.call(object) : result;
  46. }
  47. module.exports = result;