UNPKG

1.84 kBJavaScriptView Raw
1import SetCache from './_SetCache';
2import arrayIncludes from './_arrayIncludes';
3import arrayIncludesWith from './_arrayIncludesWith';
4import arrayMap from './_arrayMap';
5import baseUnary from './_baseUnary';
6import cacheHas from './_cacheHas';
7
8/** Used as the size to enable large array optimizations. */
9var LARGE_ARRAY_SIZE = 200;
10
11/**
12 * The base implementation of methods like `_.difference` without support
13 * for excluding multiple arrays or iteratee shorthands.
14 *
15 * @private
16 * @param {Array} array The array to inspect.
17 * @param {Array} values The values to exclude.
18 * @param {Function} [iteratee] The iteratee invoked per element.
19 * @param {Function} [comparator] The comparator invoked per element.
20 * @returns {Array} Returns the new array of filtered values.
21 */
22function baseDifference(array, values, iteratee, comparator) {
23 var index = -1,
24 includes = arrayIncludes,
25 isCommon = true,
26 length = array.length,
27 result = [],
28 valuesLength = values.length;
29
30 if (!length) {
31 return result;
32 }
33 if (iteratee) {
34 values = arrayMap(values, baseUnary(iteratee));
35 }
36 if (comparator) {
37 includes = arrayIncludesWith;
38 isCommon = false;
39 }
40 else if (values.length >= LARGE_ARRAY_SIZE) {
41 includes = cacheHas;
42 isCommon = false;
43 values = new SetCache(values);
44 }
45 outer:
46 while (++index < length) {
47 var value = array[index],
48 computed = iteratee ? iteratee(value) : value;
49
50 if (isCommon && computed === computed) {
51 var valuesIndex = valuesLength;
52 while (valuesIndex--) {
53 if (values[valuesIndex] === computed) {
54 continue outer;
55 }
56 }
57 result.push(value);
58 }
59 else if (!includes(values, computed, comparator)) {
60 result.push(value);
61 }
62 }
63 return result;
64}
65
66export default baseDifference;