42 lines
1.9 KiB
JavaScript
42 lines
1.9 KiB
JavaScript
|
|
const require_toInteger = require("../util/toInteger.js");
|
||
|
|
const require_isEqualsSameValueZero = require("../../_internal/isEqualsSameValueZero.js");
|
||
|
|
require("../util/eq.js");
|
||
|
|
const require_isString = require("../predicate/isString.js");
|
||
|
|
//#region src/compat/array/includes.ts
|
||
|
|
/**
|
||
|
|
* Checks if a specified value exists within a given source, which can be an array, an object, or a string.
|
||
|
|
*
|
||
|
|
* The comparison uses SameValueZero to check for inclusion.
|
||
|
|
*
|
||
|
|
* @param {T[] | Record<string, any> | string} source - The source to search in. It can be an array, an object, or a string.
|
||
|
|
* @param {T} [target] - The value to search for in the source.
|
||
|
|
* @param {number} [fromIndex=0] - The index to start searching from. If negative, it is treated as an offset from the end of the source.
|
||
|
|
* @returns {boolean} `true` if the value is found in the source, `false` otherwise.
|
||
|
|
*
|
||
|
|
* @example
|
||
|
|
* includes([1, 2, 3], 2); // true
|
||
|
|
* includes({ a: 1, b: 'a', c: NaN }, 'a'); // true
|
||
|
|
* includes('hello world', 'world'); // true
|
||
|
|
* includes('hello world', 'test'); // false
|
||
|
|
*/
|
||
|
|
function includes(source, target, fromIndex, guard) {
|
||
|
|
if (source == null) return false;
|
||
|
|
if (guard || !fromIndex) fromIndex = 0;
|
||
|
|
else fromIndex = require_toInteger.toInteger(fromIndex);
|
||
|
|
if (require_isString.isString(source)) {
|
||
|
|
if (fromIndex > source.length || target instanceof RegExp) return false;
|
||
|
|
if (fromIndex < 0) fromIndex = Math.max(0, source.length + fromIndex);
|
||
|
|
return source.includes(target, fromIndex);
|
||
|
|
}
|
||
|
|
if (Array.isArray(source)) return source.includes(target, fromIndex);
|
||
|
|
const keys = Object.keys(source);
|
||
|
|
if (fromIndex < 0) fromIndex = Math.max(0, keys.length + fromIndex);
|
||
|
|
for (let i = fromIndex; i < keys.length; i++) {
|
||
|
|
const value = Reflect.get(source, keys[i]);
|
||
|
|
if (require_isEqualsSameValueZero.isEqualsSameValueZero(value, target)) return true;
|
||
|
|
}
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
//#endregion
|
||
|
|
exports.includes = includes;
|