Skip to content

Commit

Permalink
Fix Array.prototype.includes
Browse files Browse the repository at this point in the history
Closes #2823
Closes #2820

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=190108636
  • Loading branch information
teppeis authored and brad4d committed Mar 23, 2018
1 parent bce9c36 commit 29763b4
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 6 deletions.
9 changes: 7 additions & 2 deletions src/com/google/javascript/jscomp/js/es6/array/includes.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,13 @@ $jscomp.polyfill('Array.prototype.includes', function(orig) {
array = /** @type {!IArrayLike} */ (String(array));
}
var len = array.length;
for (var i = opt_fromIndex || 0; i < len; i++) {
if (array[i] == searchElement || Object.is(array[i], searchElement)) {
var i = opt_fromIndex || 0;
if (i < 0) {
i = Math.max(i + len, 0);
}
for (; i < len; i++) {
var element = array[i];
if (element === searchElement || Object.is(element, searchElement)) {
return true;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/com/google/javascript/jscomp/resources.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,46 @@ testSuite({
assertTrue(arr.includes(-0));
assertTrue(arr.includes(1));
assertTrue(arr.includes(NaN));
assertTrue(arr.includes(NaN, 2));
assertTrue(arr.includes(3));
assertTrue(arr.includes(3, 3));
assertFalse(arr.includes(2));
assertFalse(arr.includes(NaN, 3));

assertFalse([1, NaN, 3].includes(0));
assertFalse([1, NaN, 3].includes(-0));
assertFalse([0, 1, 3].includes(NaN));

// fromIndex
assertTrue(arr.includes(3, 3));
assertFalse(arr.includes(3, 4));
assertFalse(arr.includes(3, 5));
assertTrue(arr.includes(3, -1));
assertFalse(arr.includes(0, 1));
assertTrue(arr.includes(0, 0));
assertFalse(arr.includes(0, -1));
assertFalse(arr.includes(0, -3));
assertTrue(arr.includes(0, -4));
assertTrue(arr.includes(0, -5));

// null and undefined
// Make sure the compiler knows both null and undefined are allowed
// to avoid a type error.
arr = /** @type {!Array<null|undefined>} */ ([null]);
assertTrue(arr.includes(null));
assertFalse(arr.includes(undefined));

arr = /** @type {!Array<null|undefined>} */ ([undefined]);
assertTrue(arr.includes(undefined));
assertFalse(arr.includes(null));

// empty slot
arr = Array(1);
assertTrue(arr.includes(undefined));

// string
arr = 'abcABC';
assertTrue(Array.prototype.includes.call(arr, 'a'));
assertFalse(Array.prototype.includes.call(arr, 'd'));

// ArrayLike
arr = {length: 2, 0: 5, 1: 6, 2: 7};
assertTrue(Array.prototype.includes.call(arr, 5));
assertTrue(Array.prototype.includes.call(arr, 6));
Expand Down

0 comments on commit 29763b4

Please sign in to comment.