-
Notifications
You must be signed in to change notification settings - Fork 75
/
includes.js
56 lines (53 loc) · 1.34 KB
/
includes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Assert if a given array contains a value
* @module 101/includes
*/
'use strict';
var isNumber = require('./is-number');
/**
* @param {Array} array
* @param {*} searchElement
* @param {Number} fromIndex
* @return Boolean
*/
module.exports = function (array, searchElement, fromIndex) {
if (arguments.length === 1) {
return includes.bind(null, array);
} else {
return includes(array, searchElement, fromIndex);
}
};
function includes (array, searchElement, fromIndex) {
if (!isNumber(fromIndex)) {
fromIndex = 0;
}
if (Array.prototype.includes) {
return Array.prototype.includes.call(array, searchElement, fromIndex);
} else {
// ES7 Array.prototype.includes polyfill (modified)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility
var O = Object(array);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = fromIndex;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
}
}