parseProjection.js 686 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. /**
  3. * Convert a string or array into a projection object, retaining all
  4. * `-` and `+` paths.
  5. */
  6. module.exports = function parseProjection(v, retainMinusPaths) {
  7. const type = typeof v;
  8. if (type === 'string') {
  9. v = v.split(/\s+/);
  10. }
  11. if (!Array.isArray(v) && Object.prototype.toString.call(v) !== '[object Arguments]') {
  12. return v;
  13. }
  14. const len = v.length;
  15. const ret = {};
  16. for (let i = 0; i < len; ++i) {
  17. let field = v[i];
  18. if (!field) {
  19. continue;
  20. }
  21. const include = '-' == field[0] ? 0 : 1;
  22. if (!retainMinusPaths && include === 0) {
  23. field = field.substring(1);
  24. }
  25. ret[field] = include;
  26. }
  27. return ret;
  28. };