@ndhoule/includes
Version:
Determine whether or not a value is contained by a given collection.
83 lines (72 loc) • 1.77 kB
JavaScript
;
/*
* Module dependencies.
*/
var each = require('@ndhoule/each');
var strIndexOf = String.prototype.indexOf;
/**
* Object.is/sameValueZero polyfill.
*
* @api private
* @param {*} value1
* @param {*} value2
* @return {boolean}
*/
// TODO: Move to library
var sameValueZero = function sameValueZero(value1, value2) {
// Normal values and check for 0 / -0
if (value1 === value2) {
return value1 !== 0 || 1 / value1 === 1 / value2;
}
// NaN
return value1 !== value1 && value2 !== value2;
};
/**
* Searches a given `collection` for a value, returning true if the collection
* contains the value and false otherwise. Can search strings, arrays, and
* objects.
*
* @name includes
* @api public
* @param {*} searchElement The element to search for.
* @param {Object|Array|string} collection The collection to search.
* @return {boolean}
* @example
* includes(2, [1, 2, 3]);
* //=> true
*
* includes(4, [1, 2, 3]);
* //=> false
*
* includes(2, { a: 1, b: 2, c: 3 });
* //=> true
*
* includes('a', { a: 1, b: 2, c: 3 });
* //=> false
*
* includes('abc', 'xyzabc opq');
* //=> true
*
* includes('nope', 'xyzabc opq');
* //=> false
*/
var includes = function includes(searchElement, collection) {
var found = false;
// Delegate to String.prototype.indexOf when `collection` is a string
if (typeof collection === 'string') {
return strIndexOf.call(collection, searchElement) !== -1;
}
// Iterate through enumerable/own array elements and object properties.
each(function(value) {
if (sameValueZero(value, searchElement)) {
found = true;
// Exit iteration early when found
return false;
}
}, collection);
return found;
};
/*
* Exports.
*/
module.exports = includes;