array-iteration-from-last.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. var bind = require('../internals/function-bind-context');
  2. var IndexedObject = require('../internals/indexed-object');
  3. var toObject = require('../internals/to-object');
  4. var lengthOfArrayLike = require('../internals/length-of-array-like');
  5. // `Array.prototype.{ findLast, findLastIndex }` methods implementation
  6. var createMethod = function (TYPE) {
  7. var IS_FIND_LAST_INDEX = TYPE == 1;
  8. return function ($this, callbackfn, that) {
  9. var O = toObject($this);
  10. var self = IndexedObject(O);
  11. var boundFunction = bind(callbackfn, that);
  12. var index = lengthOfArrayLike(self);
  13. var value, result;
  14. while (index-- > 0) {
  15. value = self[index];
  16. result = boundFunction(value, index, O);
  17. if (result) switch (TYPE) {
  18. case 0: return value; // findLast
  19. case 1: return index; // findLastIndex
  20. }
  21. }
  22. return IS_FIND_LAST_INDEX ? -1 : undefined;
  23. };
  24. };
  25. module.exports = {
  26. // `Array.prototype.findLast` method
  27. // https://github.com/tc39/proposal-array-find-from-last
  28. findLast: createMethod(0),
  29. // `Array.prototype.findLastIndex` method
  30. // https://github.com/tc39/proposal-array-find-from-last
  31. findLastIndex: createMethod(1)
  32. };