array-includes.js 1.3 KB

1234567891011121314151617181920212223242526272829303132
  1. var toIndexedObject = require('../internals/to-indexed-object');
  2. var toAbsoluteIndex = require('../internals/to-absolute-index');
  3. var lengthOfArrayLike = require('../internals/length-of-array-like');
  4. // `Array.prototype.{ indexOf, includes }` methods implementation
  5. var createMethod = function (IS_INCLUDES) {
  6. return function ($this, el, fromIndex) {
  7. var O = toIndexedObject($this);
  8. var length = lengthOfArrayLike(O);
  9. var index = toAbsoluteIndex(fromIndex, length);
  10. var value;
  11. // Array#includes uses SameValueZero equality algorithm
  12. // eslint-disable-next-line no-self-compare -- NaN check
  13. if (IS_INCLUDES && el != el) while (length > index) {
  14. value = O[index++];
  15. // eslint-disable-next-line no-self-compare -- NaN check
  16. if (value != value) return true;
  17. // Array#indexOf ignores holes, Array#includes - not
  18. } else for (;length > index; index++) {
  19. if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
  20. } return !IS_INCLUDES && -1;
  21. };
  22. };
  23. module.exports = {
  24. // `Array.prototype.includes` method
  25. // https://tc39.es/ecma262/#sec-array.prototype.includes
  26. includes: createMethod(true),
  27. // `Array.prototype.indexOf` method
  28. // https://tc39.es/ecma262/#sec-array.prototype.indexof
  29. indexOf: createMethod(false)
  30. };