You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.6 KiB

4 years ago
  1. 'use strict';
  2. var values = require('../helpers/values');
  3. var nestedValue = require('../helpers/nestedValue');
  4. module.exports = function where(key, operator, value) {
  5. var comparisonOperator = operator;
  6. var comparisonValue = value;
  7. var items = values(this.items);
  8. if (operator === undefined || operator === true) {
  9. return new this.constructor(items.filter(function (item) {
  10. return nestedValue(item, key);
  11. }));
  12. }
  13. if (operator === false) {
  14. return new this.constructor(items.filter(function (item) {
  15. return !nestedValue(item, key);
  16. }));
  17. }
  18. if (value === undefined) {
  19. comparisonValue = operator;
  20. comparisonOperator = '===';
  21. }
  22. var collection = items.filter(function (item) {
  23. switch (comparisonOperator) {
  24. case '==':
  25. return nestedValue(item, key) === Number(comparisonValue) || nestedValue(item, key) === comparisonValue.toString();
  26. default:
  27. case '===':
  28. return nestedValue(item, key) === comparisonValue;
  29. case '!=':
  30. case '<>':
  31. return nestedValue(item, key) !== Number(comparisonValue) && nestedValue(item, key) !== comparisonValue.toString();
  32. case '!==':
  33. return nestedValue(item, key) !== comparisonValue;
  34. case '<':
  35. return nestedValue(item, key) < comparisonValue;
  36. case '<=':
  37. return nestedValue(item, key) <= comparisonValue;
  38. case '>':
  39. return nestedValue(item, key) > comparisonValue;
  40. case '>=':
  41. return nestedValue(item, key) >= comparisonValue;
  42. }
  43. });
  44. return new this.constructor(collection);
  45. };