omnibelt/dot-path-or.js

  1. const useWith = require('ramda/src/useWith');
  2. const identity = require('ramda/src/identity');
  3. const pathOr = require('ramda/src/pathOr');
  4. const split = require('ramda/src/split');
  5. /**
  6. * If the given, non-null object has a value at the given dot-separated path, returns the
  7. * value at that path. Otherwise returns the provided default value. Path can be composed
  8. * of any combination of prop names and/or array indices.
  9. *
  10. * @see dotPath
  11. *
  12. * @signature a -> String -> Object<a> -> a
  13. *
  14. * @example
  15. * dotPathOr('N/A', 'a.b', { a: { b: 1 } }); // => 1
  16. * dotPathOr('N/A', 'invalid.key', { a: 1 }); // => 'N/A'
  17. * dotPathOr('N/A', 'a.b.0', { a: { b: [1, 2, 3] } }); // => 1
  18. * dotPathOr('N/A', 'a.b.0', { a: { b: 'not an arrray' } }); // => 'N/A'
  19. */
  20. const dotPathOr = useWith(pathOr, [identity, split('.'), identity]);
  21. module.exports = dotPathOr;