findIndex.js

  1. 'use strict';
  2. const { Each } = require('./each');
  3. const { setShorthand } = require('./internal/collection');
  4. class FindIndex extends Each {
  5. constructor(collection, iterator) {
  6. super(collection, iterator, set);
  7. this._result = -1;
  8. }
  9. _callResolve(value, index) {
  10. if (value) {
  11. this._size = 0;
  12. this._promise._resolve(index);
  13. } else if (--this._rest === 0) {
  14. this._promise._resolve(-1);
  15. }
  16. }
  17. }
  18. module.exports = { findIndex, FindIndex };
  19. function set(collection) {
  20. setShorthand.call(this, collection);
  21. if (this._keys !== undefined) {
  22. this._rest = 0;
  23. }
  24. return this;
  25. }
  26. /**
  27. * `Aigle.findIndex` is like `Aigle.find`, it will return the index of the first element which the iterator returns truthy.
  28. * @param {Array} collection
  29. * @param {Function|Array|Object|string} iterator
  30. * @return {Aigle} Returns an Aigle instance
  31. * @example
  32. * const order = [];
  33. * const collection = [1, 4, 2];
  34. * const iterator = num => {
  35. * return Aigle.delay(num * 10)
  36. * .then(() => {
  37. * order.push(num);
  38. * return num % 2 === 0;
  39. * });
  40. * };
  41. * Aigle.findIndex(collection, iterator)
  42. * .then(index => {
  43. * console.log(index); // 2
  44. * console.log(order); // [1, 2]
  45. * });
  46. *
  47. * @example
  48. * const order = [];
  49. * const collection = [1, 4, 2];
  50. * const iterator = num => {
  51. * return Aigle.delay(num * 10)
  52. * .then(() => {
  53. * order.push(num);
  54. * return false;
  55. * });
  56. * };
  57. * Aigle.findIndex(collection, iterator)
  58. * .then(index => {
  59. * console.log(index); // -1
  60. * console.log(order); // [1, 2, 4]
  61. * });
  62. *
  63. * @example
  64. * const collection = [{
  65. * name: 'bargey', active: false
  66. * }, {
  67. * name: 'fread', active: true
  68. * }];
  69. * Aigle.findIndex(collection, 'active')
  70. * .then(index => {
  71. * console.log(index); // 1
  72. * });
  73. *
  74. * @example
  75. * const collection = [{
  76. * name: 'bargey', active: false
  77. * }, {
  78. * name: 'fread', active: true
  79. * }];
  80. * Aigle.findIndex(collection, ['name', 'fread'])
  81. * .then(index => {
  82. * console.log(index); // true
  83. * });
  84. *
  85. * @example
  86. * const collection = [{
  87. * name: 'bargey', active: false
  88. * }, {
  89. * name: 'fread', active: true
  90. * }];
  91. * Aigle.find(collection, { name: 'fread', active: true })
  92. * .then(index => {
  93. * console.log(index); // 1
  94. * });
  95. */
  96. function findIndex(collection, iterator) {
  97. return new FindIndex(collection, iterator)._execute();
  98. }