hasIncludedChildren.js 805 B

123456789101112131415161718192021222324252627282930313233343536
  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. * const res = hasIncludedChildren({ 'a.b.c': 0 });
  8. * res.a; // 1
  9. * res['a.b']; // 1
  10. * res['a.b.c']; // 1
  11. * res['a.c']; // undefined
  12. */
  13. module.exports = function hasIncludedChildren(fields) {
  14. const hasIncludedChildren = {};
  15. const keys = Object.keys(fields);
  16. for (const key of keys) {
  17. if (key.indexOf('.') === -1) {
  18. hasIncludedChildren[key] = 1;
  19. continue;
  20. }
  21. const parts = key.split('.');
  22. let c = parts[0];
  23. for (let i = 0; i < parts.length; ++i) {
  24. hasIncludedChildren[c] = 1;
  25. if (i + 1 < parts.length) {
  26. c = c + '.' + parts[i + 1];
  27. }
  28. }
  29. }
  30. return hasIncludedChildren;
  31. };