hasIncludedChildren.js 854 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. /**
  3. * Creates an object that precomputes whether a given path has child fields in
  4. * the projection.
  5. *
  6. * #### Example:
  7. *
  8. * const res = hasIncludedChildren({ 'a.b.c': 0 });
  9. * res.a; // 1
  10. * res['a.b']; // 1
  11. * res['a.b.c']; // 1
  12. * res['a.c']; // undefined
  13. *
  14. * @param {Object} fields
  15. * @api private
  16. */
  17. module.exports = function hasIncludedChildren(fields) {
  18. const hasIncludedChildren = {};
  19. const keys = Object.keys(fields);
  20. for (const key of keys) {
  21. if (key.indexOf('.') === -1) {
  22. hasIncludedChildren[key] = 1;
  23. continue;
  24. }
  25. const parts = key.split('.');
  26. let c = parts[0];
  27. for (let i = 0; i < parts.length; ++i) {
  28. hasIncludedChildren[c] = 1;
  29. if (i + 1 < parts.length) {
  30. c = c + '.' + parts[i + 1];
  31. }
  32. }
  33. }
  34. return hasIncludedChildren;
  35. };