paulwalko.github.io/_site/node_modules/jshint/dist/jshint.js

23044 lines
978 KiB
JavaScript
Raw Normal View History

2016-06-09 17:51:55 -04:00
/*! 2.7.0 */
var JSHINT;
if (typeof window === 'undefined') window = {};
(function () {
var require;
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var identifierStartTable = [];
for (var i = 0; i < 128; i++) {
identifierStartTable[i] =
i === 36 || // $
i >= 65 && i <= 90 || // A-Z
i === 95 || // _
i >= 97 && i <= 122; // a-z
}
var identifierPartTable = [];
for (var i = 0; i < 128; i++) {
identifierPartTable[i] =
identifierStartTable[i] || // $, _, A-Z, a-z
i >= 48 && i <= 57; // 0-9
}
module.exports = {
asciiIdentifierStartTable: identifierStartTable,
asciiIdentifierPartTable: identifierPartTable
};
},{}],2:[function(require,module,exports){
var str = '768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,1155,1156,1157,1158,1159,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1471,1473,1474,1476,1477,1479,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1648,1750,1751,1752,1753,1754,1755,1756,1759,1760,1761,1762,1763,1764,1767,1768,1770,1771,1772,1773,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1809,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,2027,2028,2029,2030,2031,2032,2033,2034,2035,2070,2071,2072,2073,2075,2076,2077,2078,2079,2080,2081,2082,2083,2085,2086,2087,2089,2090,2091,2092,2093,2137,2138,2139,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2304,2305,2306,2307,2362,2363,2364,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2385,2386,2387,2388,2389,2390,2391,2402,2403,2406,2407,2408,2409,2410,2411,2412,2413,2414,2415,2433,2434,2435,2492,2494,2495,2496,2497,2498,2499,2500,2503,2504,2507,2508,2509,2519,2530,2531,2534,2535,2536,2537,2538,2539,2540,2541,2542,2543,2561,2562,2563,2620,2622,2623,2624,2625,2626,2631,2632,2635,2636,2637,2641,2662,2663,2664,2665,2666,2667,2668,2669,2670,2671,2672,2673,2677,2689,2690,2691,2748,2750,2751,2752,2753,2754,2755,2756,2757,2759,2760,2761,2763,2764,2765,2786,2787,2790,2791,2792,2793,2794,2795,2796,2797,2798,2799,2817,2818,2819,2876,2878,2879,2880,2881,2882,2883,2884,2887,2888,2891,2892,2893,2902,2903,2914,2915,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2946,3006,3007,3008,3009,3010,3014,3015,3016,3018,3019,3020,3021,3031,3046,3047,3048,3049,3050,3051,3052,3053,3054,3055,3073,3074,3075,3134,3135,3136,3137,3138,3139,3140,3142,3143,3144,3146,3147,3148,3149,3157,3158,3170,3171,3174,3175,3176,3177,3178,3179,3180,3181,3182,3183,3202,3203,3260,3262,3263,3264,3265,3266,3267,3268,3270,3271,3272,3274,3275,3276,3277,3285,3286,3298,3299,3302,3303,3304,3305,3306,3307,3308,3309,3310,3311,3330,3331,3390,3391,3392,3393,3394,3395,3396,3398,3399,3400,3402,3403,3404,3405,3415,3426,3427,3430,3431,3432,3433,3434,3435,3436,3437,3438,3439,3458,3459,3530,3535,3536,3537,3538,3539,3540,3542,3544,3545,3546,3547,3548,3549,3550,3551,3570,3571,3633,3636,3637,3638,3639,3640,3641,3642,3655,3656,3657,3658,3659,3660,3661,3662,3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3761,3764,3765,3766,3767,3768,3769,3771,3772,3784,3785,3786,3787,3788,3789,3792,3793,3794,3795,3796,3797,3798,3799,3800,3801,3864,3865,3872,3873,3874,3875,3876,3877,3878,3879,3880,3881,3893,3895,3897,3902,3903,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964,3965,3966,3967,3968,3969,3970,3971,3972,3974,3975,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,3993,3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009,4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,4024,4025,4026,4027,4028,4038,4139,4140,4141,4142,4143,4144,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157,4158,4160,4161,4162,4163,4164,4165,4166,4167,4168,4169,4182,4183,4184,4185,4190,4191,4192,4194,4195,4196,4199,4200,4201,4202,4203,4204,4205,4209,4210,4211,4212,4226,4227,4228,4229,4230,4
var arr = str.split(',').map(function(code) {
return parseInt(code, 10);
});
module.exports = arr;
},{}],3:[function(require,module,exports){
var str = '170,181,186,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,710,711,712,713,714,715,716,717,718,719,720,721,736,737,738,739,740,748,750,880,881,882,883,884,886,887,890,891,892,893,902,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279,1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,131
var arr = str.split(',').map(function(code) {
return parseInt(code, 10);
});
module.exports = arr;
},{}],4:[function(require,module,exports){
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// when used in node, this will actually load the util module we depend on
// versus loading the builtin util module as happens otherwise
// this is a bug in node module loading as far as I am concerned
var util = require('util/');
var pSlice = Array.prototype.slice;
var hasOwn = Object.prototype.hasOwnProperty;
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
}
else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = stackStartFunction.name;
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (util.isUndefined(value)) {
return '' + value;
}
if (util.isNumber(value) && !isFinite(value)) {
return value.toString();
}
if (util.isFunction(value) || util.isRegExp(value)) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (util.isString(s)) {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b)) {
return a === b;
}
var aIsArgs = isArguments(a),
bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
var ka = objectKeys(a),
kb = objectKeys(b),
key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (util.isString(expected)) {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [true].concat(pSlice.call(arguments)));
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
_throws.apply(this, [false].concat(pSlice.call(arguments)));
};
assert.ifError = function(err) { if (err) {throw err;}};
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
},{"util/":9}],5:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],6:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],7:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],8:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],9:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":8,"_process":7,"inherits":6}],10:[function(require,module,exports){
(function (global){
/*global window, global*/
var util = require("util")
var assert = require("assert")
var now = require("date-now")
var slice = Array.prototype.slice
var console
var times = {}
if (typeof global !== "undefined" && global.console) {
console = global.console
} else if (typeof window !== "undefined" && window.console) {
console = window.console
} else {
console = {}
}
var functions = [
[log, "log"],
[info, "info"],
[warn, "warn"],
[error, "error"],
[time, "time"],
[timeEnd, "timeEnd"],
[trace, "trace"],
[dir, "dir"],
[consoleAssert, "assert"]
]
for (var i = 0; i < functions.length; i++) {
var tuple = functions[i]
var f = tuple[0]
var name = tuple[1]
if (!console[name]) {
console[name] = f
}
}
module.exports = console
function log() {}
function info() {
console.log.apply(console, arguments)
}
function warn() {
console.log.apply(console, arguments)
}
function error() {
console.warn.apply(console, arguments)
}
function time(label) {
times[label] = now()
}
function timeEnd(label) {
var time = times[label]
if (!time) {
throw new Error("No such label: " + label)
}
var duration = now() - time
console.log(label + ": " + duration + "ms")
}
function trace() {
var err = new Error()
err.name = "Trace"
err.message = util.format.apply(null, arguments)
console.error(err.stack)
}
function dir(object) {
console.log(util.inspect(object) + "\n")
}
function consoleAssert(expression) {
if (!expression) {
var arr = slice.call(arguments, 1)
assert.ok(false, util.format.apply(null, arr))
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"assert":4,"date-now":11,"util":9}],11:[function(require,module,exports){
module.exports = now
function now() {
return new Date().getTime()
}
},{}],12:[function(require,module,exports){
(function (global){
/**
* @license
* lodash 3.6.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern -d -o ./index.js`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '3.6.0';
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_BOUND_FLAG = 4,
CURRY_FLAG = 8,
CURRY_RIGHT_FLAG = 16,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64,
ARY_FLAG = 128,
REARG_FLAG = 256;
/** Used as default options for `_.trunc`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect when a function becomes hot. */
var HOT_COUNT = 150,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_DROP_WHILE_FLAG = 0,
LAZY_FILTER_FLAG = 1,
LAZY_MAP_FLAG = 2;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities and HTML characters. */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
reUnescapedHtml = /[&<>"'`]/g,
reHasEscapedHtml = RegExp(reEscapedHtml.source),
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g,
reEvaluate = /<%([\s\S]+?)%>/g,
reInterpolate = /<%=([\s\S]+?)%>/g;
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*/
var reComboMarks = /[\u0300-\u036f\ufe20-\ufe23]/g;
/**
* Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components).
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect hexadecimal string values. */
var reHexPrefix = /^0[xX]/;
/** Used to detect host constructors (Safari > 5). */
var reHostCtor = /^\[object .+?Constructor\]$/;
/** Used to match latin-1 supplementary letters (excluding mathematical operators). */
var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/**
* Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special).
* In addition to special characters the forward slash is escaped to allow for
* easier `eval` use and `Function` compilation.
*/
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
reHasRegExpChars = RegExp(reRegExpChars.source);
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used to match words to create compound words. */
var reWords = (function() {
var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
}());
/** Used to detect and test for whitespace. */
var whitespace = (
// Basic whitespace characters.
' \t\x0b\f\xa0\ufeff' +
// Line terminators.
'\n\r\u2028\u2029' +
// Unicode category "Zs" space separators.
'\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
);
/** Used to assign default `context` object properties. */
var contextProps = [
'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document',
'isFinite', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
'window'
];
/** Used to make template sourceURLs easier to identify. */
var templateCounter = -1;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
cloneableTags[dateTag] = cloneableTags[float32Tag] =
cloneableTags[float64Tag] = cloneableTags[int8Tag] =
cloneableTags[int16Tag] = cloneableTags[int32Tag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[stringTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[mapTag] = cloneableTags[setTag] =
cloneableTags[weakMapTag] = false;
/** Used as an internal `_.debounce` options object by `_.throttle`. */
var debounceOptions = {
'leading': false,
'maxWait': 0,
'trailing': false
};
/** Used to map latin-1 supplementary letters to basic latin letters. */
var deburredLetters = {
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss'
};
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
'`': '&#96;'
};
/** Used to map HTML entities to characters. */
var htmlUnescapes = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
'&#96;': '`'
};
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Detect free variable `exports`. */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect free variable `global` from Node.js. */
var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
/** Detect free variable `self`. */
var freeSelf = objectTypes[typeof self] && self && self.Object && self;
/** Detect free variable `window`. */
var freeWindow = objectTypes[typeof window] && window && window.Object && window;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/**
* Used as a reference to the global object.
*
* The `this` value is used if it is the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `compareAscending` which compares values and
* sorts them in ascending order without guaranteeing a stable sort.
*
* @private
* @param {*} value The value to compare to `other`.
* @param {*} other The value to compare to `value`.
* @returns {number} Returns the sort order indicator for `value`.
*/
function baseCompareAscending(value, other) {
if (value !== other) {
var valIsReflexive = value === value,
othIsReflexive = other === other;
if (value > other || !valIsReflexive || (typeof value == 'undefined' && othIsReflexive)) {
return 1;
}
if (value < other || !othIsReflexive || (typeof other == 'undefined' && valIsReflexive)) {
return -1;
}
}
return 0;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to search.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without support for binary searches.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
if (value !== value) {
return indexOfNaN(array, fromIndex);
}
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.isFunction` without support for environments
* with incorrect `typeof` results.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
*/
function baseIsFunction(value) {
// Avoid a Chakra JIT bug in compatibility modes of IE 11.
// See https://github.com/jashkenas/underscore/issues/1621 for more details.
return typeof value == 'function' || false;
}
/**
* Converts `value` to a string if it is not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
if (typeof value == 'string') {
return value;
}
return value == null ? '' : (value + '');
}
/**
* Used by `_.max` and `_.min` as the default callback for string values.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the code unit of the first character of the string.
*/
function charAtCallback(string) {
return string.charCodeAt(0);
}
/**
* Used by `_.trim` and `_.trimLeft` to get the index of the first character
* of `string` that is not found in `chars`.
*
* @private
* @param {string} string The string to inspect.
* @param {string} chars The characters to find.
* @returns {number} Returns the index of the first character not found in `chars`.
*/
function charsLeftIndex(string, chars) {
var index = -1,
length = string.length;
while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
return index;
}
/**
* Used by `_.trim` and `_.trimRight` to get the index of the last character
* of `string` that is not found in `chars`.
*
* @private
* @param {string} string The string to inspect.
* @param {string} chars The characters to find.
* @returns {number} Returns the index of the last character not found in `chars`.
*/
function charsRightIndex(string, chars) {
var index = string.length;
while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
return index;
}
/**
* Used by `_.sortBy` to compare transformed elements of a collection and stable
* sort them in ascending order.
*
* @private
* @param {Object} object The object to compare to `other`.
* @param {Object} other The object to compare to `object`.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareAscending(object, other) {
return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
}
/**
* Used by `_.sortByOrder` to compare multiple properties of each element
* in a collection and stable sort them in the following order:
*
* If orders is unspecified, sort in ascending order for all properties.
* Otherwise, for each property, sort in ascending order if its corresponding value in
* orders is true, and descending order if false.
*
* @private
* @param {Object} object The object to compare to `other`.
* @param {Object} other The object to compare to `object`.
* @param {boolean[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
return result * (orders[index] ? 1 : -1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://code.google.com/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/**
* Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
function deburrLetter(letter) {
return deburredLetters[letter];
}
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeHtmlChar(chr) {
return htmlEscapes[chr];
}
/**
* Used by `_.template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* Gets the index at which the first occurrence of `NaN` is found in `array`.
*
* @private
* @param {Array} array The array to search.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched `NaN`, else `-1`.
*/
function indexOfNaN(array, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 0 : -1);
while ((fromRight ? index-- : ++index < length)) {
var other = array[index];
if (other !== other) {
return index;
}
}
return -1;
}
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
* character code is whitespace.
*
* @private
* @param {number} charCode The character code to inspect.
* @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
*/
function isSpace(charCode) {
return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
(charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
}
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = -1,
result = [];
while (++index < length) {
if (array[index] === placeholder) {
array[index] = PLACEHOLDER;
result[++resIndex] = index;
}
}
return result;
}
/**
* An implementation of `_.uniq` optimized for sorted arrays without support
* for callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The function invoked per iteration.
* @returns {Array} Returns the new duplicate-value-free array.
*/
function sortedUniq(array, iteratee) {
var seen,
index = -1,
length = array.length,
resIndex = -1,
result = [];
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value, index, array) : value;
if (!index || seen !== computed) {
seen = computed;
result[++resIndex] = value;
}
}
return result;
}
/**
* Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the first non-whitespace character.
*/
function trimmedLeftIndex(string) {
var index = -1,
length = string.length;
while (++index < length && isSpace(string.charCodeAt(index))) {}
return index;
}
/**
* Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedRightIndex(string) {
var index = string.length;
while (index-- && isSpace(string.charCodeAt(index))) {}
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
function unescapeHtmlChar(chr) {
return htmlUnescapes[chr];
}
/*--------------------------------------------------------------------------*/
/**
* Create a new pristine `lodash` function using the given `context` object.
*
* @static
* @memberOf _
* @category Utility
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'foo': _.constant('foo') });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'bar': lodash.constant('bar') });
*
* _.isFunction(_.foo);
* // => true
* _.isFunction(_.bar);
* // => false
*
* lodash.isFunction(lodash.foo);
* // => false
* lodash.isFunction(lodash.bar);
* // => true
*
* // using `context` to mock `Date#getTime` use in `_.now`
* var mock = _.runInContext({
* 'Date': function() {
* return { 'getTime': getTimeMock };
* }
* });
*
* // or creating a suped-up `defer` in Node.js
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
function runInContext(context) {
// Avoid issues with some ES3 environments that attempt to use values, named
// after built-in constructors like `Object`, for the creation of literals.
// ES5 clears this up by stating that literals must use built-in constructors.
// See https://es5.github.io/#x11.1.5 for more details.
context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
/** Native constructor references. */
var Array = context.Array,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Number = context.Number,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for native method references. */
var arrayProto = Array.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to detect DOM support. */
var document = (document = context.window) && document.document;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to the length of n-tuples for `_.unzip`. */
var getLength = baseProperty('length');
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/**
* Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = context._;
/** Used to detect if a method is native. */
var reNative = RegExp('^' +
escapeRegExp(objToString)
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Native method references. */
var ArrayBuffer = isNative(ArrayBuffer = context.ArrayBuffer) && ArrayBuffer,
bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice,
ceil = Math.ceil,
clearTimeout = context.clearTimeout,
floor = Math.floor,
getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
push = arrayProto.push,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
Set = isNative(Set = context.Set) && Set,
setTimeout = context.setTimeout,
splice = arrayProto.splice,
Uint8Array = isNative(Uint8Array = context.Uint8Array) && Uint8Array,
WeakMap = isNative(WeakMap = context.WeakMap) && WeakMap;
/** Used to clone array buffers. */
var Float64Array = (function() {
// Safari 5 errors when using an array buffer to initialize a typed array
// where the array buffer's `byteLength` is not a multiple of the typed
// array's `BYTES_PER_ELEMENT`.
try {
var func = isNative(func = context.Float64Array) && func,
result = new func(new ArrayBuffer(10), 0, 1) && func;
} catch(e) {}
return result;
}());
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
nativeIsFinite = context.isFinite,
nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeNow = isNative(nativeNow = Date.now) && nativeNow,
nativeNumIsFinite = isNative(nativeNumIsFinite = Number.isFinite) && nativeNumIsFinite,
nativeParseInt = context.parseInt,
nativeRandom = Math.random;
/** Used as references for `-Infinity` and `Infinity`. */
var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used as the size, in bytes, of each `Float64Array` element. */
var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/** Used to lookup unminified function names. */
var realNames = {};
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable implicit chaining.
* Methods that operate on and return arrays, collections, and functions can
* be chained together. Methods that return a boolean or single value will
* automatically end the chain returning the unwrapped value. Explicit chaining
* may be enabled using `_.chain`. The execution of chained methods is lazy,
* that is, execution is deferred until `_#value` is implicitly or explicitly
* called.
*
* Lazy evaluation allows several methods to support shortcut fusion. Shortcut
* fusion is an optimization that merges iteratees to avoid creating intermediate
* arrays and reduce the number of iteratee executions.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
* `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
* `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
* `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
* and `where`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
* `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
* `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`,
* `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`,
* `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`,
* `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`,
* `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`,
* `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, `merge`,
* `mixin`, `negate`, `noop`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
* `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
* `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`,
* `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`,
* `spread`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`,
* `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, `transform`,
* `union`, `uniq`, `unshift`, `unzip`, `values`, `valuesIn`, `where`,
* `without`, `wrap`, `xor`, `zip`, and `zipObject`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`,
* `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`,
* `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`,
* `identity`, `includes`, `indexOf`, `inRange`, `isArguments`, `isArray`,
* `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`,
* `isFinite`,`isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`,
* `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`,
* `isTypedArray`, `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`,
* `noConflict`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`,
* `random`, `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`,
* `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`,
* `startCase`, `startsWith`, `sum`, `template`, `trim`, `trimLeft`,
* `trimRight`, `trunc`, `unescape`, `uniqueId`, `value`, and `words`
*
* The wrapper method `sample` will return a wrapped value when `n` is provided,
* otherwise an unwrapped value is returned.
*
* @name _
* @constructor
* @category Chain
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var wrapped = _([1, 2, 3]);
*
* // returns an unwrapped value
* wrapped.reduce(function(sum, n) {
* return sum + n;
* });
* // => 6
*
* // returns a wrapped value
* var squares = wrapped.map(function(n) {
* return n * n;
* });
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
/**
* The function whose prototype all chaining wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable chaining for all wrapper methods.
* @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
*/
function LodashWrapper(value, chainAll, actions) {
this.__wrapped__ = value;
this.__actions__ = actions || [];
this.__chain__ = !!chainAll;
}
/**
* An object environment feature flags.
*
* @static
* @memberOf _
* @type Object
*/
var support = lodash.support = {};
(function(x) {
/**
* Detect if functions can be decompiled by `Function#toString`
* (all but Firefox OS certified apps, older Opera mobile browsers, and
* the PlayStation 3; forced `false` for Windows 8 apps).
*
* @memberOf _.support
* @type boolean
*/
support.funcDecomp = /\bthis\b/.test(function() { return this; });
/**
* Detect if `Function#name` is supported (all but IE).
*
* @memberOf _.support
* @type boolean
*/
support.funcNames = typeof Function.name == 'string';
/**
* Detect if the DOM is supported.
*
* @memberOf _.support
* @type boolean
*/
try {
support.dom = document.createDocumentFragment().nodeType === 11;
} catch(e) {
support.dom = false;
}
/**
* Detect if `arguments` object indexes are non-enumerable.
*
* In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object
* indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat
* `arguments` object indexes as non-enumerable and fail `hasOwnProperty`
* checks for indexes that exceed their function's formal parameters with
* associated values of `0`.
*
* @memberOf _.support
* @type boolean
*/
try {
support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1);
} catch(e) {
support.nonEnumArgs = true;
}
}(0, 0));
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB). Change the following template settings to use
* alternative delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type string
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type Object
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type Function
*/
'_': lodash
}
};
/*------------------------------------------------------------------------*/
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = null;
this.__dir__ = 1;
this.__dropCount__ = 0;
this.__filtered__ = false;
this.__iteratees__ = null;
this.__takeCount__ = POSITIVE_INFINITY;
this.__views__ = null;
}
/**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/
function lazyClone() {
var actions = this.__actions__,
iteratees = this.__iteratees__,
views = this.__views__,
result = new LazyWrapper(this.__wrapped__);
result.__actions__ = actions ? arrayCopy(actions) : null;
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
result.__iteratees__ = iteratees ? arrayCopy(iteratees) : null;
result.__takeCount__ = this.__takeCount__;
result.__views__ = views ? arrayCopy(views) : null;
return result;
}
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
/**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/
function lazyValue() {
var array = this.__wrapped__.value();
if (!isArray(array)) {
return baseWrapperValue(array, this.__actions__);
}
var dir = this.__dir__,
isRight = dir < 0,
view = getView(0, array.length, this.__views__),
start = view.start,
end = view.end,
length = end - start,
index = isRight ? end : (start - 1),
takeCount = nativeMin(length, this.__takeCount__),
iteratees = this.__iteratees__,
iterLength = iteratees ? iteratees.length : 0,
resIndex = 0,
result = [];
outer:
while (length-- && resIndex < takeCount) {
index += dir;
var iterIndex = -1,
value = array[index];
while (++iterIndex < iterLength) {
var data = iteratees[iterIndex],
iteratee = data.iteratee,
type = data.type;
if (type == LAZY_DROP_WHILE_FLAG) {
if (data.done && (isRight ? (index > data.index) : (index < data.index))) {
data.count = 0;
data.done = false;
}
data.index = index;
if (!data.done) {
var limit = data.limit;
if (!(data.done = limit > -1 ? (data.count++ >= limit) : !iteratee(value))) {
continue outer;
}
}
} else {
var computed = iteratee(value);
if (type == LAZY_MAP_FLAG) {
value = computed;
} else if (!computed) {
if (type == LAZY_FILTER_FLAG) {
continue outer;
} else {
break outer;
}
}
}
}
result[resIndex++] = value;
}
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates a cache object to store key/value pairs.
*
* @private
* @static
* @name Cache
* @memberOf _.memoize
*/
function MapCache() {
this.__data__ = {};
}
/**
* Removes `key` and its value from the cache.
*
* @private
* @name delete
* @memberOf _.memoize.Cache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
*/
function mapDelete(key) {
return this.has(key) && delete this.__data__[key];
}
/**
* Gets the cached value for `key`.
*
* @private
* @name get
* @memberOf _.memoize.Cache
* @param {string} key The key of the value to get.
* @returns {*} Returns the cached value.
*/
function mapGet(key) {
return key == '__proto__' ? undefined : this.__data__[key];
}
/**
* Checks if a cached value for `key` exists.
*
* @private
* @name has
* @memberOf _.memoize.Cache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
}
/**
* Adds `value` to `key` of the cache.
*
* @private
* @name set
* @memberOf _.memoize.Cache
* @param {string} key The key of the value to cache.
* @param {*} value The value to cache.
* @returns {Object} Returns the cache object.
*/
function mapSet(key, value) {
if (key != '__proto__') {
this.__data__[key] = value;
}
return this;
}
/*------------------------------------------------------------------------*/
/**
*
* Creates a cache object to store unique values.
*
* @private
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var length = values ? values.length : 0;
this.data = { 'hash': nativeCreate(null), 'set': new Set };
while (length--) {
this.push(values[length]);
}
}
/**
* Checks if `value` is in `cache` mimicking the return signature of
* `_.indexOf` by returning `0` if the value is found, else `-1`.
*
* @private
* @param {Object} cache The cache to search.
* @param {*} value The value to search for.
* @returns {number} Returns `0` if `value` is found, else `-1`.
*/
function cacheIndexOf(cache, value) {
var data = cache.data,
result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
return result ? 0 : -1;
}
/**
* Adds `value` to the cache.
*
* @private
* @name push
* @memberOf SetCache
* @param {*} value The value to cache.
*/
function cachePush(value) {
var data = this.data;
if (typeof value == 'string' || isObject(value)) {
data.set.add(value);
} else {
data.hash[value] = true;
}
}
/*------------------------------------------------------------------------*/
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.forEachRight` for arrays without support for
* callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEachRight(array, iteratee) {
var length = array.length;
while (length--) {
if (iteratee(array[length], length, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.every` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/**
* A specialized version of `_.filter` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array.length,
resIndex = -1,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[++resIndex] = value;
}
}
return result;
}
/**
* A specialized version of `_.map` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* A specialized version of `_.max` for arrays without support for iteratees.
*
* @private
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
*/
function arrayMax(array) {
var index = -1,
length = array.length,
result = NEGATIVE_INFINITY;
while (++index < length) {
var value = array[index];
if (value > result) {
result = value;
}
}
return result;
}
/**
* A specialized version of `_.min` for arrays without support for iteratees.
*
* @private
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
*/
function arrayMin(array) {
var index = -1,
length = array.length,
result = POSITIVE_INFINITY;
while (++index < length) {
var value = array[index];
if (value < result) {
result = value;
}
}
return result;
}
/**
* A specialized version of `_.reduce` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initFromArray] Specify using the first element of `array`
* as the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initFromArray) {
var index = -1,
length = array.length;
if (initFromArray && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* A specialized version of `_.reduceRight` for arrays without support for
* callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initFromArray] Specify using the last element of `array`
* as the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
var length = array.length;
if (initFromArray && length) {
accumulator = array[--length];
}
while (length--) {
accumulator = iteratee(accumulator, array[length], length, array);
}
return accumulator;
}
/**
* A specialized version of `_.some` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* A specialized version of `_.sum` for arrays without support for iteratees.
*
* @private
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
*/
function arraySum(array) {
var length = array.length,
result = 0;
while (length--) {
result += +array[length] || 0;
}
return result;
}
/**
* Used by `_.defaults` to customize its `_.assign` use.
*
* @private
* @param {*} objectValue The destination object property value.
* @param {*} sourceValue The source object property value.
* @returns {*} Returns the value to assign to the destination object.
*/
function assignDefaults(objectValue, sourceValue) {
return typeof objectValue == 'undefined' ? sourceValue : objectValue;
}
/**
* Used by `_.template` to customize its `_.assign` use.
*
* **Note:** This method is like `assignDefaults` except that it ignores
* inherited property values when checking if a property is `undefined`.
*
* @private
* @param {*} objectValue The destination object property value.
* @param {*} sourceValue The source object property value.
* @param {string} key The key associated with the object and source values.
* @param {Object} object The destination object.
* @returns {*} Returns the value to assign to the destination object.
*/
function assignOwnDefaults(objectValue, sourceValue, key, object) {
return (typeof objectValue == 'undefined' || !hasOwnProperty.call(object, key))
? sourceValue
: objectValue;
}
/**
* The base implementation of `_.assign` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize assigning values.
* @returns {Object} Returns the destination object.
*/
function baseAssign(object, source, customizer) {
var props = keys(source);
if (!customizer) {
return baseCopy(source, object, props);
}
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index],
value = object[key],
result = customizer(value, source[key], key, object, source);
if ((result === result ? (result !== value) : (value === value)) ||
(typeof value == 'undefined' && !(key in object))) {
object[key] = result;
}
}
return object;
}
/**
* The base implementation of `_.at` without support for strings and individual
* key arguments.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {number[]|string[]} [props] The property names or indexes of elements to pick.
* @returns {Array} Returns the new array of picked elements.
*/
function baseAt(collection, props) {
var index = -1,
length = collection.length,
isArr = isLength(length),
propsLength = props.length,
result = Array(propsLength);
while(++index < propsLength) {
var key = props[index];
if (isArr) {
key = parseFloat(key);
result[index] = isIndex(key, length) ? collection[key] : undefined;
} else {
result[index] = collection[key];
}
}
return result;
}
/**
* Copies the properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Object} [object={}] The object to copy properties to.
* @param {Array} props The property names to copy.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, object, props) {
if (!props) {
props = object;
object = {};
}
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
/**
* The base implementation of `_.callback` which supports specifying the
* number of arguments to provide to `func`.
*
* @private
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function baseCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function') {
return typeof thisArg == 'undefined'
? func
: bindCallback(func, thisArg, argCount);
}
if (func == null) {
return identity;
}
if (type == 'object') {
return baseMatches(func);
}
return typeof thisArg == 'undefined'
? baseProperty(func + '')
: baseMatchesProperty(func + '', thisArg);
}
/**
* The base implementation of `_.clone` without support for argument juggling
* and `this` binding `customizer` functions.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The object `value` belongs to.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates clones with source counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
var result;
if (customizer) {
result = object ? customizer(value, key, object) : customizer(value);
}
if (typeof result != 'undefined') {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return arrayCopy(value, result);
}
} else {
var tag = objToString.call(value),
isFunc = tag == funcTag;
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = initCloneObject(isFunc ? {} : value);
if (!isDeep) {
return baseCopy(value, result, keys(value));
}
} else {
return cloneableTags[tag]
? initCloneByTag(value, tag, isDeep)
: (object ? value : {});
}
}
// Check for circular references and return corresponding clone.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
// Add the source value to the stack of traversed objects and associate it with its clone.
stackA.push(value);
stackB.push(result);
// Recursively populate clone (susceptible to call stack limits).
(isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
});
return result;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || context.Object();
};
}());
/**
* The base implementation of `_.delay` and `_.defer` which accepts an index
* of where to slice the arguments to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Object} args The arguments provide to `func`.
* @returns {number} Returns the timer id.
*/
function baseDelay(func, wait, args) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* The base implementation of `_.difference` which accepts a single array
* of values to exclude.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values) {
var length = array ? array.length : 0,
result = [];
if (!length) {
return result;
}
var index = -1,
indexOf = getIndexOf(),
isCommon = indexOf == baseIndexOf,
cache = (isCommon && values.length >= 200) ? createCache(values) : null,
valuesLength = values.length;
if (cache) {
indexOf = cacheIndexOf;
isCommon = false;
values = cache;
}
outer:
while (++index < length) {
var value = array[index];
if (isCommon && value === value) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === value) {
continue outer;
}
}
result.push(value);
}
else if (indexOf(values, value, 0) < 0) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.forEach` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `_.forEachRight` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEachRight = createBaseEach(baseForOwnRight, true);
/**
* The base implementation of `_.every` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
*/
function baseFill(array, value, start, end) {
var length = array.length;
start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (typeof end == 'undefined' || end > length) ? length : (+end || 0);
if (end < 0) {
end += length;
}
length = start > end ? 0 : (end >>> 0);
start >>>= 0;
while (start < length) {
array[start++] = value;
}
return array;
}
/**
* The base implementation of `_.filter` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
/**
* The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
* without support for callback shorthands and `this` binding, which iterates
* over `collection` using the provided `eachFunc`.
*
* @private
* @param {Array|Object|string} collection The collection to search.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @param {boolean} [retKey] Specify returning the key of the found element
* instead of the element itself.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFind(collection, predicate, eachFunc, retKey) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = retKey ? key : value;
return false;
}
});
return result;
}
/**
* The base implementation of `_.flatten` with added support for restricting
* flattening and specifying the start index.
*
* @private
* @param {Array} array The array to flatten.
* @param {boolean} isDeep Specify a deep flatten.
* @param {boolean} isStrict Restrict flattening to arrays and `arguments` objects.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, isDeep, isStrict) {
var index = -1,
length = array.length,
resIndex = -1,
result = [];
while (++index < length) {
var value = array[index];
if (isObjectLike(value) && isLength(value.length) && (isArray(value) || isArguments(value))) {
if (isDeep) {
// Recursively flatten arrays (susceptible to call stack limits).
value = baseFlatten(value, isDeep, isStrict);
}
var valIndex = -1,
valLength = value.length;
result.length += valLength;
while (++valIndex < valLength) {
result[++resIndex] = value[valIndex];
}
} else if (!isStrict) {
result[++resIndex] = value;
}
}
return result;
}
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iterator functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseForRight = createBaseFor(true);
/**
* The base implementation of `_.forIn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
return baseFor(object, iteratee, keysIn);
}
/**
* The base implementation of `_.forOwn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.forOwnRight` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from those provided.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the new array of filtered property names.
*/
function baseFunctions(object, props) {
var index = -1,
length = props.length,
resIndex = -1,
result = [];
while (++index < length) {
var key = props[index];
if (isFunction(object[key])) {
result[++resIndex] = key;
}
}
return result;
}
/**
* The base implementation of `_.isEqual` without support for `this` binding
* `customizer` functions.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
// Exit early for identical values.
if (value === other) {
// Treat `+0` vs. `-0` as not equal.
return value !== 0 || (1 / value == 1 / other);
}
var valType = typeof value,
othType = typeof other;
// Exit early for unlike primitive values.
if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') ||
value == null || other == null) {
// Return `false` unless both values are `NaN`.
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing objects.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `value` objects.
* @param {Array} [stackB=[]] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = objToString.call(object);
if (objTag == argsTag) {
objTag = objectTag;
} else if (objTag != objectTag) {
objIsArr = isTypedArray(object);
}
}
if (!othIsArr) {
othTag = objToString.call(other);
if (othTag == argsTag) {
othTag = objectTag;
} else if (othTag != objectTag) {
othIsArr = isTypedArray(other);
}
}
var objIsObj = (objTag == objectTag || (isLoose && objTag == funcTag)),
othIsObj = (othTag == objectTag || (isLoose && othTag == funcTag)),
isSameTag = objTag == othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
return equalByTag(object, other, objTag);
}
if (isLoose) {
if (!isSameTag && !(objIsObj && othIsObj)) {
return false;
}
} else {
var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (valWrapped || othWrapped) {
return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
}
if (!isSameTag) {
return false;
}
}
// Assume cyclic values are equal.
// For more information on detecting circular references see https://es5.github.io/#JO.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == object) {
return stackB[length] == other;
}
}
// Add `object` and `other` to the stack of traversed objects.
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
/**
* The base implementation of `_.isMatch` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The source property names to match.
* @param {Array} values The source values to match.
* @param {Array} strictCompareFlags Strict comparison flags for source values.
* @param {Function} [customizer] The function to customize comparing objects.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, props, values, strictCompareFlags, customizer) {
var index = -1,
length = props.length,
noCustomizer = !customizer;
while (++index < length) {
if ((noCustomizer && strictCompareFlags[index])
? values[index] !== object[props[index]]
: !(props[index] in object)
) {
return false;
}
}
index = -1;
while (++index < length) {
var key = props[index],
objValue = object[key],
srcValue = values[index];
if (noCustomizer && strictCompareFlags[index]) {
var result = typeof objValue != 'undefined' || (key in object);
} else {
result = customizer ? customizer(objValue, srcValue, key) : undefined;
if (typeof result == 'undefined') {
result = baseIsEqual(srcValue, objValue, customizer, true);
}
}
if (!result) {
return false;
}
}
return true;
}
/**
* The base implementation of `_.map` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var result = [];
baseEach(collection, function(value, key, collection) {
result.push(iteratee(value, key, collection));
});
return result;
}
/**
* The base implementation of `_.matches` which does not clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
*/
function baseMatches(source) {
var props = keys(source),
length = props.length;
if (!length) {
return constant(true);
}
if (length == 1) {
var key = props[0],
value = source[key];
if (isStrictComparable(value)) {
return function(object) {
return object != null && object[key] === value &&
(typeof value != 'undefined' || (key in toObject(object)));
};
}
}
var values = Array(length),
strictCompareFlags = Array(length);
while (length--) {
value = source[props[length]];
values[length] = value;
strictCompareFlags[length] = isStrictComparable(value);
}
return function(object) {
return object != null && baseIsMatch(toObject(object), props, values, strictCompareFlags);
};
}
/**
* The base implementation of `_.matchesProperty` which does not coerce `key`
* to a string.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} value The value to compare.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(key, value) {
if (isStrictComparable(value)) {
return function(object) {
return object != null && object[key] === value &&
(typeof value != 'undefined' || (key in toObject(object)));
};
}
return function(object) {
return object != null && baseIsEqual(value, object[key], null, true);
};
}
/**
* The base implementation of `_.merge` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns the destination object.
*/
function baseMerge(object, source, customizer, stackA, stackB) {
if (!isObject(object)) {
return object;
}
var isSrcArr = isLength(source.length) && (isArray(source) || isTypedArray(source));
(isSrcArr ? arrayEach : baseForOwn)(source, function(srcValue, key, source) {
if (isObjectLike(srcValue)) {
stackA || (stackA = []);
stackB || (stackB = []);
return baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
}
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = typeof result == 'undefined';
if (isCommon) {
result = srcValue;
}
if ((isSrcArr || typeof result != 'undefined') &&
(isCommon || (result === result ? (result !== value) : (value === value)))) {
object[key] = result;
}
});
return object;
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
var length = stackA.length,
srcValue = source[key];
while (length--) {
if (stackA[length] == srcValue) {
object[key] = stackB[length];
return;
}
}
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = typeof result == 'undefined';
if (isCommon) {
result = srcValue;
if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) {
result = isArray(value)
? value
: ((value && value.length) ? arrayCopy(value) : []);
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
result = isArguments(value)
? toPlainObject(value)
: (isPlainObject(value) ? value : {});
}
else {
isCommon = false;
}
}
// Add the source value to the stack of traversed objects and associate
// it with its merged value.
stackA.push(srcValue);
stackB.push(result);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
} else if (result === result ? (result !== value) : (value === value)) {
object[key] = result;
}
}
/**
* The base implementation of `_.property` which does not coerce `key` to a string.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.random` without support for argument juggling
* and returning floating-point numbers.
*
* @private
* @param {number} min The minimum possible value.
* @param {number} max The maximum possible value.
* @returns {number} Returns the random number.
*/
function baseRandom(min, max) {
return min + floor(nativeRandom() * (max - min + 1));
}
/**
* The base implementation of `_.reduce` and `_.reduceRight` without support
* for callback shorthands and `this` binding, which iterates over `collection`
* using the provided `eachFunc`.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initFromCollection Specify using the first or last element
* of `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initFromCollection
? (initFromCollection = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The base implementation of `setData` without support for hot loop detection.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (typeof end == 'undefined' || end > length) ? length : (+end || 0);
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* The base implementation of `_.some` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/**
* The base implementation of `_.sortBy` which uses `comparer` to define
* the sort order of `array` and replaces criteria objects with their
* corresponding values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* The base implementation of `_.sortByOrder` without param guards.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string[]} props The property names to sort by.
* @param {boolean[]} orders The sort orders of `props`.
* @returns {Array} Returns the new sorted array.
*/
function baseSortByOrder(collection, props, orders) {
var index = -1,
length = collection.length,
result = isLength(length) ? Array(length) : [];
baseEach(collection, function(value) {
var length = props.length,
criteria = Array(length);
while (length--) {
criteria[length] = value == null ? undefined : value[props[length]];
}
result[++index] = { 'criteria': criteria, 'index': index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
/**
* The base implementation of `_.sum` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(collection, iteratee) {
var result = 0;
baseEach(collection, function(value, index, collection) {
result += +iteratee(value, index, collection) || 0;
});
return result;
}
/**
* The base implementation of `_.uniq` without support for callback shorthands
* and `this` binding.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The function invoked per iteration.
* @returns {Array} Returns the new duplicate-value-free array.
*/
function baseUniq(array, iteratee) {
var index = -1,
indexOf = getIndexOf(),
length = array.length,
isCommon = indexOf == baseIndexOf,
isLarge = isCommon && length >= 200,
seen = isLarge ? createCache() : null,
result = [];
if (seen) {
indexOf = cacheIndexOf;
isCommon = false;
} else {
isLarge = false;
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value, index, array) : value;
if (isCommon && value === value) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (indexOf(seen, computed, 0) < 0) {
if (iteratee || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* returned by `keysFunc`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
var index = -1,
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
/**
* The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
* and `_.takeWhile` without support for callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
*/
function baseWhile(array, predicate, isDrop, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
return isDrop
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to peform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/
function baseWrapperValue(value, actions) {
var result = value;
if (result instanceof LazyWrapper) {
result = result.value();
}
var index = -1,
length = actions.length;
while (++index < length) {
var args = [result],
action = actions[index];
push.apply(args, action.args);
result = action.func.apply(action.thisArg, args);
}
return result;
}
/**
* Performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function binaryIndex(array, value, retHighest) {
var low = 0,
high = array ? array.length : low;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (retHighest ? (computed <= value) : (computed < value)) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return binaryIndexBy(array, value, identity, retHighest);
}
/**
* This function is like `binaryIndex` except that it invokes `iteratee` for
* `value` and each element of `array` to compute their sort ranking. The
* iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The function invoked per iteration.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function binaryIndexBy(array, value, iteratee, retHighest) {
value = iteratee(value);
var low = 0,
high = array ? array.length : 0,
valIsNaN = value !== value,
valIsUndef = typeof value == 'undefined';
while (low < high) {
var mid = floor((low + high) / 2),
computed = iteratee(array[mid]),
isReflexive = computed === computed;
if (valIsNaN) {
var setLow = isReflexive || retHighest;
} else if (valIsUndef) {
setLow = isReflexive && (retHighest || typeof computed != 'undefined');
} else {
setLow = retHighest ? (computed <= value) : (computed < value);
}
if (setLow) {
low = mid + 1;
} else {
high = mid;
}
}
return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (typeof thisArg == 'undefined') {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
/**
* Creates a clone of the given array buffer.
*
* @private
* @param {ArrayBuffer} buffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function bufferClone(buffer) {
return bufferSlice.call(buffer, 0);
}
if (!bufferSlice) {
// PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`.
bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) {
var byteLength = buffer.byteLength,
floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0,
offset = floatLength * FLOAT64_BYTES_PER_ELEMENT,
result = new ArrayBuffer(byteLength);
if (floatLength) {
var view = new Float64Array(result, 0, floatLength);
view.set(new Float64Array(buffer, 0, floatLength));
}
if (byteLength != offset) {
view = new Uint8Array(result, offset);
view.set(new Uint8Array(buffer, offset));
}
return result;
};
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array|Object} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders) {
var holdersLength = holders.length,
argsIndex = -1,
argsLength = nativeMax(args.length - holdersLength, 0),
leftIndex = -1,
leftLength = partials.length,
result = Array(argsLength + leftLength);
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
result[holders[argsIndex]] = args[argsIndex];
}
while (argsLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array|Object} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders) {
var holdersIndex = -1,
holdersLength = holders.length,
argsIndex = -1,
argsLength = nativeMax(args.length - holdersLength, 0),
rightIndex = -1,
rightLength = partials.length,
result = Array(argsLength + rightLength);
while (++argsIndex < argsLength) {
result[argsIndex] = args[argsIndex];
}
var pad = argsIndex;
while (++rightIndex < rightLength) {
result[pad + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
result[pad + holders[holdersIndex]] = args[argsIndex++];
}
return result;
}
/**
* Creates a function that aggregates a collection, creating an accumulator
* object composed from the results of running each element in the collection
* through an iteratee.
*
* **Note:** This function is used to create `_.countBy`, `_.groupBy`, `_.indexBy`,
* and `_.partition`.
*
* @private
* @param {Function} setter The function to set keys and values of the accumulator object.
* @param {Function} [initializer] The function to initialize the accumulator object.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee, thisArg) {
var result = initializer ? initializer() : {};
iteratee = getCallback(iteratee, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
setter(result, value, iteratee(value, index, collection), collection);
}
} else {
baseEach(collection, function(value, key, collection) {
setter(result, value, iteratee(value, key, collection), collection);
});
}
return result;
};
}
/**
* Creates a function that assigns properties of source object(s) to a given
* destination object.
*
* **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return function() {
var args = arguments,
length = args.length,
object = args[0];
if (length < 2 || object == null) {
return object;
}
var customizer = args[length - 2],
thisArg = args[length - 1],
guard = args[3];
if (length > 3 && typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = (length > 2 && typeof thisArg == 'function') ? thisArg : null;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(args[1], args[2], guard)) {
customizer = length == 3 ? null : customizer;
length = 2;
}
var index = 0;
while (++index < length) {
var source = args[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
};
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
var length = collection ? collection.length : 0;
if (!isLength(length)) {
return eachFunc(collection, iteratee);
}
var index = fromRight ? length : -1,
iterable = toObject(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Creates a function that wraps `func` and invokes it with the `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new bound function.
*/
function createBindWrapper(func, thisArg) {
var Ctor = createCtorWrapper(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(thisArg, arguments);
}
return wrapper;
}
/**
* Creates a `Set` cache object to optimize linear searches of large arrays.
*
* @private
* @param {Array} [values] The values to cache.
* @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
*/
var createCache = !(nativeCreate && Set) ? constant(null) : function(values) {
return new SetCache(values);
};
/**
* Creates a function that produces compound words out of the words in a
* given string.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
var index = -1,
array = words(deburr(string)),
length = array.length,
result = '';
while (++index < length) {
result = callback(result, array[index], index);
}
return result;
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtorWrapper(Ctor) {
return function() {
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, arguments);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* Creates a `_.curry` or `_.curryRight` function.
*
* @private
* @param {boolean} flag The curry bit flag.
* @returns {Function} Returns the new curry function.
*/
function createCurry(flag) {
function curryFunc(func, arity, guard) {
if (guard && isIterateeCall(func, arity, guard)) {
arity = null;
}
var result = createWrapper(func, flag, null, null, null, null, null, arity);
result.placeholder = curryFunc.placeholder;
return result;
}
return curryFunc;
}
/**
* Creates a `_.max` or `_.min` function.
*
* @private
* @param {Function} arrayFunc The function to get the extremum value from an array.
* @param {boolean} [isMin] Specify returning the minimum, instead of the maximum,
* extremum value.
* @returns {Function} Returns the new extremum function.
*/
function createExtremum(arrayFunc, isMin) {
return function(collection, iteratee, thisArg) {
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = null;
}
var func = getCallback(),
noIteratee = iteratee == null;
if (!(func === baseCallback && noIteratee)) {
noIteratee = false;
iteratee = func(iteratee, thisArg, 3);
}
if (noIteratee) {
var isArr = isArray(collection);
if (!isArr && isString(collection)) {
iteratee = charAtCallback;
} else {
return arrayFunc(isArr ? collection : toIterable(collection));
}
}
return extremumBy(collection, iteratee, isMin);
};
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new find function.
*/
function createFind(eachFunc, fromRight) {
return function(collection, predicate, thisArg) {
predicate = getCallback(predicate, thisArg, 3);
if (isArray(collection)) {
var index = baseFindIndex(collection, predicate, fromRight);
return index > -1 ? collection[index] : undefined;
}
return baseFind(collection, predicate, eachFunc);
}
}
/**
* Creates a `_.findIndex` or `_.findLastIndex` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new find function.
*/
function createFindIndex(fromRight) {
return function(array, predicate, thisArg) {
if (!(array && array.length)) {
return -1;
}
predicate = getCallback(predicate, thisArg, 3);
return baseFindIndex(array, predicate, fromRight);
};
}
/**
* Creates a `_.findKey` or `_.findLastKey` function.
*
* @private
* @param {Function} objectFunc The function to iterate over an object.
* @returns {Function} Returns the new find function.
*/
function createFindKey(objectFunc) {
return function(object, predicate, thisArg) {
predicate = getCallback(predicate, thisArg, 3);
return baseFind(object, predicate, objectFunc, true);
};
}
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return function() {
var length = arguments.length;
if (!length) {
return function() { return arguments[0]; };
}
var wrapper,
index = fromRight ? length : -1,
leftIndex = 0,
funcs = Array(length);
while ((fromRight ? index-- : ++index < length)) {
var func = funcs[leftIndex++] = arguments[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var funcName = wrapper ? '' : getFuncName(func);
wrapper = funcName == 'wrapper' ? new LodashWrapper([]) : wrapper;
}
index = wrapper ? -1 : length;
while (++index < length) {
func = funcs[index];
funcName = getFuncName(func);
var data = funcName == 'wrapper' ? getData(func) : null;
if (data && isLaziable(data[0])) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
}
}
return function() {
var args = arguments;
if (wrapper && args.length == 1 && isArray(args[0])) {
return wrapper.plant(args[0]).value();
}
var index = 0,
result = funcs[index].apply(this, args);
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
};
}
/**
* Creates a function for `_.forEach` or `_.forEachRight`.
*
* @private
* @param {Function} arrayFunc The function to iterate over an array.
* @param {Function} eachFunc The function to iterate over a collection.
* @returns {Function} Returns the new each function.
*/
function createForEach(arrayFunc, eachFunc) {
return function(collection, iteratee, thisArg) {
return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))
? arrayFunc(collection, iteratee)
: eachFunc(collection, bindCallback(iteratee, thisArg, 3));
};
}
/**
* Creates a function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {Function} objectFunc The function to iterate over an object.
* @returns {Function} Returns the new each function.
*/
function createForIn(objectFunc) {
return function(object, iteratee, thisArg) {
if (typeof iteratee != 'function' || typeof thisArg != 'undefined') {
iteratee = bindCallback(iteratee, thisArg, 3);
}
return objectFunc(object, iteratee, keysIn);
};
}
/**
* Creates a function for `_.forOwn` or `_.forOwnRight`.
*
* @private
* @param {Function} objectFunc The function to iterate over an object.
* @returns {Function} Returns the new each function.
*/
function createForOwn(objectFunc) {
return function(object, iteratee, thisArg) {
if (typeof iteratee != 'function' || typeof thisArg != 'undefined') {
iteratee = bindCallback(iteratee, thisArg, 3);
}
return objectFunc(object, iteratee);
};
}
/**
* Creates a function for `_.padLeft` or `_.padRight`.
*
* @private
* @param {boolean} [fromRight] Specify padding from the right.
* @returns {Function} Returns the new pad function.
*/
function createPadDir(fromRight) {
return function(string, length, chars) {
string = baseToString(string);
return string && ((fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string));
};
}
/**
* Creates a `_.partial` or `_.partialRight` function.
*
* @private
* @param {boolean} flag The partial bit flag.
* @returns {Function} Returns the new partial function.
*/
function createPartial(flag) {
var partialFunc = restParam(function(func, partials) {
var holders = replaceHolders(partials, partialFunc.placeholder);
return createWrapper(func, flag, null, partials, holders);
});
return partialFunc;
}
/**
* Creates a function for `_.reduce` or `_.reduceRight`.
*
* @private
* @param {Function} arrayFunc The function to iterate over an array.
* @param {Function} eachFunc The function to iterate over a collection.
* @returns {Function} Returns the new each function.
*/
function createReduce(arrayFunc, eachFunc) {
return function(collection, iteratee, accumulator, thisArg) {
var initFromArray = arguments.length < 3;
return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))
? arrayFunc(collection, iteratee, accumulator, initFromArray)
: baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
};
}
/**
* Creates a function that wraps `func` and invokes it with optional `this`
* binding of, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & ARY_FLAG,
isBind = bitmask & BIND_FLAG,
isBindKey = bitmask & BIND_KEY_FLAG,
isCurry = bitmask & CURRY_FLAG,
isCurryBound = bitmask & CURRY_BOUND_FLAG,
isCurryRight = bitmask & CURRY_RIGHT_FLAG;
var Ctor = !isBindKey && createCtorWrapper(func),
key = func;
function wrapper() {
// Avoid `arguments` object use disqualifying optimizations by
// converting it to an array before providing it to other functions.
var length = arguments.length,
index = length,
args = Array(length);
while (index--) {
args[index] = arguments[index];
}
if (partials) {
args = composeArgs(args, partials, holders);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight);
}
if (isCurry || isCurryRight) {
var placeholder = wrapper.placeholder,
argsHolders = replaceHolders(args, placeholder);
length -= argsHolders.length;
if (length < arity) {
var newArgPos = argPos ? arrayCopy(argPos) : null,
newArity = nativeMax(arity - length, 0),
newsHolders = isCurry ? argsHolders : null,
newHoldersRight = isCurry ? null : argsHolders,
newPartials = isCurry ? args : null,
newPartialsRight = isCurry ? null : args;
bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
if (!isCurryBound) {
bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
}
var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
result = createHybridWrapper.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return result;
}
}
var thisBinding = isBind ? thisArg : this;
if (isBindKey) {
func = thisBinding[key];
}
if (argPos) {
args = reorder(args, argPos);
}
if (isAry && ary < args.length) {
args.length = ary;
}
var fn = (this && this !== root && this instanceof wrapper) ? (Ctor || createCtorWrapper(func)) : func;
return fn.apply(thisBinding, args);
}
return wrapper;
}
/**
* Creates the padding required for `string` based on the given `length`.
* The `chars` string is truncated if the number of characters exceeds `length`.
*
* @private
* @param {string} string The string to create padding for.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the pad for `string`.
*/
function createPadding(string, length, chars) {
var strLength = string.length;
length = +length;
if (strLength >= length || !nativeIsFinite(length)) {
return '';
}
var padLength = length - strLength;
chars = chars == null ? ' ' : (chars + '');
return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength);
}
/**
* Creates a function that wraps `func` and invokes it with the optional `this`
* binding of `thisArg` and the `partials` prepended to those provided to
* the wrapper.
*
* @private
* @param {Function} func The function to partially apply arguments to.
* @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to the new function.
* @returns {Function} Returns the new bound function.
*/
function createPartialWrapper(func, bitmask, thisArg, partials) {
var isBind = bitmask & BIND_FLAG,
Ctor = createCtorWrapper(func);
function wrapper() {
// Avoid `arguments` object use disqualifying optimizations by
// converting it to an array before providing it `func`.
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(argsLength + leftLength);
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, args);
}
return wrapper;
}
/**
* Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
*
* @private
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {Function} Returns the new index function.
*/
function createSortedIndex(retHighest) {
return function(array, value, iteratee, thisArg) {
var func = getCallback(iteratee);
return (func === baseCallback && iteratee == null)
? binaryIndex(array, value, retHighest)
: binaryIndexBy(array, value, func(iteratee, thisArg, 1), retHighest);
};
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of flags.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
partials = holders = null;
}
length -= (holders ? holders.length : 0);
if (bitmask & PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = null;
}
var data = isBindKey ? null : getData(func),
newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
if (data) {
mergeData(newData, data);
bitmask = newData[1];
arity = newData[9];
}
newData[9] = arity == null
? (isBindKey ? 0 : func.length)
: (nativeMax(arity - length, 0) || 0);
if (bitmask == BIND_FLAG) {
var result = createBindWrapper(newData[0], newData[2]);
} else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
result = createPartialWrapper.apply(undefined, newData);
} else {
result = createHybridWrapper.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setter(result, newData);
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing arrays.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
var index = -1,
arrLength = array.length,
othLength = other.length,
result = true;
if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (result && ++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
result = undefined;
if (customizer) {
result = isLoose
? customizer(othValue, arrValue, index)
: customizer(arrValue, othValue, index);
}
if (typeof result == 'undefined') {
// Recursively compare arrays (susceptible to call stack limits).
if (isLoose) {
var othIndex = othLength;
while (othIndex--) {
othValue = other[othIndex];
result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
if (result) {
break;
}
}
} else {
result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
}
}
}
return !!result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} value The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
// Coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
return +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object)
? other != +other
// But, treat `-0` vs. `+0` as not equal.
: (object == 0 ? ((1 / object) == (1 / other)) : object == +other);
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings primitives and string
// objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
return object == (other + '');
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
var objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isLoose) {
return false;
}
var skipCtor = isLoose,
index = -1;
while (++index < objLength) {
var key = objProps[index],
result = isLoose ? key in other : hasOwnProperty.call(other, key);
if (result) {
var objValue = object[key],
othValue = other[key];
result = undefined;
if (customizer) {
result = isLoose
? customizer(othValue, objValue, key)
: customizer(objValue, othValue, key);
}
if (typeof result == 'undefined') {
// Recursively compare objects (susceptible to call stack limits).
result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB);
}
}
if (!result) {
return false;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (!skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
return false;
}
}
return true;
}
/**
* Gets the extremum value of `collection` invoking `iteratee` for each value
* in `collection` to generate the criterion by which the value is ranked.
* The `iteratee` is invoked with three arguments: (value, index, collection).
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {boolean} [isMin] Specify returning the minimum, instead of the
* maximum, extremum value.
* @returns {*} Returns the extremum value.
*/
function extremumBy(collection, iteratee, isMin) {
var exValue = isMin ? POSITIVE_INFINITY : NEGATIVE_INFINITY,
computed = exValue,
result = computed;
baseEach(collection, function(value, index, collection) {
var current = iteratee(value, index, collection);
if ((isMin ? (current < computed) : (current > computed)) ||
(current === exValue && current === result)) {
computed = current;
result = value;
}
});
return result;
}
/**
* Gets the appropriate "callback" function. If the `_.callback` method is
* customized this function returns the custom method, otherwise it returns
* the `baseCallback` function. If arguments are provided the chosen function
* is invoked with them and its result is returned.
*
* @private
* @returns {Function} Returns the chosen function or its result.
*/
function getCallback(func, thisArg, argCount) {
var result = lodash.callback || callback;
result = result === callback ? baseCallback : result;
return argCount ? result(func, thisArg, argCount) : result;
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
var getFuncName = (function() {
if (!support.funcNames) {
return constant('');
}
if (constant.name == 'constant') {
return baseProperty('name');
}
return function(func) {
var result = func.name,
array = realNames[result],
length = array ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
};
}());
/**
* Gets the appropriate "indexOf" function. If the `_.indexOf` method is
* customized this function returns the custom method, otherwise it returns
* the `baseIndexOf` function. If arguments are provided the chosen function
* is invoked with them and its result is returned.
*
* @private
* @returns {Function|number} Returns the chosen function or its result.
*/
function getIndexOf(collection, target, fromIndex) {
var result = lodash.indexOf || indexOf;
result = result === indexOf ? baseIndexOf : result;
return collection ? result(collection, target, fromIndex) : result;
}
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} [transforms] The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms ? transforms.length : 0;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add array properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
var Ctor = object.constructor;
if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
Ctor = Object;
}
return new Ctor;
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return bufferClone(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
var buffer = object.buffer;
return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
var result = new Ctor(object.source, reFlags.exec(object));
result.lastIndex = object.lastIndex;
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = +value;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number') {
var length = object.length,
prereq = isLength(length) && isIndex(index, length);
} else {
prereq = type == 'string' && index in object;
}
if (prereq) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func);
return !!funcName && func === lodash[funcName] && funcName in LazyWrapper.prototype;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value));
}
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers required to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
* augment function arguments, making the order in which they are executed important,
* preventing the merging of metadata. However, we make an exception for a safe
* common case where curried functions have `_.ary` and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < ARY_FLAG;
var isCombo =
(srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
(srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
(srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = arrayCopy(value);
}
// Use source `ary` if it's smaller.
if (srcBitmask & ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
/**
* A specialized version of `_.pick` that picks `object` properties specified
* by the `props` array.
*
* @private
* @param {Object} object The source object.
* @param {string[]} props The property names to pick.
* @returns {Object} Returns the new object.
*/
function pickByArray(object, props) {
object = toObject(object);
var index = -1,
length = props.length,
result = {};
while (++index < length) {
var key = props[index];
if (key in object) {
result[key] = object[key];
}
}
return result;
}
/**
* A specialized version of `_.pick` that picks `object` properties `predicate`
* returns truthy for.
*
* @private
* @param {Object} object The source object.
* @param {Function} predicate The function invoked per iteration.
* @returns {Object} Returns the new object.
*/
function pickByCallback(object, predicate) {
var result = {};
baseForIn(object, function(value, key, object) {
if (predicate(value, key, object)) {
result[key] = value;
}
});
return result;
}
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = arrayCopy(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity function
* to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = (function() {
var count = 0,
lastCalled = 0;
return function(key, value) {
var stamp = now(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return key;
}
} else {
count = 0;
}
return baseSetData(key, value);
};
}());
/**
* A fallback implementation of `_.isPlainObject` which checks if `value`
* is an object created by the `Object` constructor or has a `[[Prototype]]`
* of `null`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
*/
function shimIsPlainObject(value) {
var Ctor,
support = lodash.support;
// Exit early for non `Object` objects.
if (!(isObjectLike(value) && objToString.call(value) == objectTag) ||
(!hasOwnProperty.call(value, 'constructor') &&
(Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
var result;
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
baseForIn(value, function(subValue, key) {
result = key;
});
return typeof result == 'undefined' || hasOwnProperty.call(value, result);
}
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length,
support = lodash.support;
var allowIndexes = length && isLength(length) &&
(isArray(object) || (support.nonEnumArgs && isArguments(object)));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
/**
* Converts `value` to an array-like object if it is not one.
*
* @private
* @param {*} value The value to process.
* @returns {Array|Object} Returns the array-like object.
*/
function toIterable(value) {
if (value == null) {
return [];
}
if (!isLength(value.length)) {
return values(value);
}
return isObject(value) ? value : Object(value);
}
/**
* Converts `value` to an object if it is not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
return wrapper instanceof LazyWrapper
? wrapper.clone()
: new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
* If `collection` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the new array containing chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if (guard ? isIterateeCall(array, size, guard) : size == null) {
size = 1;
} else {
size = nativeMax(+size || 1, 1);
}
var index = 0,
length = array ? array.length : 0,
resIndex = -1,
result = Array(ceil(length / size));
while (index < length) {
result[++resIndex] = baseSlice(array, index, (index += size));
}
return result;
}
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array ? array.length : 0,
resIndex = -1,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[++resIndex] = value;
}
}
return result;
}
/**
* Creates an array excluding all values of the provided arrays using
* `SameValueZero` for equality comparisons.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.difference([1, 2, 3], [4, 2]);
* // => [1, 3]
*/
var difference = restParam(function(array, values) {
return (isArray(array) || isArguments(array))
? baseDifference(array, baseFlatten(values, false, true))
: [];
});
/**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function drop(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
return baseSlice(array, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function dropRight(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
n = length - (+n || 0);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* bound to `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that match the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRightWhile([1, 2, 3], function(n) {
* return n > 1;
* });
* // => [1]
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* // using the `_.matches` callback shorthand
* _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
* // => ['barney', 'fred']
*
* // using the `_.matchesProperty` callback shorthand
* _.pluck(_.dropRightWhile(users, 'active', false), 'user');
* // => ['barney']
*
* // using the `_.property` callback shorthand
* _.pluck(_.dropRightWhile(users, 'active'), 'user');
* // => ['barney', 'fred', 'pebbles']
*/
function dropRightWhile(array, predicate, thisArg) {
return (array && array.length)
? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
: [];
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* bound to `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropWhile([1, 2, 3], function(n) {
* return n < 3;
* });
* // => [3]
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* // using the `_.matches` callback shorthand
* _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
* // => ['fred', 'pebbles']
*
* // using the `_.matchesProperty` callback shorthand
* _.pluck(_.dropWhile(users, 'active', false), 'user');
* // => ['pebbles']
*
* // using the `_.property` callback shorthand
* _.pluck(_.dropWhile(users, 'active'), 'user');
* // => ['barney', 'fred', 'pebbles']
*/
function dropWhile(array, predicate, thisArg) {
return (array && array.length)
? baseWhile(array, getCallback(predicate, thisArg, 3), true)
: [];
}
/**
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8], '*', 1, 2);
* // => [4, '*', 8]
*/
function fill(array, value, start, end) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
start = 0;
end = length;
}
return baseFill(array, value, start, end);
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(chr) {
* return chr.user == 'barney';
* });
* // => 0
*
* // using the `_.matches` callback shorthand
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // using the `_.matchesProperty` callback shorthand
* _.findIndex(users, 'active', false);
* // => 0
*
* // using the `_.property` callback shorthand
* _.findIndex(users, 'active');
* // => 2
*/
var findIndex = createFindIndex();
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(chr) {
* return chr.user == 'pebbles';
* });
* // => 2
*
* // using the `_.matches` callback shorthand
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // using the `_.matchesProperty` callback shorthand
* _.findLastIndex(users, 'active', false);
* // => 2
*
* // using the `_.property` callback shorthand
* _.findLastIndex(users, 'active');
* // => 0
*/
var findLastIndex = createFindIndex(true);
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @alias head
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.first([1, 2, 3]);
* // => 1
*
* _.first([]);
* // => undefined
*/
function first(array) {
return array ? array[0] : undefined;
}
/**
* Flattens a nested array. If `isDeep` is `true` the array is recursively
* flattened, otherwise it is only flattened a single level.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to flatten.
* @param {boolean} [isDeep] Specify a deep flatten.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, 3, [4]]]);
* // => [1, 2, 3, [4]]
*
* // using `isDeep`
* _.flatten([1, [2, 3, [4]]], true);
* // => [1, 2, 3, 4]
*/
function flatten(array, isDeep, guard) {
var length = array ? array.length : 0;
if (guard && isIterateeCall(array, isDeep, guard)) {
isDeep = false;
}
return length ? baseFlatten(array, isDeep) : [];
}
/**
* Recursively flattens a nested array.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to recursively flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, 3, [4]]]);
* // => [1, 2, 3, 4]
*/
function flattenDeep(array) {
var length = array ? array.length : 0;
return length ? baseFlatten(array, true) : [];
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using `SameValueZero` for equality comparisons. If `fromIndex` is negative,
* it is used as the offset from the end of `array`. If `array` is sorted
* providing `true` for `fromIndex` performs a faster binary search.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
* to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // using `fromIndex`
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*
* // performing a binary search
* _.indexOf([1, 1, 2, 2], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
if (typeof fromIndex == 'number') {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
} else if (fromIndex) {
var index = binaryIndex(array, value),
other = array[index];
if (value === value ? (value === other) : (other !== other)) {
return index;
}
return -1;
}
return baseIndexOf(array, value, fromIndex || 0);
}
/**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/
function initial(array) {
return dropRight(array, 1);
}
/**
* Creates an array of unique values in all provided arrays using `SameValueZero`
* for equality comparisons.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of shared values.
* @example
* _.intersection([1, 2], [4, 2], [2, 1]);
* // => [2]
*/
function intersection() {
var args = [],
argsIndex = -1,
argsLength = arguments.length,
caches = [],
indexOf = getIndexOf(),
isCommon = indexOf == baseIndexOf;
while (++argsIndex < argsLength) {
var value = arguments[argsIndex];
if (isArray(value) || isArguments(value)) {
args.push(value);
caches.push((isCommon && value.length >= 120) ? createCache(argsIndex && value) : null);
}
}
argsLength = args.length;
var array = args[0],
index = -1,
length = array ? array.length : 0,
result = [],
seen = caches[0];
outer:
while (++index < length) {
value = array[index];
if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
argsIndex = argsLength;
while (--argsIndex) {
var cache = caches[argsIndex];
if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value, 0)) < 0) {
continue outer;
}
}
if (seen) {
seen.push(value);
}
result.push(value);
}
}
return result;
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array ? array.length : 0;
return length ? array[length - 1] : undefined;
}
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=array.length-1] The index to search from
* or `true` to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // using `fromIndex`
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*
* // performing a binary search
* _.lastIndexOf([1, 1, 2, 2], 2, true);
* // => 3
*/
function lastIndexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = length;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
} else if (fromIndex) {
index = binaryIndex(array, value, true) - 1;
var other = array[index];
if (value === value ? (value === other) : (other !== other)) {
return index;
}
return -1;
}
if (value !== value) {
return indexOfNaN(array, index, true);
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Removes all provided values from `array` using `SameValueZero` for equality
* comparisons.
*
* **Notes:**
* - Unlike `_.without`, this method mutates `array`
* - [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except
* that `NaN` matches `NaN`
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3, 1, 2, 3];
*
* _.pull(array, 2, 3);
* console.log(array);
* // => [1, 1]
*/
function pull() {
var args = arguments,
array = args[0];
if (!(array && array.length)) {
return array;
}
var index = 0,
indexOf = getIndexOf(),
length = args.length;
while (++index < length) {
var fromIndex = 0,
value = args[index];
while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
splice.call(array, fromIndex, 1);
}
}
return array;
}
/**
* Removes elements from `array` corresponding to the given indexes and returns
* an array of the removed elements. Indexes may be specified as an array of
* indexes or as individual arguments.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove,
* specified as individual indexes or arrays of indexes.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [5, 10, 15, 20];
* var evens = _.pullAt(array, 1, 3);
*
* console.log(array);
* // => [5, 15]
*
* console.log(evens);
* // => [10, 20]
*/
var pullAt = restParam(function(array, indexes) {
array || (array = []);
indexes = baseFlatten(indexes);
var length = indexes.length,
result = baseAt(array, indexes);
indexes.sort(baseCompareAscending);
while (length--) {
var index = parseFloat(indexes[length]);
if (index != previous && isIndex(index)) {
var previous = index;
splice.call(array, index, 1);
}
}
return result;
});
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is bound to
* `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** Unlike `_.filter`, this method mutates `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to modify.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [];
predicate = getCallback(predicate, thisArg, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
splice.call(array, index--, 1);
length--;
}
}
return result;
}
/**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @alias tail
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.rest([1, 2, 3]);
* // => [2, 3]
*/
function rest(array) {
return drop(array, 1);
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This function is used instead of `Array#slice` to support node
* lists in IE < 9 and to ensure dense arrays are returned.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function slice(array, start, end) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value` should
* be inserted into `array` in order to maintain its sort order. If an iteratee
* function is provided it is invoked for `value` and each element of `array`
* to compute their sort ranking. The iteratee is bound to `thisArg` and
* invoked with one argument; (value).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*
* _.sortedIndex([4, 4, 5, 5], 5);
* // => 2
*
* var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
*
* // using an iteratee function
* _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
* return this.data[word];
* }, dict);
* // => 1
*
* // using the `_.property` callback shorthand
* _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
* // => 1
*/
var sortedIndex = createSortedIndex();
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 4, 5, 5], 5);
* // => 4
*/
var sortedLastIndex = createSortedIndex(true);
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/
function take(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (guard ? isIterateeCall(array, n, guard) : n == null) {
n = 1;
}
n = length - (+n || 0);
return baseSlice(array, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is bound to `thisArg`
* and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRightWhile([1, 2, 3], function(n) {
* return n > 1;
* });
* // => [2, 3]
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* // using the `_.matches` callback shorthand
* _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
* // => ['pebbles']
*
* // using the `_.matchesProperty` callback shorthand
* _.pluck(_.takeRightWhile(users, 'active', false), 'user');
* // => ['fred', 'pebbles']
*
* // using the `_.property` callback shorthand
* _.pluck(_.takeRightWhile(users, 'active'), 'user');
* // => []
*/
function takeRightWhile(array, predicate, thisArg) {
return (array && array.length)
? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
: [];
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is bound to
* `thisArg` and invoked with three arguments: (value, index, array).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeWhile([1, 2, 3], function(n) {
* return n < 3;
* });
* // => [1, 2]
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false},
* { 'user': 'pebbles', 'active': true }
* ];
*
* // using the `_.matches` callback shorthand
* _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
* // => ['barney']
*
* // using the `_.matchesProperty` callback shorthand
* _.pluck(_.takeWhile(users, 'active', false), 'user');
* // => ['barney', 'fred']
*
* // using the `_.property` callback shorthand
* _.pluck(_.takeWhile(users, 'active'), 'user');
* // => []
*/
function takeWhile(array, predicate, thisArg) {
return (array && array.length)
? baseWhile(array, getCallback(predicate, thisArg, 3))
: [];
}
/**
* Creates an array of unique values, in order, of the provided arrays using
* `SameValueZero` for equality comparisons.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([1, 2], [4, 2], [2, 1]);
* // => [1, 2, 4]
*/
var union = restParam(function(arrays) {
return baseUniq(baseFlatten(arrays, false, true));
});
/**
* Creates a duplicate-value-free version of an array using `SameValueZero`
* for equality comparisons. Providing `true` for `isSorted` performs a faster
* search algorithm for sorted arrays. If an iteratee function is provided it
* is invoked for each value in the array to generate the criterion by which
* uniqueness is computed. The `iteratee` is bound to `thisArg` and invoked
* with three arguments: (value, index, array).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @alias unique
* @category Array
* @param {Array} array The array to inspect.
* @param {boolean} [isSorted] Specify the array is sorted.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1]);
* // => [1, 2]
*
* // using `isSorted`
* _.uniq([1, 1, 2], true);
* // => [1, 2]
*
* // using an iteratee function
* _.uniq([1, 2.5, 1.5, 2], function(n) {
* return this.floor(n);
* }, Math);
* // => [1, 2.5]
*
* // using the `_.property` callback shorthand
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniq(array, isSorted, iteratee, thisArg) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
if (isSorted != null && typeof isSorted != 'boolean') {
thisArg = iteratee;
iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted;
isSorted = false;
}
var func = getCallback();
if (!(func === baseCallback && iteratee == null)) {
iteratee = func(iteratee, thisArg, 3);
}
return (isSorted && getIndexOf() == baseIndexOf)
? sortedUniq(array, iteratee)
: baseUniq(array, iteratee);
}
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-`_.zip`
* configuration.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*
* _.unzip(zipped);
* // => [['fred', 'barney'], [30, 40], [true, false]]
*/
function unzip(array) {
var index = -1,
length = (array && array.length && arrayMax(arrayMap(array, getLength))) >>> 0,
result = Array(length);
while (++index < length) {
result[index] = arrayMap(array, baseProperty(index));
}
return result;
}
/**
* Creates an array excluding all provided values using `SameValueZero` for
* equality comparisons.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to filter.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.without([1, 2, 1, 3], 1, 2);
* // => [3]
*/
var without = restParam(function(array, values) {
return (isArray(array) || isArguments(array))
? baseDifference(array, values)
: [];
});
/**
* Creates an array that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the provided arrays.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of values.
* @example
*
* _.xor([1, 2], [4, 2]);
* // => [1, 4]
*/
function xor() {
var index = -1,
length = arguments.length;
while (++index < length) {
var array = arguments[index];
if (isArray(array) || isArguments(array)) {
var result = result
? baseDifference(result, array).concat(baseDifference(array, result))
: array;
}
}
return result ? baseUniq(result) : [];
}
/**
* Creates an array of grouped elements, the first of which contains the first
* elements of the given arrays, the second of which contains the second elements
* of the given arrays, and so on.
*
* @static
* @memberOf _
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*/
var zip = restParam(unzip);
/**
* The inverse of `_.pairs`; this method returns an object composed from arrays
* of property names and values. Provide either a single two dimensional array,
* e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
* and one of corresponding values.
*
* @static
* @memberOf _
* @alias object
* @category Array
* @param {Array} props The property names.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject([['fred', 30], ['barney', 40]]);
* // => { 'fred': 30, 'barney': 40 }
*
* _.zipObject(['fred', 'barney'], [30, 40]);
* // => { 'fred': 30, 'barney': 40 }
*/
function zipObject(props, values) {
var index = -1,
length = props ? props.length : 0,
result = {};
if (length && !values && !isArray(props[0])) {
values = [];
}
while (++index < length) {
var key = props[index];
if (values) {
result[key] = values[index];
} else if (key) {
result[key[0]] = key[1];
}
}
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object that wraps `value` with explicit method
* chaining enabled.
*
* @static
* @memberOf _
* @category Chain
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _.chain(users)
* .sortBy('age')
* .map(function(chr) {
* return chr.user + ' is ' + chr.age;
* })
* .first()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}
/**
* This method invokes `interceptor` and returns `value`. The interceptor is
* bound to `thisArg` and invoked with one argument; (value). The purpose of
* this method is to "tap into" a method chain in order to perform operations
* on intermediate results within the chain.
*
* @static
* @memberOf _
* @category Chain
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @param {*} [thisArg] The `this` binding of `interceptor`.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor, thisArg) {
interceptor.call(thisArg, value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
*
* @static
* @memberOf _
* @category Chain
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @param {*} [thisArg] The `this` binding of `interceptor`.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
*/
function thru(value, interceptor, thisArg) {
return interceptor.call(thisArg, value);
}
/**
* Enables explicit method chaining on the wrapper object.
*
* @name chain
* @memberOf _
* @category Chain
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // without explicit chaining
* _(users).first();
* // => { 'user': 'barney', 'age': 36 }
*
* // with explicit chaining
* _(users).chain()
* .first()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/
function wrapperChain() {
return chain(this);
}
/**
* Executes the chained sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @category Chain
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapper = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapper = wrapper.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapper.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}
/**
* Creates a clone of the chained sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @category Chain
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapper = _(array).map(function(value) {
* return Math.pow(value, 2);
* });
*
* var other = [3, 4];
* var otherWrapper = wrapper.plant(other);
*
* otherWrapper.value();
* // => [9, 16]
*
* wrapper.value();
* // => [1, 4]
*/
function wrapperPlant(value) {
var result,
parent = this;
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
if (result) {
previous.__wrapped__ = clone;
} else {
result = clone;
}
var previous = clone;
parent = parent.__wrapped__;
}
previous.__wrapped__ = value;
return result;
}
/**
* Reverses the wrapped array so the first element becomes the last, the
* second element becomes the second to last, and so on.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @category Chain
* @returns {Object} Returns the new reversed `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
if (this.__actions__.length) {
value = new LazyWrapper(this);
}
return new LodashWrapper(value.reverse(), this.__chain__);
}
return this.thru(function(value) {
return value.reverse();
});
}
/**
* Produces the result of coercing the unwrapped value to a string.
*
* @name toString
* @memberOf _
* @category Chain
* @returns {string} Returns the coerced string value.
* @example
*
* _([1, 2, 3]).toString();
* // => '1,2,3'
*/
function wrapperToString() {
return (this.value() + '');
}
/**
* Executes the chained sequence to extract the unwrapped value.
*
* @name value
* @memberOf _
* @alias run, toJSON, valueOf
* @category Chain
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements corresponding to the given keys, or indexes,
* of `collection`. Keys may be specified as individual arguments or as arrays
* of keys.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(number|number[]|string|string[])} [props] The property names
* or indexes of elements to pick, specified individually or in arrays.
* @returns {Array} Returns the new array of picked elements.
* @example
*
* _.at(['a', 'b', 'c'], [0, 2]);
* // => ['a', 'c']
*
* _.at(['barney', 'fred', 'pebbles'], 0, 2);
* // => ['barney', 'pebbles']
*/
var at = restParam(function(collection, props) {
var length = collection ? collection.length : 0;
if (isLength(length)) {
collection = toIterable(collection);
}
return baseAt(collection, baseFlatten(props));
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is the number of times the key was returned by `iteratee`.
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(n) {
* return Math.floor(n);
* });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(n) {
* return this.floor(n);
* }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
});
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* The predicate is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false }
* ];
*
* // using the `_.matches` callback shorthand
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // using the `_.matchesProperty` callback shorthand
* _.every(users, 'active', false);
* // => true
*
* // using the `_.property` callback shorthand
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
predicate = null;
}
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
predicate = getCallback(predicate, thisArg, 3);
}
return func(collection, predicate);
}
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
* invoked with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias select
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new filtered array.
* @example
*
* _.filter([4, 5, 6], function(n) {
* return n % 2 == 0;
* });
* // => [4, 6]
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // using the `_.matches` callback shorthand
* _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
* // => ['barney']
*
* // using the `_.matchesProperty` callback shorthand
* _.pluck(_.filter(users, 'active', false), 'user');
* // => ['fred']
*
* // using the `_.property` callback shorthand
* _.pluck(_.filter(users, 'active'), 'user');
* // => ['barney']
*/
function filter(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayFilter : baseFilter;
predicate = getCallback(predicate, thisArg, 3);
return func(collection, predicate);
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is bound to `thisArg` and
* invoked with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias detect
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.result(_.find(users, function(chr) {
* return chr.age < 40;
* }), 'user');
* // => 'barney'
*
* // using the `_.matches` callback shorthand
* _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
* // => 'pebbles'
*
* // using the `_.matchesProperty` callback shorthand
* _.result(_.find(users, 'active', false), 'user');
* // => 'fred'
*
* // using the `_.property` callback shorthand
* _.result(_.find(users, 'active'), 'user');
* // => 'barney'
*/
var find = createFind(baseEach);
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(baseEachRight, true);
/**
* Performs a deep comparison between each element in `collection` and the
* source object, returning the first element that has equivalent property
* values.
*
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
* numbers, `Object` objects, regexes, and strings. Objects are compared by
* their own, not inherited, enumerable properties. For comparing a single
* own or inherited property value see `_.matchesProperty`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Object} source The object of property values to match.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
* // => 'barney'
*
* _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
* // => 'fred'
*/
function findWhere(collection, source) {
return find(collection, baseMatches(source));
}
/**
* Iterates over elements of `collection` invoking `iteratee` for each element.
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection). Iterator functions may exit iteration early
* by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a `length` property
* are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
* may be used for object iteration.
*
* @static
* @memberOf _
* @alias each
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2]).forEach(function(n) {
* console.log(n);
* }).value();
* // => logs each value from left to right and returns the array
*
* _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
* console.log(n, key);
* });
* // => logs each value-key pair and returns the object (iteration order is not guaranteed)
*/
var forEach = createForEach(arrayEach, baseEach);
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @alias eachRight
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2]).forEachRight(function(n) {
* console.log(n);
* }).value();
* // => logs each value from right to left and returns the array
*/
var forEachRight = createForEach(arrayEachRight, baseEachRight);
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is an array of the elements responsible for generating the key.
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([4.2, 6.1, 6.4], function(n) {
* return Math.floor(n);
* });
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* _.groupBy([4.2, 6.1, 6.4], function(n) {
* return this.floor(n);
* }, Math);
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* // using the `_.property` callback shorthand
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
result[key] = [value];
}
});
/**
* Checks if `value` is in `collection` using `SameValueZero` for equality
* comparisons. If `fromIndex` is negative, it is used as the offset from
* the end of `collection`.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @alias contains, include
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {*} target The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
* @returns {boolean} Returns `true` if a matching element is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
* // => true
*
* _.includes('pebbles', 'eb');
* // => true
*/
function includes(collection, target, fromIndex, guard) {
var length = collection ? collection.length : 0;
if (!isLength(length)) {
collection = values(collection);
length = collection.length;
}
if (!length) {
return false;
}
if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
fromIndex = 0;
} else {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
}
return (typeof collection == 'string' || !isArray(collection) && isString(collection))
? (fromIndex < length && collection.indexOf(target, fromIndex) > -1)
: (getIndexOf(collection, target, fromIndex) > -1);
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through `iteratee`. The corresponding value
* of each key is the last element responsible for generating the key. The
* iteratee function is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var keyData = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.indexBy(keyData, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(keyData, function(object) {
* return String.fromCharCode(object.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(keyData, function(object) {
* return this.fromCharCode(object.code);
* }, String);
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*/
var indexBy = createAggregator(function(result, value, key) {
result[key] = value;
});
/**
* Invokes the method named by `methodName` on each element in `collection`,
* returning an array of the results of each invoked method. Any additional
* arguments are provided to each invoked method. If `methodName` is a function
* it is invoked for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|string} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invoke = restParam(function(collection, methodName, args) {
var index = -1,
isFunc = typeof methodName == 'function',
length = collection ? collection.length : 0,
result = isLength(length) ? Array(length) : [];
baseEach(collection, function(value) {
var func = isFunc ? methodName : (value != null && value[methodName]);
result[++index] = func ? func.apply(value, args) : undefined;
});
return result;
});
/**
* Creates an array of values by running each element in `collection` through
* `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
* arguments: (value, index|key, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* Many lodash methods are guarded to work as interatees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, `drop`,
* `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, `parseInt`,
* `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimLeft`,
* `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, `uniq`, and `words`
*
* @static
* @memberOf _
* @alias collect
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* create a `_.property` or `_.matches` style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new mapped array.
* @example
*
* function timesThree(n) {
* return n * 3;
* }
*
* _.map([1, 2], timesThree);
* // => [3, 6]
*
* _.map({ 'a': 1, 'b': 2 }, timesThree);
* // => [3, 6] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // using the `_.property` callback shorthand
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee, thisArg) {
var func = isArray(collection) ? arrayMap : baseMap;
iteratee = getCallback(iteratee, thisArg, 3);
return func(collection, iteratee);
}
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, while the second of which
* contains elements `predicate` returns falsey for. The predicate is bound
* to `thisArg` and invoked with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* _.partition([1, 2, 3], function(n) {
* return n % 2;
* });
* // => [[1, 3], [2]]
*
* _.partition([1.2, 2.3, 3.4], function(n) {
* return this.floor(n) % 2;
* }, Math);
* // => [[1.2, 3.4], [2.3]]
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* var mapper = function(array) {
* return _.pluck(array, 'user');
* };
*
* // using the `_.matches` callback shorthand
* _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
* // => [['pebbles'], ['barney', 'fred']]
*
* // using the `_.matchesProperty` callback shorthand
* _.map(_.partition(users, 'active', false), mapper);
* // => [['barney', 'pebbles'], ['fred']]
*
* // using the `_.property` callback shorthand
* _.map(_.partition(users, 'active'), mapper);
* // => [['fred'], ['barney', 'pebbles']]
*/
var partition = createAggregator(function(result, value, key) {
result[key ? 0 : 1].push(value);
}, function() { return [[], []]; });
/**
* Gets the value of `key` from all elements in `collection`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string} key The key of the property to pluck.
* @returns {Array} Returns the property values.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.pluck(users, 'user');
* // => ['barney', 'fred']
*
* var userIndex = _.indexBy(users, 'user');
* _.pluck(userIndex, 'age');
* // => [36, 40] (iteration order is not guaranteed)
*/
function pluck(collection, key) {
return map(collection, baseProperty(key));
}
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` through `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not provided the first element of `collection` is used as the initial
* value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as interatees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `includes`, `merge`, `sortByAll`, and `sortByOrder`
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* });
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
* result[key] = n * 3;
* return result;
* }, {});
* // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
*/
var reduce = createReduce(arrayReduce, baseEach);
/**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @alias foldr
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
var reduceRight = createReduce(arrayReduceRight, baseEachRight);
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Array} Returns the new filtered array.
* @example
*
* _.reject([1, 2, 3, 4], function(n) {
* return n % 2 == 0;
* });
* // => [1, 3]
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* // using the `_.matches` callback shorthand
* _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
* // => ['barney']
*
* // using the `_.matchesProperty` callback shorthand
* _.pluck(_.reject(users, 'active', false), 'user');
* // => ['fred']
*
* // using the `_.property` callback shorthand
* _.pluck(_.reject(users, 'active'), 'user');
* // => ['barney']
*/
function reject(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayFilter : baseFilter;
predicate = getCallback(predicate, thisArg, 3);
return func(collection, function(value, index, collection) {
return !predicate(value, index, collection);
});
}
/**
* Gets a random element or `n` random elements from a collection.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to sample.
* @param {number} [n] The number of elements to sample.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {*} Returns the random sample(s).
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*
* _.sample([1, 2, 3, 4], 2);
* // => [3, 1]
*/
function sample(collection, n, guard) {
if (guard ? isIterateeCall(collection, n, guard) : n == null) {
collection = toIterable(collection);
var length = collection.length;
return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
}
var result = shuffle(collection);
result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length);
return result;
}
/**
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
collection = toIterable(collection);
var index = -1,
length = collection.length,
result = Array(length);
while (++index < length) {
var rand = baseRandom(0, index);
if (index != rand) {
result[index] = result[rand];
}
result[rand] = collection[index];
}
return result;
}
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable properties for objects.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the size of `collection`.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
var length = collection ? collection.length : 0;
return isLength(length) ? length : keys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* The function returns as soon as it finds a passing value and does not iterate
* over the entire collection. The predicate is bound to `thisArg` and invoked
* with three arguments: (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias any
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // using the `_.matches` callback shorthand
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // using the `_.matchesProperty` callback shorthand
* _.some(users, 'active', false);
* // => true
*
* // using the `_.property` callback shorthand
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, thisArg) {
var func = isArray(collection) ? arraySome : baseSome;
if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
predicate = null;
}
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
predicate = getCallback(predicate, thisArg, 3);
}
return func(collection, predicate);
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection through `iteratee`. This method performs
* a stable sort, that is, it preserves the original sort order of equal elements.
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Array|Function|Object|string} [iteratee=_.identity] The function
* invoked per iteration. If a property name or an object is provided it is
* used to create a `_.property` or `_.matches` style callback respectively.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the new sorted array.
* @example
*
* _.sortBy([1, 2, 3], function(n) {
* return Math.sin(n);
* });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(n) {
* return this.sin(n);
* }, Math);
* // => [3, 1, 2]
*
* var users = [
* { 'user': 'fred' },
* { 'user': 'pebbles' },
* { 'user': 'barney' }
* ];
*
* // using the `_.property` callback shorthand
* _.pluck(_.sortBy(users, 'user'), 'user');
* // => ['barney', 'fred', 'pebbles']
*/
function sortBy(collection, iteratee, thisArg) {
if (collection == null) {
return [];
}
var index = -1,
length = collection.length,
result = isLength(length) ? Array(length) : [];
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = null;
}
iteratee = getCallback(iteratee, thisArg, 3);
baseEach(collection, function(value, key, collection) {
result[++index] = { 'criteria': iteratee(value, key, collection), 'index': index, 'value': value };
});
return baseSortBy(result, compareAscending);
}
/**
* This method is like `_.sortBy` except that it sorts by property names
* instead of an iteratee function.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(string|string[])} props The property names to sort by,
* specified as individual property names or arrays of property names.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 26 },
* { 'user': 'fred', 'age': 30 }
* ];
*
* _.map(_.sortByAll(users, ['user', 'age']), _.values);
* // => [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
*/
function sortByAll() {
var args = arguments,
collection = args[0],
guard = args[3],
index = 0,
length = args.length - 1;
if (collection == null) {
return [];
}
var props = Array(length);
while (index < length) {
props[index] = args[++index];
}
if (guard && isIterateeCall(args[1], args[2], guard)) {
props = args[1];
}
return baseSortByOrder(collection, baseFlatten(props), []);
}
/**
* This method is like `_.sortByAll` except that it allows specifying the
* sort orders of the property names to sort by. A truthy value in `orders`
* will sort the corresponding property name in ascending order while a
* falsey value will sort it in descending order.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string[]} props The property names to sort by.
* @param {boolean[]} orders The sort orders of `props`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 26 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 }
* ];
*
* // sort by `user` in ascending order and by `age` in descending order
* _.map(_.sortByOrder(users, ['user', 'age'], [true, false]), _.values);
* // => [['barney', 36], ['barney', 26], ['fred', 40], ['fred', 30]]
*/
function sortByOrder(collection, props, orders, guard) {
if (collection == null) {
return [];
}
if (guard && isIterateeCall(props, orders, guard)) {
orders = null;
}
if (!isArray(props)) {
props = props == null ? [] : [props];
}
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseSortByOrder(collection, props, orders);
}
/**
* Performs a deep comparison between each element in `collection` and the
* source object, returning an array of all elements that have equivalent
* property values.
*
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
* numbers, `Object` objects, regexes, and strings. Objects are compared by
* their own, not inherited, enumerable properties. For comparing a single
* own or inherited property value see `_.matchesProperty`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to search.
* @param {Object} source The object of property values to match.
* @returns {Array} Returns the new filtered array.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
* { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
* ];
*
* _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
* // => ['barney']
*
* _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
* // => ['fred']
*/
function where(collection, source) {
return filter(collection, baseMatches(source));
}
/*------------------------------------------------------------------------*/
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Date
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
var now = nativeNow || function() {
return new Date().getTime();
};
/*------------------------------------------------------------------------*/
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it is called `n` or more times.
*
* @static
* @memberOf _
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => logs 'done saving!' after the two async saves have completed
*/
function after(n, func) {
if (typeof func != 'function') {
if (typeof n == 'function') {
var temp = n;
n = func;
func = temp;
} else {
throw new TypeError(FUNC_ERROR_TEXT);
}
}
n = nativeIsFinite(n = +n) ? n : 0;
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that accepts up to `n` arguments ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the new function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
if (guard && isIterateeCall(func, n, guard)) {
n = null;
}
n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
return createWrapper(func, ARY_FLAG, null, null, null, null, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it is called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery('#add').on('click', _.before(5, addContactToList));
* // => allows adding up to 4 contacts to the list
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
if (typeof n == 'function') {
var temp = n;
n = func;
func = temp;
} else {
throw new TypeError(FUNC_ERROR_TEXT);
}
}
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
} else {
func = null;
}
return result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and prepends any additional `_.bind` arguments to those provided to the
* bound function.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind` this method does not set the `length`
* property of bound functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var greet = function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* };
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // using placeholders
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = restParam(function(func, thisArg, partials) {
var bitmask = BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, bind.placeholder);
bitmask |= PARTIAL_FLAG;
}
return createWrapper(func, bitmask, thisArg, partials, holders);
});
/**
* Binds methods of an object to the object itself, overwriting the existing
* method. Method names may be specified as individual arguments or as arrays
* of method names. If no method names are provided all enumerable function
* properties, own and inherited, of `object` are bound.
*
* **Note:** This method does not set the `length` property of bound functions.
*
* @static
* @memberOf _
* @category Function
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} [methodNames] The object method names to bind,
* specified as individual method names or arrays of method names.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'onClick': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view);
* jQuery('#docs').on('click', view.onClick);
* // => logs 'clicked docs' when the element is clicked
*/
var bindAll = restParam(function(object, methodNames) {
methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
var index = -1,
length = methodNames.length;
while (++index < length) {
var key = methodNames[index];
object[key] = createWrapper(object[key], BIND_FLAG, object);
}
return object;
});
/**
* Creates a function that invokes the method at `object[key]` and prepends
* any additional `_.bindKey` arguments to those provided to the bound function.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist.
* See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @category Function
* @param {Object} object The object the method belongs to.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // using placeholders
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
var bindKey = restParam(function(object, key, partials) {
var bitmask = BIND_FLAG | BIND_KEY_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, bindKey.placeholder);
bitmask |= PARTIAL_FLAG;
}
return createWrapper(key, bitmask, object, partials, holders);
});
/**
* Creates a function that accepts one or more arguments of `func` that when
* called either invokes `func` returning its result, if all `func` arguments
* have been provided, or returns a function that accepts one or more of the
* remaining `func` arguments, and so on. The arity of `func` may be specified
* if `func.length` is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method does not set the `length` property of curried functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // using placeholders
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
var curry = createCurry(CURRY_FLAG);
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method does not set the `length` property of curried functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // using placeholders
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
var curryRight = createCurry(CURRY_RIGHT_FLAG);
/**
* Creates a function that delays invoking `func` until after `wait` milliseconds
* have elapsed since the last time it was invoked. The created function comes
* with a `cancel` method to cancel delayed invocations. Provide an options
* object to indicate that `func` should be invoked on the leading and/or
* trailing edge of the `wait` timeout. Subsequent calls to the debounced
* function return the result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it is invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : (+wait || 0);
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
var isCalled = trailingCall;
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
if (timeoutId) {
clearTimeout(timeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (trailing || (maxWait !== wait)) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // logs 'deferred' after one or more milliseconds
*/
var defer = restParam(function(func, args) {
return baseDelay(func, 1, args);
});
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => logs 'later' after one second
*/
var delay = restParam(function(func, wait, args) {
return baseDelay(func, wait, args);
});
/**
* Creates a function that returns the result of invoking the provided
* functions with the `this` binding of the created function, where each
* successive invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @category Function
* @param {...Function} [funcs] Functions to invoke.
* @returns {Function} Returns the new function.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow(_.add, square);
* addSquare(1, 2);
* // => 9
*/
var flow = createFlow();
/**
* This method is like `_.flow` except that it creates a function that
* invokes the provided functions from right to left.
*
* @static
* @memberOf _
* @alias backflow, compose
* @category Function
* @param {...Function} [funcs] Functions to invoke.
* @returns {Function} Returns the new function.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight(square, _.add);
* addSquare(1, 2);
* // => 9
*/
var flowRight = createFlow(true);
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is coerced to a string and used as the
* cache key. The `func` is invoked with the `this` binding of the memoized
* function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the [`Map`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object)
* method interface of `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var upperCase = _.memoize(function(string) {
* return string.toUpperCase();
* });
*
* upperCase('fred');
* // => 'FRED'
*
* // modifying the result cache
* upperCase.cache.set('fred', 'BARNEY');
* upperCase('fred');
* // => 'BARNEY'
*
* // replacing `_.memoize.Cache`
* var object = { 'user': 'fred' };
* var other = { 'user': 'barney' };
* var identity = _.memoize(_.identity);
*
* identity(object);
* // => { 'user': 'fred' }
* identity(other);
* // => { 'user': 'fred' }
*
* _.memoize.Cache = WeakMap;
* var identity = _.memoize(_.identity);
*
* identity(object);
* // => { 'user': 'fred' }
* identity(other);
* // => { 'user': 'barney' }
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
cache = memoized.cache,
key = resolver ? resolver.apply(this, args) : args[0];
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
cache.set(key, result);
return result;
};
memoized.cache = new memoize.Cache;
return memoized;
}
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
return !predicate.apply(this, arguments);
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first call. The `func` is invoked
* with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` invokes `createApplication` once
*/
function once(func) {
return before(func, 2);
}
/**
* Creates a function that invokes `func` with `partial` arguments prepended
* to those provided to the new function. This method is like `_.bind` except
* it does **not** alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method does not set the `length` property of partially
* applied functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) {
* return greeting + ' ' + name;
* };
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // using placeholders
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = createPartial(PARTIAL_FLAG);
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to those provided to the new function.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method does not set the `length` property of partially
* applied functions.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) {
* return greeting + ' ' + name;
* };
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // using placeholders
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified indexes where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes,
* specified as individual indexes or arrays of indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, 2, 0, 1);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*
* var map = _.rearg(_.map, [1, 0]);
* map(function(n) {
* return n * 3;
* }, [1, 2, 3]);
* // => [3, 6, 9]
*/
var rearg = restParam(function(func, indexes) {
return createWrapper(func, REARG_FLAG, null, null, null, baseFlatten(indexes));
});
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(typeof start == 'undefined' ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
/**
* Creates a function that invokes `func` with the `this` binding of the created
* function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
*
* **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to spread arguments over.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* // with a Promise
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
*/
function spread(func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function(array) {
return func.apply(this, array);
};
}
/**
* Creates a function that only invokes `func` at most once per every `wait`
* milliseconds. The created function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the throttled function return the result of the last
* `func` call.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify invoking on the leading
* edge of the timeout.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
* 'trailing': false
* }));
*
* // cancel a trailing throttled call
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
debounceOptions.leading = leading;
debounceOptions.maxWait = +wait;
debounceOptions.trailing = trailing;
return debounce(func, wait, debounceOptions);
}
/**
* Creates a function that provides `value` to the wrapper function as its
* first argument. Any additional arguments provided to the function are
* appended to those provided to the wrapper function. The wrapper is invoked
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Function
* @param {*} value The value to wrap.
* @param {Function} wrapper The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, &amp; pebbles</p>'
*/
function wrap(value, wrapper) {
wrapper = wrapper == null ? identity : wrapper;
return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []);
}
/*------------------------------------------------------------------------*/
/**
* Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
* otherwise they are assigned by reference. If `customizer` is provided it is
* invoked to produce the cloned values. If `customizer` returns `undefined`
* cloning is handled by the method instead. The `customizer` is bound to
* `thisArg` and invoked with two argument; (value [, index|key, object]).
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
* The enumerable properties of `arguments` objects and objects created by
* constructors other than `Object` are cloned to plain `Object` objects. An
* empty object is returned for uncloneable values such as functions, DOM nodes,
* Maps, Sets, and WeakMaps.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {*} Returns the cloned value.
* @example
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* var shallow = _.clone(users);
* shallow[0] === users[0];
* // => true
*
* var deep = _.clone(users, true);
* deep[0] === users[0];
* // => false
*
* // using a customizer callback
* var el = _.clone(document.body, function(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* });
*
* el === document.body
* // => false
* el.nodeName
* // => BODY
* el.childNodes.length;
* // => 0
*/
function clone(value, isDeep, customizer, thisArg) {
if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
isDeep = false;
}
else if (typeof isDeep == 'function') {
thisArg = customizer;
customizer = isDeep;
isDeep = false;
}
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1);
return baseClone(value, isDeep, customizer);
}
/**
* Creates a deep clone of `value`. If `customizer` is provided it is invoked
* to produce the cloned values. If `customizer` returns `undefined` cloning
* is handled by the method instead. The `customizer` is bound to `thisArg`
* and invoked with two argument; (value [, index|key, object]).
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
* The enumerable properties of `arguments` objects and objects created by
* constructors other than `Object` are cloned to plain `Object` objects. An
* empty object is returned for uncloneable values such as functions, DOM nodes,
* Maps, Sets, and WeakMaps.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to deep clone.
* @param {Function} [customizer] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {*} Returns the deep cloned value.
* @example
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* var deep = _.cloneDeep(users);
* deep[0] === users[0];
* // => false
*
* // using a customizer callback
* var el = _.cloneDeep(document.body, function(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* });
*
* el === document.body
* // => false
* el.nodeName
* // => BODY
* el.childNodes.length;
* // => 20
*/
function cloneDeep(value, customizer, thisArg) {
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1);
return baseClone(value, true, customizer);
}
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
var length = isObjectLike(value) ? value.length : undefined;
return isLength(length) && objToString.call(value) == argsTag;
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
}
/**
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
*/
function isDate(value) {
return isObjectLike(value) && objToString.call(value) == dateTag;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement(value) {
return !!value && value.nodeType === 1 && isObjectLike(value) &&
(objToString.call(value).indexOf('Element') > -1);
}
// Fallback for environments without DOM support.
if (!support.dom) {
isElement = function(value) {
return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
};
}
/**
* Checks if `value` is empty. A value is considered empty unless it is an
* `arguments` object, array, string, or jQuery-like collection with a length
* greater than `0` or an object with own enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
var length = value.length;
if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) ||
(isObjectLike(value) && isFunction(value.splice)))) {
return !length;
}
return !keys(value).length;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent. If `customizer` is provided it is invoked to compare values.
* If `customizer` returns `undefined` comparisons are handled by the method
* instead. The `customizer` is bound to `thisArg` and invoked with three
* arguments: (value, other [, index|key]).
*
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
* numbers, `Object` objects, regexes, and strings. Objects are compared by
* their own, not inherited, enumerable properties. Functions and DOM nodes
* are **not** supported. Provide a customizer function to extend support
* for comparing other values.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* object == other;
* // => false
*
* _.isEqual(object, other);
* // => true
*
* // using a customizer callback
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqual(array, other, function(value, other) {
* if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
* return true;
* }
* });
* // => true
*/
function isEqual(value, other, customizer, thisArg) {
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3);
if (!customizer && isStrictComparable(value) && isStrictComparable(other)) {
return value === other;
}
var result = customizer ? customizer(value, other) : undefined;
return typeof result == 'undefined' ? baseIsEqual(value, other, customizer) : !!result;
}
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
}
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on [`Number.isFinite`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite).
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(10);
* // => true
*
* _.isFinite('10');
* // => false
*
* _.isFinite(true);
* // => false
*
* _.isFinite(Object(10));
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
var isFinite = nativeNumIsFinite || function(value) {
return typeof value == 'number' && nativeIsFinite(value);
};
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return objToString.call(value) == funcTag;
};
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return type == 'function' || (!!value && type == 'object');
}
/**
* Performs a deep comparison between `object` and `source` to determine if
* `object` contains equivalent property values. If `customizer` is provided
* it is invoked to compare values. If `customizer` returns `undefined`
* comparisons are handled by the method instead. The `customizer` is bound
* to `thisArg` and invoked with three arguments: (value, other, index|key).
*
* **Note:** This method supports comparing properties of arrays, booleans,
* `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
* and DOM nodes are **not** supported. Provide a customizer function to extend
* support for comparing other values.
*
* @static
* @memberOf _
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'user': 'fred', 'age': 40 };
*
* _.isMatch(object, { 'age': 40 });
* // => true
*
* _.isMatch(object, { 'age': 36 });
* // => false
*
* // using a customizer callback
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatch(object, source, function(value, other) {
* return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
* });
* // => true
*/
function isMatch(object, source, customizer, thisArg) {
var props = keys(source),
length = props.length;
if (!length) {
return true;
}
if (object == null) {
return false;
}
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3);
if (!customizer && length == 1) {
var key = props[0],
value = source[key];
if (isStrictComparable(value)) {
return value === object[key] && (typeof value != 'undefined' || (key in toObject(object)));
}
}
var values = Array(length),
strictCompareFlags = Array(length);
while (length--) {
value = values[length] = source[props[length]];
strictCompareFlags[length] = isStrictComparable(value);
}
return baseIsMatch(toObject(object), props, values, strictCompareFlags, customizer);
}
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
* which returns `true` for `undefined` and other non-numeric values.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some host objects in IE.
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (objToString.call(value) == funcTag) {
return reNative.test(fnToString.call(value));
}
return isObjectLike(value) && reHostCtor.test(value);
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
* as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isNumber(8.4);
* // => true
*
* _.isNumber(NaN);
* // => true
*
* _.isNumber('8.4');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* **Note:** This method assumes objects created by the `Object` constructor
* have no inherited enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
if (!(value && objToString.call(value) == objectTag)) {
return false;
}
var valueOf = value.valueOf,
objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
return objProto
? (value == objProto || getPrototypeOf(value) == objProto)
: shimIsPlainObject(value);
};
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
function isRegExp(value) {
return (isObjectLike(value) && objToString.call(value) == regexpTag) || false;
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
/**
* Checks if `value` is `undefined`.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
/**
* Converts `value` to an array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* (function() {
* return _.toArray(arguments).slice(1);
* }(1, 2, 3));
* // => [2, 3]
*/
function toArray(value) {
var length = value ? value.length : 0;
if (!isLength(length)) {
return values(value);
}
if (!length) {
return [];
}
return arrayCopy(value);
}
/**
* Converts `value` to a plain object flattening inherited enumerable
* properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return baseCopy(value, keysIn(value));
}
/*------------------------------------------------------------------------*/
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources overwrite property assignments of previous sources.
* If `customizer` is provided it is invoked to produce the assigned values.
* The `customizer` is bound to `thisArg` and invoked with five arguments:
* (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
* // => { 'user': 'fred', 'age': 40 }
*
* // using a customizer callback
* var defaults = _.partialRight(_.assign, function(value, other) {
* return typeof value == 'undefined' ? other : value;
* });
*
* defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
var assign = createAssigner(baseAssign);
/**
* Creates an object that inherits from the given `prototype` object. If a
* `properties` object is provided its own enumerable properties are assigned
* to the created object.
*
* @static
* @memberOf _
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties, guard) {
var result = baseCreate(prototype);
if (guard && isIterateeCall(prototype, properties, guard)) {
properties = null;
}
return properties ? baseCopy(properties, result, keys(properties)) : result;
}
/**
* Assigns own enumerable properties of source object(s) to the destination
* object for all destination properties that resolve to `undefined`. Once a
* property is set, additional values of the same property are ignored.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
var defaults = restParam(function(args) {
var object = args[0];
if (object == null) {
return object;
}
args.push(assignDefaults);
return assign.apply(undefined, args);
});
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(chr) {
* return chr.age < 40;
* });
* // => 'barney' (iteration order is not guaranteed)
*
* // using the `_.matches` callback shorthand
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // using the `_.matchesProperty` callback shorthand
* _.findKey(users, 'active', false);
* // => 'fred'
*
* // using the `_.property` callback shorthand
* _.findKey(users, 'active');
* // => 'barney'
*/
var findKey = createFindKey(baseForOwn);
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to search.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {string|undefined} Returns the key of the matched element, else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(chr) {
* return chr.age < 40;
* });
* // => returns `pebbles` assuming `_.findKey` returns `barney`
*
* // using the `_.matches` callback shorthand
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // using the `_.matchesProperty` callback shorthand
* _.findLastKey(users, 'active', false);
* // => 'fred'
*
* // using the `_.property` callback shorthand
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
var findLastKey = createFindKey(baseForOwnRight);
/**
* Iterates over own and inherited enumerable properties of an object invoking
* `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
* with three arguments: (value, key, object). Iterator functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
*/
var forIn = createForIn(baseFor);
/**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
*/
var forInRight = createForIn(baseForRight);
/**
* Iterates over own enumerable properties of an object invoking `iteratee`
* for each property. The `iteratee` is bound to `thisArg` and invoked with
* three arguments: (value, key, object). Iterator functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => logs 'a' and 'b' (iteration order is not guaranteed)
*/
var forOwn = createForOwn(baseForOwn);
/**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns `object`.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
*/
var forOwnRight = createForOwn(baseForOwnRight);
/**
* Creates an array of function property names from all enumerable properties,
* own and inherited, of `object`.
*
* @static
* @memberOf _
* @alias methods
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the new array of property names.
* @example
*
* _.functions(_);
* // => ['after', 'ary', 'assign', ...]
*/
function functions(object) {
return baseFunctions(object, keysIn(object));
}
/**
* Checks if `key` exists as a direct property of `object` instead of an
* inherited property.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @param {string} key The key to check.
* @returns {boolean} Returns `true` if `key` is a direct property, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 3 };
*
* _.has(object, 'b');
* // => true
*/
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite property
* assignments of previous values unless `multiValue` is `true`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to invert.
* @param {boolean} [multiValue] Allow multiple values per key.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*
* // with `multiValue`
* _.invert(object, true);
* // => { '1': ['a', 'c'], '2': ['b'] }
*/
function invert(object, multiValue, guard) {
if (guard && isIterateeCall(object, multiValue, guard)) {
multiValue = null;
}
var index = -1,
props = keys(object),
length = props.length,
result = {};
while (++index < length) {
var key = props[index],
value = object[key];
if (multiValue) {
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}
else {
result[value] = key;
}
}
return result;
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
if (object) {
var Ctor = object.constructor,
length = object.length;
}
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object != 'function' && (length && isLength(length)))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* Creates an object with the same keys as `object` and values generated by
* running each own enumerable property of `object` through `iteratee`. The
* iteratee function is bound to `thisArg` and invoked with three arguments:
* (value, key, object).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Object} Returns the new mapped object.
* @example
*
* _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
* return n * 3;
* });
* // => { 'a': 3, 'b': 6 }
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* // using the `_.property` callback shorthand
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee, thisArg) {
var result = {};
iteratee = getCallback(iteratee, thisArg, 3);
baseForOwn(object, function(value, key, object) {
result[key] = iteratee(value, key, object);
});
return result;
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* overwrite property assignments of previous sources. If `customizer` is
* provided it is invoked to produce the merged values of the destination and
* source properties. If `customizer` returns `undefined` merging is handled
* by the method instead. The `customizer` is bound to `thisArg` and invoked
* with five arguments: (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize merging properties.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*
* // using a customizer callback
* var object = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var other = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(object, other, function(a, b) {
* if (_.isArray(a)) {
* return a.concat(b);
* }
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
*/
var merge = createAssigner(baseMerge);
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable properties of `object` that are not omitted.
* Property names may be specified as individual arguments or as arrays of
* property names. If `predicate` is provided it is invoked for each property
* of `object` omitting the properties `predicate` returns truthy for. The
* predicate is bound to `thisArg` and invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {Function|...(string|string[])} [predicate] The function invoked per
* iteration or property names to omit, specified as individual property
* names or arrays of property names.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'user': 'fred', 'age': 40 };
*
* _.omit(object, 'age');
* // => { 'user': 'fred' }
*
* _.omit(object, _.isNumber);
* // => { 'user': 'fred' }
*/
var omit = restParam(function(object, props) {
if (object == null) {
return {};
}
if (typeof props[0] != 'function') {
var props = arrayMap(baseFlatten(props), String);
return pickByArray(object, baseDifference(keysIn(object), props));
}
var predicate = bindCallback(props[0], props[1], 3);
return pickByCallback(object, function(value, key, object) {
return !predicate(value, key, object);
});
});
/**
* Creates a two dimensional array of the key-value pairs for `object`,
* e.g. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the new array of key-value pairs.
* @example
*
* _.pairs({ 'barney': 36, 'fred': 40 });
* // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
*/
function pairs(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
var key = props[index];
result[index] = [key, object[key]];
}
return result;
}
/**
* Creates an object composed of the picked `object` properties. Property
* names may be specified as individual arguments or as arrays of property
* names. If `predicate` is provided it is invoked for each property of `object`
* picking the properties `predicate` returns truthy for. The predicate is
* bound to `thisArg` and invoked with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {Function|...(string|string[])} [predicate] The function invoked per
* iteration or property names to pick, specified as individual property
* names or arrays of property names.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'user': 'fred', 'age': 40 };
*
* _.pick(object, 'user');
* // => { 'user': 'fred' }
*
* _.pick(object, _.isString);
* // => { 'user': 'fred' }
*/
var pick = restParam(function(object, props) {
if (object == null) {
return {};
}
return typeof props[0] == 'function'
? pickByCallback(object, bindCallback(props[0], props[1], 3))
: pickByArray(object, baseFlatten(props));
});
/**
* Resolves the value of property `key` on `object`. If the value of `key` is
* a function it is invoked with the `this` binding of `object` and its result
* is returned, else the property value is returned. If the property value is
* `undefined` the `defaultValue` is used in its place.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {string} key The key of the property to resolve.
* @param {*} [defaultValue] The value returned if the property value
* resolves to `undefined`.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'user': 'fred', 'age': _.constant(40) };
*
* _.result(object, 'user');
* // => 'fred'
*
* _.result(object, 'age');
* // => 40
*
* _.result(object, 'status', 'busy');
* // => 'busy'
*
* _.result(object, 'status', _.constant('busy'));
* // => 'busy'
*/
function result(object, key, defaultValue) {
var value = object == null ? undefined : object[key];
if (typeof value == 'undefined') {
value = defaultValue;
}
return isFunction(value) ? value.call(object) : value;
}
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own enumerable
* properties through `iteratee`, with each invocation potentially mutating
* the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
* with four arguments: (accumulator, value, key, object). Iterator functions
* may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Object
* @param {Array|Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* });
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
* result[key] = n * 3;
* });
* // => { 'a': 3, 'b': 6 }
*/
function transform(object, iteratee, accumulator, thisArg) {
var isArr = isArray(object) || isTypedArray(object);
iteratee = getCallback(iteratee, thisArg, 4);
if (accumulator == null) {
if (isArr || isObject(object)) {
var Ctor = object.constructor;
if (isArr) {
accumulator = isArray(object) ? new Ctor : [];
} else {
accumulator = baseCreate(isFunction(Ctor) && Ctor.prototype);
}
} else {
accumulator = {};
}
}
(isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Creates an array of the own enumerable property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return baseValues(object, keys(object));
}
/**
* Creates an array of the own and inherited enumerable property values
* of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
return baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
* Checks if `n` is between `start` and up to but not including, `end`. If
* `end` is not specified it is set to `start` with `start` then set to `0`.
*
* @static
* @memberOf _
* @category Number
* @param {number} n The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `n` is in the range, else `false`.
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*/
function inRange(value, start, end) {
start = +start || 0;
if (typeof end === 'undefined') {
end = start;
start = 0;
} else {
end = +end || 0;
}
return value >= start && value < end;
}
/**
* Produces a random number between `min` and `max` (inclusive). If only one
* argument is provided a number between `0` and the given number is returned.
* If `floating` is `true`, or either `min` or `max` are floats, a floating-point
* number is returned instead of an integer.
*
* @static
* @memberOf _
* @category Number
* @param {number} [min=0] The minimum possible value.
* @param {number} [max=1] The maximum possible value.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(min, max, floating) {
if (floating && isIterateeCall(min, max, floating)) {
max = floating = null;
}
var noMin = min == null,
noMax = max == null;
if (floating == null) {
if (noMax && typeof min == 'boolean') {
floating = min;
min = 1;
}
else if (typeof max == 'boolean') {
floating = max;
noMax = true;
}
}
if (noMin && noMax) {
max = 1;
noMax = false;
}
min = +min || 0;
if (noMax) {
max = min;
min = 0;
} else {
max = +max || 0;
}
if (floating || min % 1 || max % 1) {
var rand = nativeRandom();
return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
}
return baseRandom(min, max);
}
/*------------------------------------------------------------------------*/
/**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar');
* // => 'fooBar'
*
* _.camelCase('__foo_bar__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
});
/**
* Capitalizes the first character of `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('fred');
* // => 'Fred'
*/
function capitalize(string) {
string = baseToString(string);
return string && (string.charAt(0).toUpperCase() + string.slice(1));
}
/**
* Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = baseToString(string);
return string && string.replace(reLatin1, deburrLetter).replace(reComboMarks, '');
}
/**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to search.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search from.
* @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = baseToString(string);
target = (target + '');
var length = string.length;
position = typeof position == 'undefined'
? length
: nativeMin(position < 0 ? 0 : (+position || 0), length);
position -= target.length;
return position >= 0 && string.indexOf(target, position) == position;
}
/**
* Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
* their corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional characters
* use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't require escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value.
* See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* Backticks are escaped because in Internet Explorer < 9, they can break out
* of attribute values or HTML comments. See [#102](https://html5sec.org/#102),
* [#108](https://html5sec.org/#108), and [#133](https://html5sec.org/#133) of
* the [HTML5 Security Cheatsheet](https://html5sec.org/) for more details.
*
* When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
* to reduce XSS vectors.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, &amp; pebbles'
*/
function escape(string) {
// Reset `lastIndex` because in IE < 9 `String#replace` does not.
string = baseToString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
* Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
* "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
*/
function escapeRegExp(string) {
string = baseToString(string);
return (string && reHasRegExpChars.test(string))
? string.replace(reRegExpChars, '\\$&')
: string;
}
/**
* Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__foo_bar__');
* // => 'foo-bar'
*/
var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
});
/**
* Pads `string` on the left and right sides if it is shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = baseToString(string);
length = +length;
var strLength = string.length;
if (strLength >= length || !nativeIsFinite(length)) {
return string;
}
var mid = (length - strLength) / 2,
leftLength = floor(mid),
rightLength = ceil(mid);
chars = createPadding('', rightLength, chars);
return chars.slice(0, leftLength) + string + chars;
}
/**
* Pads `string` on the left side if it is shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padLeft('abc', 6);
* // => ' abc'
*
* _.padLeft('abc', 6, '_-');
* // => '_-_abc'
*
* _.padLeft('abc', 3);
* // => 'abc'
*/
var padLeft = createPadDir();
/**
* Pads `string` on the right side if it is shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padRight('abc', 6);
* // => 'abc '
*
* _.padRight('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padRight('abc', 3);
* // => 'abc'
*/
var padRight = createPadDir(true);
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
* in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
* of `parseInt`.
*
* @static
* @memberOf _
* @category String
* @param {string} string The string to convert.
* @param {number} [radix] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard && isIterateeCall(string, radix, guard)) {
radix = 0;
}
return nativeParseInt(string, radix);
}
// Fallback for environments with pre-ES5 implementations.
if (nativeParseInt(whitespace + '08') != 8) {
parseInt = function(string, radix, guard) {
// Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
// Chrome fails to trim leading <BOM> whitespace characters.
// See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
string = trim(string);
return nativeParseInt(string, radix || (reHexPrefix.test(string) ? 16 : 10));
};
}
/**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=0] The number of times to repeat the string.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/
function repeat(string, n) {
var result = '';
string = baseToString(string);
n = +n;
if (n < 1 || !string || !nativeIsFinite(n)) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = floor(n / 2);
string += string;
} while (n);
return result;
}
/**
* Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*
* _.snakeCase('--foo-bar');
* // => 'foo_bar'
*/
var snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
});
/**
* Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__foo_bar__');
* // => 'Foo Bar'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
});
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to search.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = baseToString(string);
position = position == null
? 0
: nativeMin(position < 0 ? 0 : (+position || 0), string.length);
return string.lastIndexOf(target, position) == position;
}
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is provided it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options] The options object.
* @param {RegExp} [options.escape] The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate] The "evaluate" delimiter.
* @param {Object} [options.imports] An object to import into the template as free variables.
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
* @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
* @param {string} [options.variable] The data object variable name.
* @param- {Object} [otherOptions] Enables the legacy `options` param signature.
* @returns {Function} Returns the compiled template function.
* @example
*
* // using the "interpolate" delimiter to create a compiled template
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // using the HTML "escape" delimiter to escape data property values
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b>&lt;script&gt;</b>'
*
* // using the "evaluate" delimiter to execute JavaScript and generate HTML
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // using the internal `print` function in "evaluate" delimiters
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // using the ES delimiter as an alternative to the default "interpolate" delimiter
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // using custom template delimiters
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // using backslashes to treat delimiters as plain text
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // using the `imports` option to import `jQuery` as `jq`
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // using the `sourceURL` option to specify a custom sourceURL for the template
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
*
* // using the `variable` option to ensure a with-statement isn't used in the compiled template
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // using the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and a stack trace
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, otherOptions) {
// Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (otherOptions && isIterateeCall(string, options, otherOptions)) {
options = otherOptions = null;
}
string = baseToString(string);
options = baseAssign(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
var imports = baseAssign(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
var sourceURL = '//# sourceURL=' +
('sourceURL' in options
? options.sourceURL
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
var value = string;
string = baseToString(string);
if (!string) {
return string;
}
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
}
chars = (chars + '');
return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
}
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimLeft(' abc ');
* // => 'abc '
*
* _.trimLeft('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimLeft(string, chars, guard) {
var value = string;
string = baseToString(string);
if (!string) {
return string;
}
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
return string.slice(trimmedLeftIndex(string));
}
return string.slice(charsLeftIndex(string, (chars + '')));
}
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimRight(' abc ');
* // => ' abc'
*
* _.trimRight('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimRight(string, chars, guard) {
var value = string;
string = baseToString(string);
if (!string) {
return string;
}
if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
return string.slice(0, trimmedRightIndex(string) + 1);
}
return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
}
/**
* Truncates `string` if it is longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object|number} [options] The options object or maximum string length.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {string} Returns the truncated string.
* @example
*
* _.trunc('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.trunc('hi-diddly-ho there, neighborino', 24);
* // => 'hi-diddly-ho there, n...'
*
* _.trunc('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.trunc('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.trunc('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
function trunc(string, options, guard) {
if (guard && isIterateeCall(string, options, guard)) {
options = null;
}
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (options != null) {
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? (+options.length || 0) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
} else {
length = +options || 0;
}
}
string = baseToString(string);
if (length >= string.length) {
return string;
}
var end = length - omission.length;
if (end < 1) {
return omission;
}
var result = string.slice(0, end);
if (separator == null) {
return result + omission;
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
newEnd,
substring = string.slice(0, end);
if (!separator.global) {
separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
newEnd = match.index;
}
result = result.slice(0, newEnd == null ? end : newEnd);
}
} else if (string.indexOf(separator, end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
/**
* The inverse of `_.escape`; this method converts the HTML entities
* `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
* corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional HTML
* entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, &amp; pebbles');
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
string = baseToString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
if (guard && isIterateeCall(string, pattern, guard)) {
pattern = null;
}
string = baseToString(string);
return string.match(pattern || reWords) || [];
}
/*------------------------------------------------------------------------*/
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Utility
* @param {Function} func The function to attempt.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // avoid throwing errors for invalid selectors
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = restParam(function(func, args) {
try {
return func.apply(undefined, args);
} catch(e) {
return isError(e) ? e : new Error(e);
}
});
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and arguments of the created function. If `func` is a property name the
* created callback returns the property value for a given element. If `func`
* is an object the created callback returns `true` for elements that contain
* the equivalent object properties, otherwise it returns `false`.
*
* @static
* @memberOf _
* @alias iteratee
* @category Utility
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // wrap to create custom callback shorthands
* _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
* if (!match) {
* return callback(func, thisArg);
* }
* return function(object) {
* return match[2] == 'gt'
* ? object[match[1]] > match[3]
* : object[match[1]] < match[3];
* };
* });
*
* _.filter(users, 'age__gt36');
* // => [{ 'user': 'fred', 'age': 40 }]
*/
function callback(func, thisArg, guard) {
if (guard && isIterateeCall(func, thisArg, guard)) {
thisArg = null;
}
return isObjectLike(func)
? matches(func)
: baseCallback(func, thisArg);
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'user': 'fred' };
* var getter = _.constant(object);
*
* getter() === object;
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function which performs a deep comparison between a given object
* and `source`, returning `true` if the given object has equivalent property
* values, else `false`.
*
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
* numbers, `Object` objects, regexes, and strings. Objects are compared by
* their own, not inherited, enumerable properties. For comparing a single
* own or inherited property value see `_.matchesProperty`.
*
* @static
* @memberOf _
* @category Utility
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, _.matches({ 'age': 40, 'active': false }));
* // => [{ 'user': 'fred', 'age': 40, 'active': false }]
*/
function matches(source) {
return baseMatches(baseClone(source, true));
}
/**
* Creates a function which compares the property value of `key` on a given
* object to `value`.
*
* **Note:** This method supports comparing arrays, booleans, `Date` objects,
* numbers, `Object` objects, regexes, and strings. Objects are compared by
* their own, not inherited, enumerable properties.
*
* @static
* @memberOf _
* @category Utility
* @param {string} key The key of the property to get.
* @param {*} value The value to compare.
* @returns {Function} Returns the new function.
* @example
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* _.find(users, _.matchesProperty('user', 'fred'));
* // => { 'user': 'fred' }
*/
function matchesProperty(key, value) {
return baseMatchesProperty(key + '', baseClone(value, true));
}
/**
* Adds all own enumerable function properties of a source object to the
* destination object. If `object` is a function then methods are added to
* its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function
* for mixins to avoid conflicts caused by modifying the original.
*
* @static
* @memberOf _
* @category Utility
* @param {Function|Object} [object=this] object The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options] The options object.
* @param {boolean} [options.chain=true] Specify whether the functions added
* are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* // use `_.runInContext` to avoid conflicts (esp. in Node.js)
* var _ = require('lodash').runInContext();
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/
function mixin(object, source, options) {
if (options == null) {
var isObj = isObject(source),
props = isObj && keys(source),
methodNames = props && props.length && baseFunctions(source, props);
if (!(methodNames ? methodNames.length : isObj)) {
methodNames = false;
options = source;
source = object;
object = this;
}
}
if (!methodNames) {
methodNames = baseFunctions(source, keys(source));
}
var chain = true,
index = -1,
isFunc = isFunction(object),
length = methodNames.length;
if (options === false) {
chain = false;
} else if (isObject(options) && 'chain' in options) {
chain = options.chain;
}
while (++index < length) {
var methodName = methodNames[index],
func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = (function(func) {
return function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = arrayCopy(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
var args = [this.value()];
push.apply(args, arguments);
return func.apply(object, args);
};
}(func));
}
}
return object;
}
/**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utility
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
context._ = oldDash;
return this;
}
/**
* A no-operation function which returns `undefined` regardless of the
* arguments it receives.
*
* @static
* @memberOf _
* @category Utility
* @example
*
* var object = { 'user': 'fred' };
*
* _.noop(object) === undefined;
* // => true
*/
function noop() {
// No operation performed.
}
/**
* Creates a function which returns the property value of `key` on a given object.
*
* @static
* @memberOf _
* @category Utility
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
* @example
*
* var users = [
* { 'user': 'fred' },
* { 'user': 'barney' }
* ];
*
* var getName = _.property('user');
*
* _.map(users, getName);
* // => ['fred', 'barney']
*
* _.pluck(_.sortBy(users, getName), 'user');
* // => ['barney', 'fred']
*/
function property(key) {
return baseProperty(key + '');
}
/**
* The opposite of `_.property`; this method creates a function which returns
* the property value of a given key on `object`.
*
* @static
* @memberOf _
* @category Utility
* @param {Object} object The object to inspect.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'a': 3, 'b': 1, 'c': 2 };
*
* _.map(['a', 'c'], _.propertyOf(object));
* // => [3, 2]
*
* _.sortBy(['a', 'b', 'c'], _.propertyOf(object));
* // => ['b', 'c', 'a']
*/
function propertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. If `end` is not specified it is
* set to `start` with `start` then set to `0`. If `start` is less than `end`
* a zero-length range is created unless a negative `step` is specified.
*
* @static
* @memberOf _
* @category Utility
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the new array of numbers.
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
function range(start, end, step) {
if (step && isIterateeCall(start, end, step)) {
end = step = null;
}
start = +start || 0;
step = step == null ? 1 : (+step || 0);
if (end == null) {
end = start;
start = 0;
} else {
end = +end || 0;
}
// Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
// See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
var index = -1,
length = nativeMax(ceil((end - start) / (step || 1)), 0),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* Invokes the iteratee function `n` times, returning an array of the results
* of each invocation. The `iteratee` is bound to `thisArg` and invoked with
* one argument; (index).
*
* @static
* @memberOf _
* @category Utility
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {Array} Returns the array of results.
* @example
*
* var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
* // => [3, 6, 4]
*
* _.times(3, function(n) {
* mage.castSpell(n);
* });
* // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` respectively
*
* _.times(3, function(n) {
* this.cast(n);
* }, mage);
* // => also invokes `mage.castSpell(n)` three times
*/
function times(n, iteratee, thisArg) {
n = +n;
// Exit early to avoid a JSC JIT bug in Safari 8
// where `Array(0)` is treated as `Array(1)`.
if (n < 1 || !nativeIsFinite(n)) {
return [];
}
var index = -1,
result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
iteratee = bindCallback(iteratee, thisArg, 1);
while (++index < n) {
if (index < MAX_ARRAY_LENGTH) {
result[index] = iteratee(index);
} else {
iteratee(index);
}
}
return result;
}
/**
* Generates a unique ID. If `prefix` is provided the ID is appended to it.
*
* @static
* @memberOf _
* @category Utility
* @param {string} [prefix] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return baseToString(prefix) + id;
}
/*------------------------------------------------------------------------*/
/**
* Adds two numbers.
*
* @static
* @memberOf _
* @category Math
* @param {number} augend The first number to add.
* @param {number} addend The second number to add.
* @returns {number} Returns the sum.
* @example
*
* _.add(6, 4);
* // => 10
*/
function add(augend, addend) {
return augend + addend;
}
/**
* Gets the maximum value of `collection`. If `collection` is empty or falsey
* `-Infinity` is returned. If an iteratee function is provided it is invoked
* for each value in `collection` to generate the criterion by which the value
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
* arguments: (value, index, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Math
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => -Infinity
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.max(users, function(chr) {
* return chr.age;
* });
* // => { 'user': 'fred', 'age': 40 }
*
* // using the `_.property` callback shorthand
* _.max(users, 'age');
* // => { 'user': 'fred', 'age': 40 }
*/
var max = createExtremum(arrayMax);
/**
* Gets the minimum value of `collection`. If `collection` is empty or falsey
* `Infinity` is returned. If an iteratee function is provided it is invoked
* for each value in `collection` to generate the criterion by which the value
* is ranked. The `iteratee` is bound to `thisArg` and invoked with three
* arguments: (value, index, collection).
*
* If a property name is provided for `iteratee` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `iteratee` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @category Math
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => Infinity
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* _.min(users, function(chr) {
* return chr.age;
* });
* // => { 'user': 'barney', 'age': 36 }
*
* // using the `_.property` callback shorthand
* _.min(users, 'age');
* // => { 'user': 'barney', 'age': 36 }
*/
var min = createExtremum(arrayMin, true);
/**
* Gets the sum of the values in `collection`.
*
* @static
* @memberOf _
* @category Math
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 6]);
* // => 10
*
* _.sum({ 'a': 4, 'b': 6 });
* // => 10
*
* var objects = [
* { 'n': 4 },
* { 'n': 6 }
* ];
*
* _.sum(objects, function(object) {
* return object.n;
* });
* // => 10
*
* // using the `_.property` callback shorthand
* _.sum(objects, 'n');
* // => 10
*/
function sum(collection, iteratee, thisArg) {
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = null;
}
var func = getCallback(),
noIteratee = iteratee == null;
if (!(func === baseCallback && noIteratee)) {
noIteratee = false;
iteratee = func(iteratee, thisArg, 3);
}
return noIteratee
? arraySum(isArray(collection) ? collection : toIterable(collection))
: baseSum(collection, iteratee);
}
/*------------------------------------------------------------------------*/
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
// Add functions to the `Map` cache.
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
// Add functions to the `Set` cache.
SetCache.prototype.push = cachePush;
// Assign cache to `_.memoize`.
memoize.Cache = MapCache;
// Add functions that return wrapped values when chaining.
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.callback = callback;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.curry = curry;
lodash.curryRight = curryRight;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.fill = fill;
lodash.filter = filter;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
lodash.flow = flow;
lodash.flowRight = flowRight;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.functions = functions;
lodash.groupBy = groupBy;
lodash.indexBy = indexBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.invert = invert;
lodash.invoke = invoke;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.mapValues = mapValues;
lodash.matches = matches;
lodash.matchesProperty = matchesProperty;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.mixin = mixin;
lodash.negate = negate;
lodash.omit = omit;
lodash.once = once;
lodash.pairs = pairs;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
lodash.pluck = pluck;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
lodash.pullAt = pullAt;
lodash.range = range;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.restParam = restParam;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
lodash.sortByAll = sortByAll;
lodash.sortByOrder = sortByOrder;
lodash.spread = spread;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.takeWhile = takeWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
lodash.times = times;
lodash.toArray = toArray;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
lodash.union = union;
lodash.uniq = uniq;
lodash.unzip = unzip;
lodash.values = values;
lodash.valuesIn = valuesIn;
lodash.where = where;
lodash.without = without;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.zip = zip;
lodash.zipObject = zipObject;
// Add aliases.
lodash.backflow = flowRight;
lodash.collect = map;
lodash.compose = flowRight;
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.extend = assign;
lodash.iteratee = callback;
lodash.methods = functions;
lodash.object = zipObject;
lodash.select = filter;
lodash.tail = rest;
lodash.unique = uniq;
// Add functions to `lodash.prototype`.
mixin(lodash, lodash);
/*------------------------------------------------------------------------*/
// Add functions that return unwrapped values when chaining.
lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.deburr = deburr;
lodash.endsWith = endsWith;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.findWhere = findWhere;
lodash.first = first;
lodash.has = has;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.inRange = inRange;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isMatch = isMatch;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isString = isString;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.max = max;
lodash.min = min;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
lodash.padLeft = padLeft;
lodash.padRight = padRight;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
lodash.result = result;
lodash.runInContext = runInContext;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.sortedLastIndex = sortedLastIndex;
lodash.startCase = startCase;
lodash.startsWith = startsWith;
lodash.sum = sum;
lodash.template = template;
lodash.trim = trim;
lodash.trimLeft = trimLeft;
lodash.trimRight = trimRight;
lodash.trunc = trunc;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
lodash.words = words;
// Add aliases.
lodash.all = every;
lodash.any = some;
lodash.contains = includes;
lodash.detect = find;
lodash.foldl = reduce;
lodash.foldr = reduceRight;
lodash.head = first;
lodash.include = includes;
lodash.inject = reduce;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
if (!lodash.prototype[methodName]) {
source[methodName] = func;
}
});
return source;
}()), false);
/*------------------------------------------------------------------------*/
// Add functions capable of returning wrapped and unwrapped values when chaining.
lodash.sample = sample;
lodash.prototype.sample = function(n) {
if (!this.__chain__ && n == null) {
return sample(this.value());
}
return this.thru(function(value) {
return sample(value, n);
});
};
/*------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type string
*/
lodash.VERSION = VERSION;
// Assign default placeholders.
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
lodash[methodName].placeholder = lodash;
});
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['dropWhile', 'filter', 'map', 'takeWhile'], function(methodName, type) {
var isFilter = type != LAZY_MAP_FLAG,
isDropWhile = type == LAZY_DROP_WHILE_FLAG;
LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
var filtered = this.__filtered__,
result = (filtered && isDropWhile) ? new LazyWrapper(this) : this.clone(),
iteratees = result.__iteratees__ || (result.__iteratees__ = []);
iteratees.push({
'done': false,
'count': 0,
'index': 0,
'iteratee': getCallback(iteratee, thisArg, 1),
'limit': -1,
'type': type
});
result.__filtered__ = filtered || isFilter;
return result;
};
});
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop', 'take'], function(methodName, index) {
var whileName = methodName + 'While';
LazyWrapper.prototype[methodName] = function(n) {
var filtered = this.__filtered__,
result = (filtered && !index) ? this.dropWhile() : this.clone();
n = n == null ? 1 : nativeMax(floor(n) || 0, 0);
if (filtered) {
if (index) {
result.__takeCount__ = nativeMin(result.__takeCount__, n);
} else {
last(result.__iteratees__).limit = n;
}
} else {
var views = result.__views__ || (result.__views__ = []);
views.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
}
return result;
};
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
LazyWrapper.prototype[methodName + 'RightWhile'] = function(predicate, thisArg) {
return this.reverse()[whileName](predicate, thisArg).reverse();
};
});
// Add `LazyWrapper` methods for `_.first` and `_.last`.
arrayEach(['first', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
});
// Add `LazyWrapper` methods for `_.initial` and `_.rest`.
arrayEach(['initial', 'rest'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this[dropName](1);
};
});
// Add `LazyWrapper` methods for `_.pluck` and `_.where`.
arrayEach(['pluck', 'where'], function(methodName, index) {
var operationName = index ? 'filter' : 'map',
createCallback = index ? baseMatches : baseProperty;
LazyWrapper.prototype[methodName] = function(value) {
return this[operationName](createCallback(value));
};
});
LazyWrapper.prototype.compact = function() {
return this.filter(identity);
};
LazyWrapper.prototype.reject = function(predicate, thisArg) {
predicate = getCallback(predicate, thisArg, 1);
return this.filter(function(value) {
return !predicate(value);
});
};
LazyWrapper.prototype.slice = function(start, end) {
start = start == null ? 0 : (+start || 0);
var result = start < 0 ? this.takeRight(-start) : this.drop(start);
if (typeof end != 'undefined') {
end = (+end || 0);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
LazyWrapper.prototype.toArray = function() {
return this.drop(0);
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (!lodashFunc) {
return;
}
var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
retUnwrapped = /^(?:first|last)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments,
length = args.length,
chainAll = this.__chain__,
value = this.__wrapped__,
isHybrid = !!this.__actions__.length,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// avoid lazy use if the iteratee has a `length` other than `1`
isLazy = useLazy = false;
}
var onlyLazy = isLazy && !isHybrid;
if (retUnwrapped && !chainAll) {
return onlyLazy
? func.call(value)
: lodashFunc.call(lodash, this.value());
}
var interceptor = function(value) {
var otherArgs = [value];
push.apply(otherArgs, args);
return lodashFunc.apply(lodash, otherArgs);
};
if (useLazy) {
var wrapper = onlyLazy ? value : new LazyWrapper(this),
result = func.apply(wrapper, args);
if (!retUnwrapped && (isHybrid || result.__actions__)) {
var actions = result.__actions__ || (result.__actions__ = []);
actions.push({ 'func': thru, 'args': [interceptor], 'thisArg': lodash });
}
return new LodashWrapper(result, chainAll);
}
return this.thru(interceptor);
};
});
// Add `Array` and `String` methods to `lodash.prototype`.
arrayEach(['concat', 'join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
return func.apply(this.value(), args);
}
return this[chainName](function(value) {
return func.apply(value, args);
});
};
});
// Map minified function names to their real names.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (lodashFunc) {
var key = lodashFunc.name,
names = realNames[key] || (realNames[key] = []);
names.push({ 'name': methodName, 'func': lodashFunc });
}
});
realNames[createHybridWrapper(null, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': null }];
// Add functions to the lazy wrapper.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.reverse = lazyReverse;
LazyWrapper.prototype.value = lazyValue;
// Add chaining functions to the `lodash` wrapper.
lodash.prototype.chain = wrapperChain;
lodash.prototype.commit = wrapperCommit;
lodash.prototype.plant = wrapperPlant;
lodash.prototype.reverse = wrapperReverse;
lodash.prototype.toString = wrapperToString;
lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
// Add function aliases to the `lodash` wrapper.
lodash.prototype.collect = lodash.prototype.map;
lodash.prototype.head = lodash.prototype.first;
lodash.prototype.select = lodash.prototype.filter;
lodash.prototype.tail = lodash.prototype.rest;
return lodash;
}
/*--------------------------------------------------------------------------*/
// Export lodash.
var _ = runInContext();
// Some AMD build optimizers like r.js check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose lodash to the global object when an AMD loader is present to avoid
// errors in cases where lodash is loaded by a script tag and not intended
// as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
// more details.
root._ = _;
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
});
}
// Check for `exports` after `define` in case a build optimizer adds an `exports` object.
else if (freeExports && freeModule) {
// Export for Node.js or RingoJS.
if (moduleExports) {
(freeModule.exports = _)._ = _;
}
// Export for Narwhal or Rhino -require.
else {
freeExports._ = _;
}
}
else {
// Export for a browser or Rhino.
root._ = _;
}
}.call(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],13:[function(require,module,exports){
/*
* Lexical analysis and token construction.
*/
"use strict";
var _ = require("lodash");
var events = require("events");
var reg = require("./reg.js");
var state = require("./state.js").state;
var unicodeData = require("../data/ascii-identifier-data.js");
var asciiIdentifierStartTable = unicodeData.asciiIdentifierStartTable;
var asciiIdentifierPartTable = unicodeData.asciiIdentifierPartTable;
var nonAsciiIdentifierStartTable = require("../data/non-ascii-identifier-start.js");
var nonAsciiIdentifierPartTable = require("../data/non-ascii-identifier-part-only.js");
// Some of these token types are from JavaScript Parser API
// while others are specific to JSHint parser.
// JS Parser API: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
var Token = {
Identifier: 1,
Punctuator: 2,
NumericLiteral: 3,
StringLiteral: 4,
Comment: 5,
Keyword: 6,
NullLiteral: 7,
BooleanLiteral: 8,
RegExp: 9,
TemplateHead: 10,
TemplateMiddle: 11,
TemplateTail: 12,
NoSubstTemplate: 13
};
var Context = {
Block: 1,
Template: 2
};
// Object that handles postponed lexing verifications that checks the parsed
// environment state.
function asyncTrigger() {
var _checks = [];
return {
push: function(fn) {
_checks.push(fn);
},
check: function() {
for (var check = 0; check < _checks.length; ++check) {
_checks[check]();
}
_checks.splice(0, _checks.length);
}
};
}
/*
* Lexer for JSHint.
*
* This object does a char-by-char scan of the provided source code
* and produces a sequence of tokens.
*
* var lex = new Lexer("var i = 0;");
* lex.start();
* lex.token(); // returns the next token
*
* You have to use the token() method to move the lexer forward
* but you don't have to use its return value to get tokens. In addition
* to token() method returning the next token, the Lexer object also
* emits events.
*
* lex.on("Identifier", function(data) {
* if (data.name.indexOf("_") >= 0) {
* // Produce a warning.
* }
* });
*
* Note that the token() method returns tokens in a JSLint-compatible
* format while the event emitter uses a slightly modified version of
* Mozilla's JavaScript Parser API. Eventually, we will move away from
* JSLint format.
*/
function Lexer(source) {
var lines = source;
if (typeof lines === "string") {
lines = lines
.replace(/\r\n/g, "\n")
.replace(/\r/g, "\n")
.split("\n");
}
// If the first line is a shebang (#!), make it a blank and move on.
// Shebangs are used by Node scripts.
if (lines[0] && lines[0].substr(0, 2) === "#!") {
if (lines[0].indexOf("node") !== -1) {
state.option.node = true;
}
lines[0] = "";
}
this.emitter = new events.EventEmitter();
this.source = source;
this.setLines(lines);
this.prereg = true;
this.line = 0;
this.char = 1;
this.from = 1;
this.input = "";
this.inComment = false;
this.context = [];
this.templateStarts = [];
for (var i = 0; i < state.option.indent; i += 1) {
state.tab += " ";
}
}
Lexer.prototype = {
_lines: [],
inContext: function(ctxType) {
return this.context.length > 0 && this.context[this.context.length - 1].type === ctxType;
},
pushContext: function(ctxType) {
this.context.push({ type: ctxType });
},
popContext: function() {
return this.context.pop();
},
isContext: function(context) {
return this.context.length > 0 && this.context[this.context.length - 1] === context;
},
currentContext: function() {
return this.context.length > 0 && this.context[this.context.length - 1];
},
getLines: function() {
this._lines = state.lines;
return this._lines;
},
setLines: function(val) {
this._lines = val;
state.lines = this._lines;
},
/*
* Return the next i character without actually moving the
* char pointer.
*/
peek: function(i) {
return this.input.charAt(i || 0);
},
/*
* Move the char pointer forward i times.
*/
skip: function(i) {
i = i || 1;
this.char += i;
this.input = this.input.slice(i);
},
/*
* Subscribe to a token event. The API for this method is similar
* Underscore.js i.e. you can subscribe to multiple events with
* one call:
*
* lex.on("Identifier Number", function(data) {
* // ...
* });
*/
on: function(names, listener) {
names.split(" ").forEach(function(name) {
this.emitter.on(name, listener);
}.bind(this));
},
/*
* Trigger a token event. All arguments will be passed to each
* listener.
*/
trigger: function() {
this.emitter.emit.apply(this.emitter, Array.prototype.slice.call(arguments));
},
/*
* Postpone a token event. the checking condition is set as
* last parameter, and the trigger function is called in a
* stored callback. To be later called using the check() function
* by the parser. This avoids parser's peek() to give the lexer
* a false context.
*/
triggerAsync: function(type, args, checks, fn) {
checks.push(function() {
if (fn()) {
this.trigger(type, args);
}
}.bind(this));
},
/*
* Extract a punctuator out of the next sequence of characters
* or return 'null' if its not possible.
*
* This method's implementation was heavily influenced by the
* scanPunctuator function in the Esprima parser's source code.
*/
scanPunctuator: function() {
var ch1 = this.peek();
var ch2, ch3, ch4;
switch (ch1) {
// Most common single-character punctuators
case ".":
if ((/^[0-9]$/).test(this.peek(1))) {
return null;
}
if (this.peek(1) === "." && this.peek(2) === ".") {
return {
type: Token.Punctuator,
value: "..."
};
}
/* falls through */
case "(":
case ")":
case ";":
case ",":
case "[":
case "]":
case ":":
case "~":
case "?":
return {
type: Token.Punctuator,
value: ch1
};
// A block/object opener
case "{":
this.pushContext(Context.Block);
return {
type: Token.Punctuator,
value: ch1
};
// A block/object closer
case "}":
if (this.inContext(Context.Block)) {
this.popContext();
}
return {
type: Token.Punctuator,
value: ch1
};
// A pound sign (for Node shebangs)
case "#":
return {
type: Token.Punctuator,
value: ch1
};
// We're at the end of input
case "":
return null;
}
// Peek more characters
ch2 = this.peek(1);
ch3 = this.peek(2);
ch4 = this.peek(3);
// 4-character punctuator: >>>=
if (ch1 === ">" && ch2 === ">" && ch3 === ">" && ch4 === "=") {
return {
type: Token.Punctuator,
value: ">>>="
};
}
// 3-character punctuators: === !== >>> <<= >>=
if (ch1 === "=" && ch2 === "=" && ch3 === "=") {
return {
type: Token.Punctuator,
value: "==="
};
}
if (ch1 === "!" && ch2 === "=" && ch3 === "=") {
return {
type: Token.Punctuator,
value: "!=="
};
}
if (ch1 === ">" && ch2 === ">" && ch3 === ">") {
return {
type: Token.Punctuator,
value: ">>>"
};
}
if (ch1 === "<" && ch2 === "<" && ch3 === "=") {
return {
type: Token.Punctuator,
value: "<<="
};
}
if (ch1 === ">" && ch2 === ">" && ch3 === "=") {
return {
type: Token.Punctuator,
value: ">>="
};
}
// Fat arrow punctuator
if (ch1 === "=" && ch2 === ">") {
return {
type: Token.Punctuator,
value: ch1 + ch2
};
}
// 2-character punctuators: <= >= == != ++ -- << >> && ||
// += -= *= %= &= |= ^= (but not /=, see below)
if (ch1 === ch2 && ("+-<>&|".indexOf(ch1) >= 0)) {
return {
type: Token.Punctuator,
value: ch1 + ch2
};
}
if ("<>=!+-*%&|^".indexOf(ch1) >= 0) {
if (ch2 === "=") {
return {
type: Token.Punctuator,
value: ch1 + ch2
};
}
return {
type: Token.Punctuator,
value: ch1
};
}
// Special case: /=.
if (ch1 === "/") {
if (ch2 === "=") {
return {
type: Token.Punctuator,
value: "/="
};
}
return {
type: Token.Punctuator,
value: "/"
};
}
return null;
},
/*
* Extract a comment out of the next sequence of characters and/or
* lines or return 'null' if its not possible. Since comments can
* span across multiple lines this method has to move the char
* pointer.
*
* In addition to normal JavaScript comments (// and /*) this method
* also recognizes JSHint- and JSLint-specific comments such as
* /*jshint, /*jslint, /*globals and so on.
*/
scanComments: function() {
var ch1 = this.peek();
var ch2 = this.peek(1);
var rest = this.input.substr(2);
var startLine = this.line;
var startChar = this.char;
// Create a comment token object and make sure it
// has all the data JSHint needs to work with special
// comments.
function commentToken(label, body, opt) {
var special = ["jshint", "jslint", "members", "member", "globals", "global", "exported"];
var isSpecial = false;
var value = label + body;
var commentType = "plain";
opt = opt || {};
if (opt.isMultiline) {
value += "*/";
}
body = body.replace(/\n/g, " ");
special.forEach(function(str) {
if (isSpecial) {
return;
}
// Don't recognize any special comments other than jshint for single-line
// comments. This introduced many problems with legit comments.
if (label === "//" && str !== "jshint") {
return;
}
if (body.charAt(str.length) === " " && body.substr(0, str.length) === str) {
isSpecial = true;
label = label + str;
body = body.substr(str.length);
}
if (!isSpecial && body.charAt(0) === " " && body.charAt(str.length + 1) === " " &&
body.substr(1, str.length) === str) {
isSpecial = true;
label = label + " " + str;
body = body.substr(str.length + 1);
}
if (!isSpecial) {
return;
}
switch (str) {
case "member":
commentType = "members";
break;
case "global":
commentType = "globals";
break;
default:
commentType = str;
}
});
return {
type: Token.Comment,
commentType: commentType,
value: value,
body: body,
isSpecial: isSpecial,
isMultiline: opt.isMultiline || false,
isMalformed: opt.isMalformed || false
};
}
// End of unbegun comment. Raise an error and skip that input.
if (ch1 === "*" && ch2 === "/") {
this.trigger("error", {
code: "E018",
line: startLine,
character: startChar
});
this.skip(2);
return null;
}
// Comments must start either with // or /*
if (ch1 !== "/" || (ch2 !== "*" && ch2 !== "/")) {
return null;
}
// One-line comment
if (ch2 === "/") {
this.skip(this.input.length); // Skip to the EOL.
return commentToken("//", rest);
}
var body = "";
/* Multi-line comment */
if (ch2 === "*") {
this.inComment = true;
this.skip(2);
while (this.peek() !== "*" || this.peek(1) !== "/") {
if (this.peek() === "") { // End of Line
body += "\n";
// If we hit EOF and our comment is still unclosed,
// trigger an error and end the comment implicitly.
if (!this.nextLine()) {
this.trigger("error", {
code: "E017",
line: startLine,
character: startChar
});
this.inComment = false;
return commentToken("/*", body, {
isMultiline: true,
isMalformed: true
});
}
} else {
body += this.peek();
this.skip();
}
}
this.skip(2);
this.inComment = false;
return commentToken("/*", body, { isMultiline: true });
}
},
/*
* Extract a keyword out of the next sequence of characters or
* return 'null' if its not possible.
*/
scanKeyword: function() {
var result = /^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input);
var keywords = [
"if", "in", "do", "var", "for", "new",
"try", "let", "this", "else", "case",
"void", "with", "enum", "while", "break",
"catch", "throw", "const", "yield", "class",
"super", "return", "typeof", "delete",
"switch", "export", "import", "default",
"finally", "extends", "function", "continue",
"debugger", "instanceof"
];
if (result && keywords.indexOf(result[0]) >= 0) {
return {
type: Token.Keyword,
value: result[0]
};
}
return null;
},
/*
* Extract a JavaScript identifier out of the next sequence of
* characters or return 'null' if its not possible. In addition,
* to Identifier this method can also produce BooleanLiteral
* (true/false) and NullLiteral (null).
*/
scanIdentifier: function() {
var id = "";
var index = 0;
var type, char;
function isNonAsciiIdentifierStart(code) {
return nonAsciiIdentifierStartTable.indexOf(code) > -1;
}
function isNonAsciiIdentifierPart(code) {
return isNonAsciiIdentifierStart(code) || nonAsciiIdentifierPartTable.indexOf(code) > -1;
}
function isHexDigit(str) {
return (/^[0-9a-fA-F]$/).test(str);
}
var readUnicodeEscapeSequence = function() {
/*jshint validthis:true */
index += 1;
if (this.peek(index) !== "u") {
return null;
}
var ch1 = this.peek(index + 1);
var ch2 = this.peek(index + 2);
var ch3 = this.peek(index + 3);
var ch4 = this.peek(index + 4);
var code;
if (isHexDigit(ch1) && isHexDigit(ch2) && isHexDigit(ch3) && isHexDigit(ch4)) {
code = parseInt(ch1 + ch2 + ch3 + ch4, 16);
if (asciiIdentifierPartTable[code] || isNonAsciiIdentifierPart(code)) {
index += 5;
return "\\u" + ch1 + ch2 + ch3 + ch4;
}
return null;
}
return null;
}.bind(this);
var getIdentifierStart = function() {
/*jshint validthis:true */
var chr = this.peek(index);
var code = chr.charCodeAt(0);
if (code === 92) {
return readUnicodeEscapeSequence();
}
if (code < 128) {
if (asciiIdentifierStartTable[code]) {
index += 1;
return chr;
}
return null;
}
if (isNonAsciiIdentifierStart(code)) {
index += 1;
return chr;
}
return null;
}.bind(this);
var getIdentifierPart = function() {
/*jshint validthis:true */
var chr = this.peek(index);
var code = chr.charCodeAt(0);
if (code === 92) {
return readUnicodeEscapeSequence();
}
if (code < 128) {
if (asciiIdentifierPartTable[code]) {
index += 1;
return chr;
}
return null;
}
if (isNonAsciiIdentifierPart(code)) {
index += 1;
return chr;
}
return null;
}.bind(this);
function removeEscapeSequences(id) {
return id.replace(/\\u([0-9a-fA-F]{4})/g, function(m0, codepoint) {
return String.fromCharCode(parseInt(codepoint, 16));
});
}
char = getIdentifierStart();
if (char === null) {
return null;
}
id = char;
for (;;) {
char = getIdentifierPart();
if (char === null) {
break;
}
id += char;
}
switch (id) {
case "true":
case "false":
type = Token.BooleanLiteral;
break;
case "null":
type = Token.NullLiteral;
break;
default:
type = Token.Identifier;
}
return {
type: type,
value: removeEscapeSequences(id),
text: id,
tokenLength: id.length
};
},
/*
* Extract a numeric literal out of the next sequence of
* characters or return 'null' if its not possible. This method
* supports all numeric literals described in section 7.8.3
* of the EcmaScript 5 specification.
*
* This method's implementation was heavily influenced by the
* scanNumericLiteral function in the Esprima parser's source code.
*/
scanNumericLiteral: function() {
var index = 0;
var value = "";
var length = this.input.length;
var char = this.peek(index);
var bad;
var isAllowedDigit = isDecimalDigit;
var base = 10;
var isLegacy = false;
function isDecimalDigit(str) {
return (/^[0-9]$/).test(str);
}
function isOctalDigit(str) {
return (/^[0-7]$/).test(str);
}
function isBinaryDigit(str) {
return (/^[01]$/).test(str);
}
function isHexDigit(str) {
return (/^[0-9a-fA-F]$/).test(str);
}
function isIdentifierStart(ch) {
return (ch === "$") || (ch === "_") || (ch === "\\") ||
(ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z");
}
// Numbers must start either with a decimal digit or a point.
if (char !== "." && !isDecimalDigit(char)) {
return null;
}
if (char !== ".") {
value = this.peek(index);
index += 1;
char = this.peek(index);
if (value === "0") {
// Base-16 numbers.
if (char === "x" || char === "X") {
isAllowedDigit = isHexDigit;
base = 16;
index += 1;
value += char;
}
// Base-8 numbers.
if (char === "o" || char === "O") {
isAllowedDigit = isOctalDigit;
base = 8;
if (!state.option.esnext) {
this.trigger("warning", {
code: "W119",
line: this.line,
character: this.char,
data: [ "Octal integer literal" ]
});
}
index += 1;
value += char;
}
// Base-2 numbers.
if (char === "b" || char === "B") {
isAllowedDigit = isBinaryDigit;
base = 2;
if (!state.option.esnext) {
this.trigger("warning", {
code: "W119",
line: this.line,
character: this.char,
data: [ "Binary integer literal" ]
});
}
index += 1;
value += char;
}
// Legacy base-8 numbers.
if (isOctalDigit(char)) {
isAllowedDigit = isOctalDigit;
base = 8;
isLegacy = true;
bad = false;
index += 1;
value += char;
}
// Decimal numbers that start with '0' such as '09' are illegal
// but we still parse them and return as malformed.
if (!isOctalDigit(char) && isDecimalDigit(char)) {
index += 1;
value += char;
}
}
while (index < length) {
char = this.peek(index);
if (isLegacy && isDecimalDigit(char)) {
// Numbers like '019' (note the 9) are not valid octals
// but we still parse them and mark as malformed.
bad = true;
} else if (!isAllowedDigit(char)) {
break;
}
value += char;
index += 1;
}
if (isAllowedDigit !== isDecimalDigit) {
if (!isLegacy && value.length <= 2) { // 0x
return {
type: Token.NumericLiteral,
value: value,
isMalformed: true
};
}
if (index < length) {
char = this.peek(index);
if (isIdentifierStart(char)) {
return null;
}
}
return {
type: Token.NumericLiteral,
value: value,
base: base,
isLegacy: isLegacy,
isMalformed: false
};
}
}
// Decimal digits.
if (char === ".") {
value += char;
index += 1;
while (index < length) {
char = this.peek(index);
if (!isDecimalDigit(char)) {
break;
}
value += char;
index += 1;
}
}
// Exponent part.
if (char === "e" || char === "E") {
value += char;
index += 1;
char = this.peek(index);
if (char === "+" || char === "-") {
value += this.peek(index);
index += 1;
}
char = this.peek(index);
if (isDecimalDigit(char)) {
value += char;
index += 1;
while (index < length) {
char = this.peek(index);
if (!isDecimalDigit(char)) {
break;
}
value += char;
index += 1;
}
} else {
return null;
}
}
if (index < length) {
char = this.peek(index);
if (isIdentifierStart(char)) {
return null;
}
}
return {
type: Token.NumericLiteral,
value: value,
base: base,
isMalformed: !isFinite(value)
};
},
// Assumes previously parsed character was \ (=== '\\') and was not skipped.
scanEscapeSequence: function(checks) {
var allowNewLine = false;
var jump = 1;
this.skip();
var char = this.peek();
switch (char) {
case "'":
this.triggerAsync("warning", {
code: "W114",
line: this.line,
character: this.char,
data: [ "\\'" ]
}, checks, function() {return state.jsonMode; });
break;
case "b":
char = "\\b";
break;
case "f":
char = "\\f";
break;
case "n":
char = "\\n";
break;
case "r":
char = "\\r";
break;
case "t":
char = "\\t";
break;
case "0":
char = "\\0";
// Octal literals fail in strict mode.
// Check if the number is between 00 and 07.
var n = parseInt(this.peek(1), 10);
this.triggerAsync("warning", {
code: "W115",
line: this.line,
character: this.char
}, checks,
function() { return n >= 0 && n <= 7 && state.isStrict(); });
break;
case "u":
var hexCode = this.input.substr(1, 4);
var code = parseInt(hexCode, 16);
if (isNaN(code)) {
this.trigger("warning", {
code: "W052",
line: this.line,
character: this.char,
data: [ "u" + hexCode ]
});
}
char = String.fromCharCode(code);
jump = 5;
break;
case "v":
this.triggerAsync("warning", {
code: "W114",
line: this.line,
character: this.char,
data: [ "\\v" ]
}, checks, function() { return state.jsonMode; });
char = "\v";
break;
case "x":
var x = parseInt(this.input.substr(1, 2), 16);
this.triggerAsync("warning", {
code: "W114",
line: this.line,
character: this.char,
data: [ "\\x-" ]
}, checks, function() { return state.jsonMode; });
char = String.fromCharCode(x);
jump = 3;
break;
case "\\":
char = "\\\\";
break;
case "\"":
char = "\\\"";
break;
case "/":
break;
case "":
allowNewLine = true;
char = "";
break;
}
return { char: char, jump: jump, allowNewLine: allowNewLine };
},
/*
* Extract a template literal out of the next sequence of characters
* and/or lines or return 'null' if its not possible. Since template
* literals can span across multiple lines, this method has to move
* the char pointer.
*/
scanTemplateLiteral: function(checks) {
var tokenType;
var value = "";
var ch;
var startLine = this.line;
var startChar = this.char;
var depth = this.templateStarts.length;
if (!state.option.esnext) {
// Only lex template strings in ESNext mode.
return null;
} else if (this.peek() === "`") {
// Template must start with a backtick.
tokenType = Token.TemplateHead;
this.templateStarts.push({ line: this.line, char: this.char });
depth = this.templateStarts.length;
this.skip(1);
this.pushContext(Context.Template);
} else if (this.inContext(Context.Template) && this.peek() === "}") {
// If we're in a template context, and we have a '}', lex a TemplateMiddle.
tokenType = Token.TemplateMiddle;
} else {
// Go lex something else.
return null;
}
while (this.peek() !== "`") {
while ((ch = this.peek()) === "") {
value += "\n";
if (!this.nextLine()) {
// Unclosed template literal --- point to the starting "`"
var startPos = this.templateStarts.pop();
this.trigger("error", {
code: "E052",
line: startPos.line,
character: startPos.char
});
return {
type: tokenType,
value: value,
startLine: startLine,
startChar: startChar,
isUnclosed: true,
depth: depth,
context: this.popContext()
};
}
}
if (ch === '$' && this.peek(1) === '{') {
value += '${';
this.skip(2);
return {
type: tokenType,
value: value,
startLine: startLine,
startChar: startChar,
isUnclosed: false,
depth: depth,
context: this.currentContext()
};
} else if (ch === '\\') {
var escape = this.scanEscapeSequence(checks);
value += escape.char;
this.skip(escape.jump);
} else if (ch !== '`') {
// Otherwise, append the value and continue.
value += ch;
this.skip(1);
}
}
// Final value is either NoSubstTemplate or TemplateTail
tokenType = tokenType === Token.TemplateHead ? Token.NoSubstTemplate : Token.TemplateTail;
this.skip(1);
this.templateStarts.pop();
return {
type: tokenType,
value: value,
startLine: startLine,
startChar: startChar,
isUnclosed: false,
depth: depth,
context: this.popContext()
};
},
/*
* Extract a string out of the next sequence of characters and/or
* lines or return 'null' if its not possible. Since strings can
* span across multiple lines this method has to move the char
* pointer.
*
* This method recognizes pseudo-multiline JavaScript strings:
*
* var str = "hello\
* world";
*/
scanStringLiteral: function(checks) {
/*jshint loopfunc:true */
var quote = this.peek();
// String must start with a quote.
if (quote !== "\"" && quote !== "'") {
return null;
}
// In JSON strings must always use double quotes.
this.triggerAsync("warning", {
code: "W108",
line: this.line,
character: this.char // +1?
}, checks, function() { return state.jsonMode && quote !== "\""; });
var value = "";
var startLine = this.line;
var startChar = this.char;
var allowNewLine = false;
this.skip();
while (this.peek() !== quote) {
if (this.peek() === "") { // End Of Line
// If an EOL is not preceded by a backslash, show a warning
// and proceed like it was a legit multi-line string where
// author simply forgot to escape the newline symbol.
//
// Another approach is to implicitly close a string on EOL
// but it generates too many false positives.
if (!allowNewLine) {
this.trigger("warning", {
code: "W112",
line: this.line,
character: this.char
});
} else {
allowNewLine = false;
// Otherwise show a warning if multistr option was not set.
// For JSON, show warning no matter what.
this.triggerAsync("warning", {
code: "W043",
line: this.line,
character: this.char
}, checks, function() { return !state.option.multistr; });
this.triggerAsync("warning", {
code: "W042",
line: this.line,
character: this.char
}, checks, function() { return state.jsonMode && state.option.multistr; });
}
// If we get an EOF inside of an unclosed string, show an
// error and implicitly close it at the EOF point.
if (!this.nextLine()) {
this.trigger("error", {
code: "E029",
line: startLine,
character: startChar
});
return {
type: Token.StringLiteral,
value: value,
startLine: startLine,
startChar: startChar,
isUnclosed: true,
quote: quote
};
}
} else { // Any character other than End Of Line
allowNewLine = false;
var char = this.peek();
var jump = 1; // A length of a jump, after we're done
// parsing this character.
if (char < " ") {
// Warn about a control character in a string.
this.trigger("warning", {
code: "W113",
line: this.line,
character: this.char,
data: [ "<non-printable>" ]
});
}
// Special treatment for some escaped characters.
if (char === "\\") {
var parsed = this.scanEscapeSequence(checks);
char = parsed.char;
jump = parsed.jump;
allowNewLine = parsed.allowNewLine;
}
value += char;
this.skip(jump);
}
}
this.skip();
return {
type: Token.StringLiteral,
value: value,
startLine: startLine,
startChar: startChar,
isUnclosed: false,
quote: quote
};
},
/*
* Extract a regular expression out of the next sequence of
* characters and/or lines or return 'null' if its not possible.
*
* This method is platform dependent: it accepts almost any
* regular expression values but then tries to compile and run
* them using system's RegExp object. This means that there are
* rare edge cases where one JavaScript engine complains about
* your regular expression while others don't.
*/
scanRegExp: function() {
var index = 0;
var length = this.input.length;
var char = this.peek();
var value = char;
var body = "";
var flags = [];
var malformed = false;
var isCharSet = false;
var terminated;
var scanUnexpectedChars = function() {
// Unexpected control character
if (char < " ") {
malformed = true;
this.trigger("warning", {
code: "W048",
line: this.line,
character: this.char
});
}
// Unexpected escaped character
if (char === "<") {
malformed = true;
this.trigger("warning", {
code: "W049",
line: this.line,
character: this.char,
data: [ char ]
});
}
}.bind(this);
// Regular expressions must start with '/'
if (!this.prereg || char !== "/") {
return null;
}
index += 1;
terminated = false;
// Try to get everything in between slashes. A couple of
// cases aside (see scanUnexpectedChars) we don't really
// care whether the resulting expression is valid or not.
// We will check that later using the RegExp object.
while (index < length) {
char = this.peek(index);
value += char;
body += char;
if (isCharSet) {
if (char === "]") {
if (this.peek(index - 1) !== "\\" || this.peek(index - 2) === "\\") {
isCharSet = false;
}
}
if (char === "\\") {
index += 1;
char = this.peek(index);
body += char;
value += char;
scanUnexpectedChars();
}
index += 1;
continue;
}
if (char === "\\") {
index += 1;
char = this.peek(index);
body += char;
value += char;
scanUnexpectedChars();
if (char === "/") {
index += 1;
continue;
}
if (char === "[") {
index += 1;
continue;
}
}
if (char === "[") {
isCharSet = true;
index += 1;
continue;
}
if (char === "/") {
body = body.substr(0, body.length - 1);
terminated = true;
index += 1;
break;
}
index += 1;
}
// A regular expression that was never closed is an
// error from which we cannot recover.
if (!terminated) {
this.trigger("error", {
code: "E015",
line: this.line,
character: this.from
});
return void this.trigger("fatal", {
line: this.line,
from: this.from
});
}
// Parse flags (if any).
while (index < length) {
char = this.peek(index);
if (!/[gim]/.test(char)) {
break;
}
flags.push(char);
value += char;
index += 1;
}
// Check regular expression for correctness.
try {
new RegExp(body, flags.join(""));
} catch (err) {
malformed = true;
this.trigger("error", {
code: "E016",
line: this.line,
character: this.char,
data: [ err.message ] // Platform dependent!
});
}
return {
type: Token.RegExp,
value: value,
flags: flags,
isMalformed: malformed
};
},
/*
* Scan for any occurrence of non-breaking spaces. Non-breaking spaces
* can be mistakenly typed on OS X with option-space. Non UTF-8 web
* pages with non-breaking pages produce syntax errors.
*/
scanNonBreakingSpaces: function() {
return state.option.nonbsp ?
this.input.search(/(\u00A0)/) : -1;
},
/*
* Scan for characters that get silently deleted by one or more browsers.
*/
scanUnsafeChars: function() {
return this.input.search(reg.unsafeChars);
},
/*
* Produce the next raw token or return 'null' if no tokens can be matched.
* This method skips over all space characters.
*/
next: function(checks) {
this.from = this.char;
// Move to the next non-space character.
var start;
if (/\s/.test(this.peek())) {
start = this.char;
while (/\s/.test(this.peek())) {
this.from += 1;
this.skip();
}
}
// Methods that work with multi-line structures and move the
// character pointer.
var match = this.scanComments() ||
this.scanStringLiteral(checks) ||
this.scanTemplateLiteral(checks);
if (match) {
return match;
}
// Methods that don't move the character pointer.
match =
this.scanRegExp() ||
this.scanPunctuator() ||
this.scanKeyword() ||
this.scanIdentifier() ||
this.scanNumericLiteral();
if (match) {
this.skip(match.tokenLength || match.value.length);
return match;
}
// No token could be matched, give up.
return null;
},
/*
* Switch to the next line and reset all char pointers. Once
* switched, this method also checks for other minor warnings.
*/
nextLine: function() {
var char;
if (this.line >= this.getLines().length) {
return false;
}
this.input = this.getLines()[this.line];
this.line += 1;
this.char = 1;
this.from = 1;
var inputTrimmed = this.input.trim();
var startsWith = function() {
return _.some(arguments, function(prefix) {
return inputTrimmed.indexOf(prefix) === 0;
});
};
var endsWith = function() {
return _.some(arguments, function(suffix) {
return inputTrimmed.indexOf(suffix, inputTrimmed.length - suffix.length) !== -1;
});
};
// If we are ignoring linter errors, replace the input with empty string
// if it doesn't already at least start or end a multi-line comment
if (state.ignoreLinterErrors === true) {
if (!startsWith("/*", "//") && !(this.inComment && endsWith("*/"))) {
this.input = "";
}
}
char = this.scanNonBreakingSpaces();
if (char >= 0) {
this.trigger("warning", { code: "W125", line: this.line, character: char + 1 });
}
this.input = this.input.replace(/\t/g, state.tab);
char = this.scanUnsafeChars();
if (char >= 0) {
this.trigger("warning", { code: "W100", line: this.line, character: char });
}
// If there is a limit on line length, warn when lines get too
// long.
if (state.option.maxlen && state.option.maxlen < this.input.length) {
var inComment = this.inComment ||
startsWith.call(inputTrimmed, "//") ||
startsWith.call(inputTrimmed, "/*");
var shouldTriggerError = !inComment || !reg.maxlenException.test(inputTrimmed);
if (shouldTriggerError) {
this.trigger("warning", { code: "W101", line: this.line, character: this.input.length });
}
}
return true;
},
/*
* This is simply a synonym for nextLine() method with a friendlier
* public name.
*/
start: function() {
this.nextLine();
},
/*
* Produce the next token. This function is called by advance() to get
* the next token. It returns a token in a JSLint-compatible format.
*/
token: function() {
/*jshint loopfunc:true */
var checks = asyncTrigger();
var token;
function isReserved(token, isProperty) {
if (!token.reserved) {
return false;
}
var meta = token.meta;
if (meta && meta.isFutureReservedWord && state.inES5()) {
// ES3 FutureReservedWord in an ES5 environment.
if (!meta.es5) {
return false;
}
// Some ES5 FutureReservedWord identifiers are active only
// within a strict mode environment.
if (meta.strictOnly) {
if (!state.option.strict && !state.isStrict()) {
return false;
}
}
if (isProperty) {
return false;
}
}
return true;
}
// Produce a token object.
var create = function(type, value, isProperty, token) {
/*jshint validthis:true */
var obj;
if (type !== "(endline)" && type !== "(end)") {
this.prereg = false;
}
if (type === "(punctuator)") {
switch (value) {
case ".":
case ")":
case "~":
case "#":
case "]":
case "++":
case "--":
this.prereg = false;
break;
default:
this.prereg = true;
}
obj = Object.create(state.syntax[value] || state.syntax["(error)"]);
}
if (type === "(identifier)") {
if (value === "return" || value === "case" || value === "typeof") {
this.prereg = true;
}
if (_.has(state.syntax, value)) {
obj = Object.create(state.syntax[value] || state.syntax["(error)"]);
// If this can't be a reserved keyword, reset the object.
if (!isReserved(obj, isProperty && type === "(identifier)")) {
obj = null;
}
}
}
if (!obj) {
obj = Object.create(state.syntax[type]);
}
obj.identifier = (type === "(identifier)");
obj.type = obj.type || type;
obj.value = value;
obj.line = this.line;
obj.character = this.char;
obj.from = this.from;
if (obj.identifier && token) obj.raw_text = token.text || token.value;
if (token && token.startLine && token.startLine !== this.line) {
obj.startLine = token.startLine;
}
if (token && token.context) {
// Context of current token
obj.context = token.context;
}
if (token && token.depth) {
// Nested template depth
obj.depth = token.depth;
}
if (token && token.isUnclosed) {
// Mark token as unclosed string / template literal
obj.isUnclosed = token.isUnclosed;
}
if (isProperty && obj.identifier) {
obj.isProperty = isProperty;
}
obj.check = checks.check;
return obj;
}.bind(this);
for (;;) {
if (!this.input.length) {
if (this.nextLine()) {
return create("(endline)", "");
}
if (this.exhausted) {
return null;
}
this.exhausted = true;
return create("(end)", "");
}
token = this.next(checks);
if (!token) {
if (this.input.length) {
// Unexpected character.
this.trigger("error", {
code: "E024",
line: this.line,
character: this.char,
data: [ this.peek() ]
});
this.input = "";
}
continue;
}
switch (token.type) {
case Token.StringLiteral:
this.triggerAsync("String", {
line: this.line,
char: this.char,
from: this.from,
startLine: token.startLine,
startChar: token.startChar,
value: token.value,
quote: token.quote
}, checks, function() { return true; });
return create("(string)", token.value, null, token);
case Token.TemplateHead:
this.trigger("TemplateHead", {
line: this.line,
char: this.char,
from: this.from,
startLine: token.startLine,
startChar: token.startChar,
value: token.value
});
return create("(template)", token.value, null, token);
case Token.TemplateMiddle:
this.trigger("TemplateMiddle", {
line: this.line,
char: this.char,
from: this.from,
startLine: token.startLine,
startChar: token.startChar,
value: token.value
});
return create("(template middle)", token.value, null, token);
case Token.TemplateTail:
this.trigger("TemplateTail", {
line: this.line,
char: this.char,
from: this.from,
startLine: token.startLine,
startChar: token.startChar,
value: token.value
});
return create("(template tail)", token.value, null, token);
case Token.NoSubstTemplate:
this.trigger("NoSubstTemplate", {
line: this.line,
char: this.char,
from: this.from,
startLine: token.startLine,
startChar: token.startChar,
value: token.value
});
return create("(no subst template)", token.value, null, token);
case Token.Identifier:
this.trigger("Identifier", {
line: this.line,
char: this.char,
from: this.form,
name: token.value,
raw_name: token.text,
isProperty: state.tokens.curr.id === "."
});
/* falls through */
case Token.Keyword:
case Token.NullLiteral:
case Token.BooleanLiteral:
return create("(identifier)", token.value, state.tokens.curr.id === ".", token);
case Token.NumericLiteral:
if (token.isMalformed) {
this.trigger("warning", {
code: "W045",
line: this.line,
character: this.char,
data: [ token.value ]
});
}
this.triggerAsync("warning", {
code: "W114",
line: this.line,
character: this.char,
data: [ "0x-" ]
}, checks, function() { return token.base === 16 && state.jsonMode; });
this.triggerAsync("warning", {
code: "W115",
line: this.line,
character: this.char
}, checks, function() {
return state.isStrict() && token.base === 8 && token.isLegacy;
});
this.trigger("Number", {
line: this.line,
char: this.char,
from: this.from,
value: token.value,
base: token.base,
isMalformed: token.malformed
});
return create("(number)", token.value);
case Token.RegExp:
return create("(regexp)", token.value);
case Token.Comment:
state.tokens.curr.comment = true;
if (token.isSpecial) {
return {
id: '(comment)',
value: token.value,
body: token.body,
type: token.commentType,
isSpecial: token.isSpecial,
line: this.line,
character: this.char,
from: this.from
};
}
break;
case "":
break;
default:
return create("(punctuator)", token.value);
}
}
}
};
exports.Lexer = Lexer;
exports.Context = Context;
},{"../data/ascii-identifier-data.js":1,"../data/non-ascii-identifier-part-only.js":2,"../data/non-ascii-identifier-start.js":3,"./reg.js":17,"./state.js":18,"events":5,"lodash":12}],14:[function(require,module,exports){
"use strict";
var _ = require("lodash");
var errors = {
// JSHint options
E001: "Bad option: '{a}'.",
E002: "Bad option value.",
// JSHint input
E003: "Expected a JSON value.",
E004: "Input is neither a string nor an array of strings.",
E005: "Input is empty.",
E006: "Unexpected early end of program.",
// Strict mode
E007: "Missing \"use strict\" statement.",
E008: "Strict violation.",
E009: "Option 'validthis' can't be used in a global scope.",
E010: "'with' is not allowed in strict mode.",
// Constants
E011: "const '{a}' has already been declared.",
E012: "const '{a}' is initialized to 'undefined'.",
E013: "Attempting to override '{a}' which is a constant.",
// Regular expressions
E014: "A regular expression literal can be confused with '/='.",
E015: "Unclosed regular expression.",
E016: "Invalid regular expression.",
// Tokens
E017: "Unclosed comment.",
E018: "Unbegun comment.",
E019: "Unmatched '{a}'.",
E020: "Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.",
E021: "Expected '{a}' and instead saw '{b}'.",
E022: "Line breaking error '{a}'.",
E023: "Missing '{a}'.",
E024: "Unexpected '{a}'.",
E025: "Missing ':' on a case clause.",
E026: "Missing '}' to match '{' from line {a}.",
E027: "Missing ']' to match '[' from line {a}.",
E028: "Illegal comma.",
E029: "Unclosed string.",
// Everything else
E030: "Expected an identifier and instead saw '{a}'.",
E031: "Bad assignment.", // FIXME: Rephrase
E032: "Expected a small integer or 'false' and instead saw '{a}'.",
E033: "Expected an operator and instead saw '{a}'.",
E034: "get/set are ES5 features.",
E035: "Missing property name.",
E036: "Expected to see a statement and instead saw a block.",
E037: null,
E038: null,
E039: "Function declarations are not invocable. Wrap the whole function invocation in parens.",
E040: "Each value should have its own case label.",
E041: "Unrecoverable syntax error.",
E042: "Stopping.",
E043: "Too many errors.",
E044: null,
E045: "Invalid for each loop.",
E046: "A yield statement shall be within a generator function (with syntax: `function*`)",
E047: null, // Vacant
E048: "{a} declaration not directly within block.",
E049: "A {a} cannot be named '{b}'.",
E050: "Mozilla requires the yield expression to be parenthesized here.",
E051: "Regular parameters cannot come after default parameters.",
E052: "Unclosed template literal.",
E053: "Export declaration must be in global scope.",
E054: "Class properties must be methods. Expected '(' but instead saw '{a}'.",
E055: "The '{a}' option cannot be set after any executable code."
};
var warnings = {
W001: "'hasOwnProperty' is a really bad name.",
W002: "Value of '{a}' may be overwritten in IE 8 and earlier.",
W003: "'{a}' was used before it was defined.",
W004: "'{a}' is already defined.",
W005: "A dot following a number can be confused with a decimal point.",
W006: "Confusing minuses.",
W007: "Confusing plusses.",
W008: "A leading decimal point can be confused with a dot: '{a}'.",
W009: "The array literal notation [] is preferable.",
W010: "The object literal notation {} is preferable.",
W011: null,
W012: null,
W013: null,
W014: "Bad line breaking before '{a}'.",
W015: null,
W016: "Unexpected use of '{a}'.",
W017: "Bad operand.",
W018: "Confusing use of '{a}'.",
W019: "Use the isNaN function to compare with NaN.",
W020: "Read only.",
W021: "'{a}' is a function.",
W022: "Do not assign to the exception parameter.",
W023: "Expected an identifier in an assignment and instead saw a function invocation.",
W024: "Expected an identifier and instead saw '{a}' (a reserved word).",
W025: "Missing name in function declaration.",
W026: "Inner functions should be listed at the top of the outer function.",
W027: "Unreachable '{a}' after '{b}'.",
W028: "Label '{a}' on {b} statement.",
W030: "Expected an assignment or function call and instead saw an expression.",
W031: "Do not use 'new' for side effects.",
W032: "Unnecessary semicolon.",
W033: "Missing semicolon.",
W034: "Unnecessary directive \"{a}\".",
W035: "Empty block.",
W036: "Unexpected /*member '{a}'.",
W037: "'{a}' is a statement label.",
W038: "'{a}' used out of scope.",
W039: "'{a}' is not allowed.",
W040: "Possible strict violation.",
W041: "Use '{a}' to compare with '{b}'.",
W042: "Avoid EOL escaping.",
W043: "Bad escaping of EOL. Use option multistr if needed.",
W044: "Bad or unnecessary escaping.", /* TODO(caitp): remove W044 */
W045: "Bad number '{a}'.",
W046: "Don't use extra leading zeros '{a}'.",
W047: "A trailing decimal point can be confused with a dot: '{a}'.",
W048: "Unexpected control character in regular expression.",
W049: "Unexpected escaped character '{a}' in regular expression.",
W050: "JavaScript URL.",
W051: "Variables should not be deleted.",
W052: "Unexpected '{a}'.",
W053: "Do not use {a} as a constructor.",
W054: "The Function constructor is a form of eval.",
W055: "A constructor name should start with an uppercase letter.",
W056: "Bad constructor.",
W057: "Weird construction. Is 'new' necessary?",
W058: "Missing '()' invoking a constructor.",
W059: "Avoid arguments.{a}.",
W060: "document.write can be a form of eval.",
W061: "eval can be harmful.",
W062: "Wrap an immediate function invocation in parens " +
"to assist the reader in understanding that the expression " +
"is the result of a function, and not the function itself.",
W063: "Math is not a function.",
W064: "Missing 'new' prefix when invoking a constructor.",
W065: "Missing radix parameter.",
W066: "Implied eval. Consider passing a function instead of a string.",
W067: "Bad invocation.",
W068: "Wrapping non-IIFE function literals in parens is unnecessary.",
W069: "['{a}'] is better written in dot notation.",
W070: "Extra comma. (it breaks older versions of IE)",
W071: "This function has too many statements. ({a})",
W072: "This function has too many parameters. ({a})",
W073: "Blocks are nested too deeply. ({a})",
W074: "This function's cyclomatic complexity is too high. ({a})",
W075: "Duplicate {a} '{b}'.",
W076: "Unexpected parameter '{a}' in get {b} function.",
W077: "Expected a single parameter in set {a} function.",
W078: "Setter is defined without getter.",
W079: "Redefinition of '{a}'.",
W080: "It's not necessary to initialize '{a}' to 'undefined'.",
W081: null,
W082: "Function declarations should not be placed in blocks. " +
"Use a function expression or move the statement to the top of " +
"the outer function.",
W083: "Don't make functions within a loop.",
W084: "Expected a conditional expression and instead saw an assignment.",
W085: "Don't use 'with'.",
W086: "Expected a 'break' statement before '{a}'.",
W087: "Forgotten 'debugger' statement?",
W088: "Creating global 'for' variable. Should be 'for (var {a} ...'.",
W089: "The body of a for in should be wrapped in an if statement to filter " +
"unwanted properties from the prototype.",
W090: "'{a}' is not a statement label.",
W091: "'{a}' is out of scope.",
W093: "Did you mean to return a conditional instead of an assignment?",
W094: "Unexpected comma.",
W095: "Expected a string and instead saw {a}.",
W096: "The '{a}' key may produce unexpected results.",
W097: "Use the function form of \"use strict\".",
W098: "'{a}' is defined but never used.",
W099: null,
W100: "This character may get silently deleted by one or more browsers.",
W101: "Line is too long.",
W102: null,
W103: "The '{a}' property is deprecated.",
W104: "'{a}' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).",
W105: "Unexpected {a} in '{b}'.",
W106: "Identifier '{a}' is not in camel case.",
W107: "Script URL.",
W108: "Strings must use doublequote.",
W109: "Strings must use singlequote.",
W110: "Mixed double and single quotes.",
W112: "Unclosed string.",
W113: "Control character in string: {a}.",
W114: "Avoid {a}.",
W115: "Octal literals are not allowed in strict mode.",
W116: "Expected '{a}' and instead saw '{b}'.",
W117: "'{a}' is not defined.",
W118: "'{a}' is only available in Mozilla JavaScript extensions (use moz option).",
W119: "'{a}' is only available in ES6 (use esnext option).",
W120: "You might be leaking a variable ({a}) here.",
W121: "Extending prototype of native object: '{a}'.",
W122: "Invalid typeof value '{a}'",
W123: "'{a}' is already defined in outer scope.",
W124: "A generator function shall contain a yield statement.",
W125: "This line contains non-breaking spaces: http://jshint.com/doc/options/#nonbsp",
W126: "Unnecessary grouping operator.",
W127: "Unexpected use of a comma operator.",
W128: "Empty array elements require elision=true.",
W129: "'{a}' is defined in a future version of JavaScript. Use a " +
"different variable name to avoid migration issues.",
W130: "Invalid element after rest element.",
W131: "Invalid parameter after rest parameter.",
W132: "`var` declarations are forbidden. Use `let` or `const` instead.",
W133: "Invalid for-{a} loop left-hand-side: {b}.",
W134: "The '{a}' option is only available when linting ECMAScript {b} code."
};
var info = {
I001: "Comma warnings can be turned off with 'laxcomma'.",
I002: null,
I003: "ES5 option is now set per default"
};
exports.errors = {};
exports.warnings = {};
exports.info = {};
_.each(errors, function(desc, code) {
exports.errors[code] = { code: code, desc: desc };
});
_.each(warnings, function(desc, code) {
exports.warnings[code] = { code: code, desc: desc };
});
_.each(info, function(desc, code) {
exports.info[code] = { code: code, desc: desc };
});
},{"lodash":12}],15:[function(require,module,exports){
"use strict";
function NameStack() {
this._stack = [];
}
Object.defineProperty(NameStack.prototype, "length", {
get: function() {
return this._stack.length;
}
});
/**
* Create a new entry in the stack. Useful for tracking names across
* expressions.
*/
NameStack.prototype.push = function() {
this._stack.push(null);
};
/**
* Discard the most recently-created name on the stack.
*/
NameStack.prototype.pop = function() {
this._stack.pop();
};
/**
* Update the most recent name on the top of the stack.
*
* @param {object} token The token to consider as the source for the most
* recent name.
*/
NameStack.prototype.set = function(token) {
this._stack[this.length - 1] = token;
};
/**
* Generate a string representation of the most recent name.
*
* @returns {string}
*/
NameStack.prototype.infer = function() {
var nameToken = this._stack[this.length - 1];
var prefix = "";
var type;
// During expected operation, the topmost entry on the stack will only
// reflect the current function's name when the function is declared without
// the `function` keyword (i.e. for in-line accessor methods). In other
// cases, the `function` expression itself will introduce an empty entry on
// the top of the stack, and this should be ignored.
if (!nameToken || nameToken.type === "class") {
nameToken = this._stack[this.length - 2];
}
if (!nameToken) {
return "(empty)";
}
type = nameToken.type;
if (type !== "(string)" && type !== "(number)" && type !== "(identifier)" && type !== "default") {
return "(expression)";
}
if (nameToken.accessorType) {
prefix = nameToken.accessorType + " ";
}
return prefix + nameToken.value;
};
module.exports = NameStack;
},{}],16:[function(require,module,exports){
"use strict";
// These are the JSHint boolean options.
exports.bool = {
enforcing: {
/**
* This option prohibits the use of bitwise operators such as `^` (XOR),
* `|` (OR) and others. Bitwise operators are very rare in JavaScript
* programs and quite often `&` is simply a mistyped `&&`.
*/
bitwise : true,
/**
*
* This options prohibits overwriting prototypes of native objects such as
* `Array`, `Date` and so on.
*
* // jshint freeze:true
* Array.prototype.count = function (value) { return 4; };
* // -> Warning: Extending prototype of native object: 'Array'.
*/
freeze : true,
/**
* This option allows you to force all variable names to use either
* camelCase style or UPPER_CASE with underscores.
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
camelcase : true,
/**
* This option requires you to always put curly braces around blocks in
* loops and conditionals. JavaScript allows you to omit curly braces when
* the block consists of only one statement, for example:
*
* while (day)
* shuffle();
*
* However, in some circumstances, it can lead to bugs (you'd think that
* `sleep()` is a part of the loop while in reality it is not):
*
* while (day)
* shuffle();
* sleep();
*/
curly : true,
/**
* This options prohibits the use of `==` and `!=` in favor of `===` and
* `!==`. The former try to coerce values before comparing them which can
* lead to some unexpected results. The latter don't do any coercion so
* they are generally safer. If you would like to learn more about type
* coercion in JavaScript, we recommend [Truth, Equality and
* JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/)
* by Angus Croll.
*/
eqeqeq : true,
/**
* This option enables warnings about the use of identifiers which are
* defined in future versions of JavaScript. Although overwriting them has
* no effect in contexts where they are not implemented, this practice can
* cause issues when migrating codebases to newer versions of the language.
*/
futurehostile: true,
/**
* This option suppresses warnings about invalid `typeof` operator values.
* This operator has only [a limited set of possible return
* values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).
* By default, JSHint warns when you compare its result with an invalid
* value which often can be a typo.
*
* // 'fuction' instead of 'function'
* if (typeof a == "fuction") { // Invalid typeof value 'fuction'
* // ...
* }
*
* Do not use this option unless you're absolutely sure you don't want
* these checks.
*/
notypeof : true,
/**
* This option tells JSHint that your code needs to adhere to ECMAScript 3
* specification. Use this option if you need your program to be executable
* in older browserssuch as Internet Explorer 6/7/8/9and other legacy
* JavaScript environments.
*/
es3 : true,
/**
* This option enables syntax first defined in [the ECMAScript 5.1
* specification](http://es5.github.io/). This includes allowing reserved
* keywords as object properties.
*/
es5 : true,
/**
* This option requires all `for in` loops to filter object's items. The
* for in statement allows for looping through the names of all of the
* properties of an object including those inherited through the prototype
* chain. This behavior can lead to unexpected items in your object so it
* is generally safer to always filter inherited properties out as shown in
* the example:
*
* for (key in obj) {
* if (obj.hasOwnProperty(key)) {
* // We are sure that obj[key] belongs to the object and was not inherited.
* }
* }
*
* For more in-depth understanding of `for in` loops in JavaScript, read
* [Exploring JavaScript for-in
* loops](http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/)
* by Angus Croll.
*/
forin : true,
/**
* This option suppresses warnings about declaring variables inside of
* control
* structures while accessing them later from the outside. Even though
* JavaScript has only two real scopesglobal and functionsuch practice
* leads to confusion among people new to the language and hard-to-debug
* bugs. This is why, by default, JSHint warns about variables that are
* used outside of their intended scope.
*
* function test() {
* if (true) {
* var x = 0;
* }
*
* x += 1; // Default: 'x' used out of scope.
* // No warning when funcscope:true
* }
*/
funcscope : true,
/**
* This option prohibits the use of immediate function invocations without
* wrapping them in parentheses. Wrapping parentheses assists readers of
* your code in understanding that the expression is the result of a
* function, and not the function itself.
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
immed : true,
/**
* This option suppresses warnings about the `__iterator__` property. This
* property is not supported by all browsers so use it carefully.
*/
iterator : true,
/**
* This option requires you to capitalize names of constructor functions.
* Capitalizing functions that are intended to be used with `new` operator
* is just a convention that helps programmers to visually distinguish
* constructor functions from other types of functions to help spot
* mistakes when using `this`.
*
* Not doing so won't break your code in any browsers or environments but
* it will be a bit harder to figure outby reading the codeif the
* function was supposed to be used with or without new. And this is
* important because when the function that was intended to be used with
* `new` is used without it, `this` will point to the global object instead
* of a new object.
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
newcap : true,
/**
* This option prohibits the use of `arguments.caller` and
* `arguments.callee`. Both `.caller` and `.callee` make quite a few
* optimizations impossible so they were deprecated in future versions of
* JavaScript. In fact, ECMAScript 5 forbids the use of `arguments.callee`
* in strict mode.
*/
noarg : true,
/**
* This option prohibits the use of the comma operator. When misused, the
* comma operator can obscure the value of a statement and promote
* incorrect code.
*/
nocomma : true,
/**
* This option warns when you have an empty block in your code. JSLint was
* originally warning for all empty blocks and we simply made it optional.
* There were no studies reporting that empty blocks in JavaScript break
* your code in any way.
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
noempty : true,
/**
* This option warns about "non-breaking whitespace" characters. These
* characters can be entered with option-space on Mac computers and have a
* potential of breaking non-UTF8 web pages.
*/
nonbsp : true,
/**
* This option prohibits the use of constructor functions for side-effects.
* Some people like to call constructor functions without assigning its
* result to any variable:
*
* new MyConstructor();
*
* There is no advantage in this approach over simply calling
* `MyConstructor` since the object that the operator `new` creates isn't
* used anywhere so you should generally avoid constructors like this one.
*/
nonew : true,
/**
* This option prohibits the use of explicitly undeclared variables. This
* option is very useful for spotting leaking and mistyped variables.
*
* // jshint undef:true
*
* function test() {
* var myVar = 'Hello, World';
* console.log(myvar); // Oops, typoed here. JSHint with undef will complain
* }
*
* If your variable is defined in another file, you can use the `global`
* directive to tell JSHint about it.
*/
undef : true,
/**
* This option prohibits the use of the grouping operator when it is not
* strictly required. Such usage commonly reflects a misunderstanding of
* unary operators, for example:
*
* // jshint singleGroups: true
*
* delete(obj.attr); // Warning: Unnecessary grouping operator.
*/
singleGroups: false,
/**
* This option requires all functions to run in ECMAScript 5's strict mode.
* [Strict mode](https://developer.mozilla.org/en/JavaScript/Strict_mode)
* is a way to opt in to a restricted variant of JavaScript. Strict mode
* eliminates some JavaScript pitfalls that didn't cause errors by changing
* them to produce errors. It also fixes mistakes that made it difficult
* for the JavaScript engines to perform certain optimizations.
*
* *Note:* This option enables strict mode for function scope only. It
* *prohibits* the global scoped strict mode because it might break
* third-party widgets on your page. If you really want to use global
* strict mode, see the *globalstrict* option.
*/
strict : true,
/**
* When set to true, the use of VariableStatements are forbidden.
* For example:
*
* // jshint varstmt: true
*
* var a; // Warning: `var` declarations are forbidden. Use `let` or `const` instead.
*/
varstmt: false,
/**
* This option is a short hand for the most strict JSHint configuration as
* available in JSHint version 2.6.3. It enables all enforcing options and
* disables all relaxing options that were defined in that release.
*
* @deprecated The option cannot be maintained without automatically opting
* users in to new features. This can lead to unexpected
* warnings/errors in when upgrading between minor versions of
* JSHint.
*/
enforceall : false
},
relaxing: {
/**
* This option suppresses warnings about missing semicolons. There is a lot
* of FUD about semicolon spread by quite a few people in the community.
* The common myths are that semicolons are required all the time (they are
* not) and that they are unreliable. JavaScript has rules about semicolons
* which are followed by *all* browsers so it is up to you to decide
* whether you should or should not use semicolons in your code.
*
* For more information about semicolons in JavaScript read [An Open Letter
* to JavaScript Leaders Regarding
* Semicolons](http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding)
* by Isaac Schlueter and [JavaScript Semicolon
* Insertion](http://inimino.org/~inimino/blog/javascript_semicolons).
*/
asi : true,
/**
* This option suppresses warnings about multi-line strings. Multi-line
* strings can be dangerous in JavaScript because all hell breaks loose if
* you accidentally put a whitespace in between the escape character (`\`)
* and a new line.
*
* Note that even though this option allows correct multi-line strings, it
* still warns about multi-line strings without escape characters or with
* anything in between the escape character and a whitespace.
*
* // jshint multistr:true
*
* var text = "Hello\
* World"; // All good.
*
* text = "Hello
* World"; // Warning, no escape character.
*
* text = "Hello\
* World"; // Warning, there is a space after \
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
multistr : true,
/**
* This option suppresses warnings about the `debugger` statements in your
* code.
*/
debug : true,
/**
* This option suppresses warnings about the use of assignments in cases
* where comparisons are expected. More often than not, code like `if (a =
* 10) {}` is a typo. However, it can be useful in cases like this one:
*
* for (var i = 0, person; person = people[i]; i++) {}
*
* You can silence this error on a per-use basis by surrounding the assignment
* with parenthesis, such as:
*
* for (var i = 0, person; (person = people[i]); i++) {}
*/
boss : true,
/**
* This option suppresses warnings about the use of `eval`. The use of
* `eval` is discouraged because it can make your code vulnerable to
* various injection attacks and it makes it hard for JavaScript
* interpreter to do certain optimizations.
*/
evil : true,
/**
* This option suppresses warnings about the use of global strict mode.
* Global strict mode can break third-party widgets so it is not
* recommended.
*
* For more info about strict mode see the `strict` option.
*/
globalstrict: true,
/**
* This option prohibits the use of unary increment and decrement
* operators. Some people think that `++` and `--` reduces the quality of
* their coding styles and there are programming languagessuch as
* Pythonthat go completely without these operators.
*/
plusplus : true,
/**
* This option suppresses warnings about the `__proto__` property.
*/
proto : true,
/**
* This option suppresses warnings about the use of script-targeted
* URLssuch as `javascript:...`.
*/
scripturl : true,
/**
* This option suppresses warnings about using `[]` notation when it can be
* expressed in dot notation: `person['name']` vs. `person.name`.
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
sub : true,
/**
* This option suppresses warnings about "weird" constructions like
* `new function () { ... }` and `new Object;`. Such constructions are
* sometimes used to produce singletons in JavaScript:
*
* var singleton = new function() {
* var privateVar;
*
* this.publicMethod = function () {}
* this.publicMethod2 = function () {}
* };
*/
supernew : true,
/**
* This option suppresses most of the warnings about possibly unsafe line
* breakings in your code. It doesn't suppress warnings about comma-first
* coding style. To suppress those you have to use `laxcomma` (see below).
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
laxbreak : true,
/**
* This option suppresses warnings about comma-first coding style:
*
* var obj = {
* name: 'Anton'
* , handle: 'valueof'
* , role: 'SW Engineer'
* };
*
* @deprecated JSHint is limiting its scope to issues of code correctness.
* If you would like to enforce rules relating to code style,
* check out [the JSCS
* project](https://github.com/jscs-dev/node-jscs).
*/
laxcomma : true,
/**
* This option suppresses warnings about possible strict violations when
* the code is running in strict mode and you use `this` in a
* non-constructor function. You should use this optionin a function scope
* onlywhen you are positive that your use of `this` is valid in the
* strict mode (for example, if you call your function using
* `Function.call`).
*
* **Note:** This option can be used only inside of a function scope.
* JSHint will fail with an error if you will try to set this option
* globally.
*/
validthis : true,
/**
* This option suppresses warnings about the use of the `with` statement.
* The semantics of the `with` statement can cause confusion among
* developers and accidental definition of global variables.
*
* More info:
*
* * [with Statement Considered
* Harmful](http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/)
*/
withstmt : true,
/**
* This options tells JSHint that your code uses Mozilla JavaScript
* extensions. Unless you develop specifically for the Firefox web browser
* you don't need this option.
*
* More info:
*
* * [New in JavaScript
* 1.7](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7)
*/
moz : true,
/**
* This option suppresses warnings about generator functions with no
* `yield` statement in them.
*/
noyield : true,
/**
* This option suppresses warnings about `== null` comparisons. Such
* comparisons are often useful when you want to check if a variable is
* `null` or `undefined`.
*/
eqnull : true,
/**
* This option suppresses warnings about missing semicolons, but only when
* the semicolon is omitted for the last statement in a one-line block:
*
* var name = (function() { return 'Anton' }());
*
* This is a very niche use case that is useful only when you use automatic
* JavaScript code generators.
*/
lastsemic : true,
/**
* This option suppresses warnings about functions inside of loops.
* Defining functions inside of loops can lead to bugs such as this one:
*
* var nums = [];
*
* for (var i = 0; i < 10; i++) {
* nums[i] = function (j) {
* return i + j;
* };
* }
*
* nums[0](2); // Prints 12 instead of 2
*
* To fix the code above you need to copy the value of `i`:
*
* var nums = [];
*
* for (var i = 0; i < 10; i++) {
* (function (i) {
* nums[i] = function (j) {
* return i + j;
* };
* }(i));
* }
*/
loopfunc : true,
/**
* This option suppresses warnings about the use of expressions where
* normally you would expect to see assignments or function calls. Most of
* the time, such code is a typo. However, it is not forbidden by the spec
* and that's why this warning is optional.
*/
expr : true,
/**
* This option tells JSHint that your code uses ECMAScript 6 specific
* syntax. Note that these features are not finalized yet and not all
* browsers implement them.
*
* More info:
*
* * [Draft Specification for ES.next (ECMA-262 Ed.
* 6)](http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts)
*/
esnext : true,
/**
* This option tells JSHint that your code uses ES3 array elision elements,
* or empty elements (for example, `[1, , , 4, , , 7]`).
*/
elision : true,
},
// Third party globals
environments: {
/**
* This option defines globals exposed by the
* [MooTools](http://mootools.net/) JavaScript framework.
*/
mootools : true,
/**
* This option defines globals exposed by
* [CouchDB](http://couchdb.apache.org/). CouchDB is a document-oriented
* database that can be queried and indexed in a MapReduce fashion using
* JavaScript.
*/
couch : true,
/**
* This option defines globals exposed by [the Jasmine unit testing
* framework](https://jasmine.github.io/).
*/
jasmine : true,
/**
* This option defines globals exposed by the [jQuery](http://jquery.com/)
* JavaScript library.
*/
jquery : true,
/**
* This option defines globals available when your code is running inside
* of the Node runtime environment. [Node.js](http://nodejs.org/) is a
* server-side JavaScript environment that uses an asynchronous
* event-driven model. This option also skips some warnings that make sense
* in the browser environments but don't make sense in Node such as
* file-level `use strict` pragmas and `console.log` statements.
*/
node : true,
/**
* This option defines globals exposed by [the QUnit unit testing
* framework](http://qunitjs.com/).
*/
qunit : true,
/**
* This option defines globals available when your code is running inside
* of the Rhino runtime environment. [Rhino](http://www.mozilla.org/rhino/)
* is an open-source implementation of JavaScript written entirely in Java.
*/
rhino : true,
/**
* This option defines globals exposed by [the ShellJS
* library](http://documentup.com/arturadib/shelljs).
*/
shelljs : true,
/**
* This option defines globals exposed by the
* [Prototype](http://www.prototypejs.org/) JavaScript framework.
*/
prototypejs : true,
/**
* This option defines globals exposed by the [YUI](http://yuilibrary.com/)
* JavaScript framework.
*/
yui : true,
/**
* This option defines globals exposed by the "BDD" and "TDD" UIs of the
* [Mocha unit testing framework](http://mochajs.org/).
*/
mocha : true,
/**
* This option informs JSHint that the input code describes an ECMAScript 6
* module. All module code is interpreted as strict mode code.
*/
module : true,
/**
* This option defines globals available when your code is running as a
* script for the [Windows Script
* Host](http://en.wikipedia.org/wiki/Windows_Script_Host).
*/
wsh : true,
/**
* This option defines globals available when your code is running inside
* of a Web Worker. [Web
* Workers](https://developer.mozilla.org/en/Using_web_workers) provide a
* simple means for web content to run scripts in background threads.
*/
worker : true,
/**
* This option defines non-standard but widely adopted globals such as
* `escape` and `unescape`.
*/
nonstandard : true,
/**
* This option defines globals exposed by modern browsers: all the way from
* good old `document` and `navigator` to the HTML5 `FileReader` and other
* new developments in the browser world.
*
* **Note:** This option doesn't expose variables like `alert` or
* `console`. See option `devel` for more information.
*/
browser : true,
/**
* This option defines globals available when using [the Browserify
* tool](http://browserify.org/) to build a project.
*/
browserify : true,
/**
* This option defines globals that are usually used for logging poor-man's
* debugging: `console`, `alert`, etc. It is usually a good idea to not
* ship them in production because, for example, `console.log` breaks in
* legacy versions of Internet Explorer.
*/
devel : true,
/**
* This option defines globals exposed by the [Dojo
* Toolkit](http://dojotoolkit.org/).
*/
dojo : true,
/**
* This option defines globals for typed array constructors.
*
* More info:
*
* * [JavaScript typed
* arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
*/
typed : true,
/**
* This option defines globals available when your core is running inside
* of the PhantomJS runtime environment. [PhantomJS](http://phantomjs.org/)
* is a headless WebKit scriptable with a JavaScript API. It has fast and
* native support for various web standards: DOM handling, CSS selector,
* JSON, Canvas, and SVG.
*/
phantom : true
},
// Obsolete options
obsolete: {
onecase : true, // if one case switch statements should be allowed
regexp : true, // if the . should not be allowed in regexp literals
regexdash : true // if unescaped first/last dash (-) inside brackets
// should be tolerated
}
};
// These are the JSHint options that can take any value
// (we use this object to detect invalid options)
exports.val = {
/**
* This option lets you set the maximum length of a line.
*
* @deprecated JSHint is limiting its scope to issues of code correctness. If
* you would like to enforce rules relating to code style, check
* out [the JSCS project](https://github.com/jscs-dev/node-jscs).
*/
maxlen : false,
/**
* This option sets a specific tab width for your code.
*
* @deprecated JSHint is limiting its scope to issues of code correctness. If
* you would like to enforce rules relating to code style, check
* out [the JSCS project](https://github.com/jscs-dev/node-jscs).
*/
indent : false,
/**
* This options allows you to set the maximum amount of warnings JSHint will
* produce before giving up. Default is 50.
*/
maxerr : false,
predef : false, // predef is deprecated and being replaced by globals
/**
* This option can be used to specify a white list of global variables that
* are not formally defined in the source code. This is most useful when
* combined with the `undef` option in order to suppress warnings for
* project-specific global variables.
*
* Setting an entry to `true` enables reading and writing to that variable.
* Setting it to `false` will trigger JSHint to consider that variable
* read-only.
*
* See also the "environment" options: a set of options to be used as short
* hand for enabling global variables defined in common JavaScript
* environments.
*/
globals : false,
/**
* This option enforces the consistency of quotation marks used throughout
* your code. It accepts three values: `true` if you don't want to enforce
* one particular style but want some consistency, `"single"` if you want to
* allow only single quotes and `"double"` if you want to allow only double
* quotes.
*
* @deprecated JSHint is limiting its scope to issues of code correctness. If
* you would like to enforce rules relating to code style, check
* out [the JSCS project](https://github.com/jscs-dev/node-jscs).
*/
quotmark : false,
scope : false,
/**
* This option lets you set the max number of statements allowed per function:
*
* // jshint maxstatements:4
*
* function main() {
* var i = 0;
* var j = 0;
*
* // Function declarations count as one statement. Their bodies
* // don't get taken into account for the outer function.
* function inner() {
* var i2 = 1;
* var j2 = 1;
*
* return i2 + j2;
* }
*
* j = i + j;
* return j; // JSHint: Too many statements per function. (5)
* }
*/
maxstatements: false,
/**
* This option lets you control how nested do you want your blocks to be:
*
* // jshint maxdepth:2
*
* function main(meaning) {
* var day = true;
*
* if (meaning === 42) {
* while (day) {
* shuffle();
*
* if (tired) { // JSHint: Blocks are nested too deeply (3).
* sleep();
* }
* }
* }
* }
*/
maxdepth : false,
/**
* This option lets you set the max number of formal parameters allowed per
* function:
*
* // jshint maxparams:3
*
* function login(request, onSuccess) {
* // ...
* }
*
* // JSHint: Too many parameters per function (4).
* function logout(request, isManual, whereAmI, onSuccess) {
* // ...
* }
*/
maxparams : false,
/**
* This option lets you control cyclomatic complexity throughout your code.
* Cyclomatic complexity measures the number of linearly independent paths
* through a program's source code. Read more about [cyclomatic complexity on
* Wikipedia](http://en.wikipedia.org/wiki/Cyclomatic_complexity).
*/
maxcomplexity: false,
/**
* This option suppresses warnings about variable shadowing i.e. declaring a
* variable that had been already declared somewhere in the outer scope.
*
* - "inner" - check for variables defined in the same scope only
* - "outer" - check for variables defined in outer scopes as well
* - false - same as inner
* - true - allow variable shadowing
*/
shadow : false,
/**
* This option warns when you define and never use your variables. It is very
* useful for general code cleanup, especially when used in addition to
* `undef`.
*
* // jshint unused:true
*
* function test(a, b) {
* var c, d = 2;
*
* return a + d;
* }
*
* test(1, 2);
*
* // Line 3: 'b' was defined but never used.
* // Line 4: 'c' was defined but never used.
*
* In addition to that, this option will warn you about unused global
* variables declared via the `global` directive.
*
* This can be set to `vars` to only check for variables, not function
* parameters, or `strict` to check all variables and parameters. The
* default (true) behavior is to allow unused parameters that are followed by
* a used parameter.
*/
unused : true,
/**
* This option prohibits the use of a variable before it was defined.
* JavaScript has function scope only and, in addition to that, all variables
* are always movedor hoisted to the top of the function. This behavior can
* lead to some very nasty bugs and that's why it is safer to always use
* variable only after they have been explicitly defined.
*
* Setting this option to "nofunc" will allow function declarations to be
* ignored.
*
* For more in-depth understanding of scoping and hoisting in JavaScript,
* read [JavaScript Scoping and
* Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting)
* by Ben Cherry.
*/
latedef : false,
ignore : false, // start/end ignoring lines of code, bypassing the lexer
// start - start ignoring lines, including the current line
// end - stop ignoring lines, starting on the next line
// line - ignore warnings / errors for just a single line
// (this option does not bypass the lexer)
ignoreDelimiters: false // array of start/end delimiters used to ignore
// certain chunks from code
};
// These are JSHint boolean options which are shared with JSLint
// where the definition in JSHint is opposite JSLint
exports.inverted = {
bitwise : true,
forin : true,
newcap : true,
plusplus: true,
regexp : true,
undef : true,
// Inverted and renamed, use JSHint name here
eqeqeq : true,
strict : true
};
exports.validNames = Object.keys(exports.val)
.concat(Object.keys(exports.bool.relaxing))
.concat(Object.keys(exports.bool.enforcing))
.concat(Object.keys(exports.bool.obsolete))
.concat(Object.keys(exports.bool.environments));
// These are JSHint boolean options which are shared with JSLint
// where the name has been changed but the effect is unchanged
exports.renamed = {
eqeq : "eqeqeq",
windows: "wsh",
sloppy : "strict"
};
exports.removed = {
nomen: true,
onevar: true,
passfail: true,
white: true,
gcl: true,
smarttabs: true,
trailing: true
};
// Add options here which should not be automatically enforced by
// `enforceall`.
exports.noenforceall = {
varstmt: true,
strict: true
};
},{}],17:[function(require,module,exports){
/*
* Regular expressions. Some of these are stupidly long.
*/
/*jshint maxlen:1000 */
"use strict";
// Unsafe comment or string (ax)
exports.unsafeString =
/@cc|<\/?|script|\]\s*\]|<\s*!|&lt/i;
// Unsafe characters that are silently deleted by one or more browsers (cx)
exports.unsafeChars =
/[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/;
// Characters in strings that need escaping (nx and nxg)
exports.needEsc =
/[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/;
exports.needEscGlobal =
/[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
// Star slash (lx)
exports.starSlash = /\*\//;
// Identifier (ix)
exports.identifier = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/;
// JavaScript URL (jx)
exports.javascriptURL = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i;
// Catches /* falls through */ comments (ft)
exports.fallsThrough = /^\s*\/\*\s*falls?\sthrough\s*\*\/\s*$/;
// very conservative rule (eg: only one space between the start of the comment and the first character)
// to relax the maxlen option
exports.maxlenException = /^(?:(?:\/\/|\/\*|\*) ?)?[^ ]+$/;
},{}],18:[function(require,module,exports){
"use strict";
var NameStack = require("./name-stack.js");
var state = {
syntax: {},
/**
* Determine if the code currently being linted is strict mode code.
*
* @returns {boolean}
*/
isStrict: function() {
return this.directive["use strict"] || this.inClassBody ||
this.option.module;
},
// Assumption: chronologically ES3 < ES5 < ES6/ESNext < Moz
inMoz: function() {
return this.option.moz && !this.option.esnext;
},
/**
* @param {object} options
* @param {boolean} options.strict - When `true`, only consider ESNext when
* in "esnext" code and *not* in "moz".
*/
inESNext: function(strict) {
if (strict) {
return !this.option.moz && this.option.esnext;
}
return this.option.moz || this.option.esnext;
},
inES5: function() {
return !this.option.es3;
},
inES3: function() {
return this.option.es3;
},
reset: function() {
this.tokens = {
prev: null,
next: null,
curr: null
};
this.option = {};
this.ignored = {};
this.directive = {};
this.jsonMode = false;
this.jsonWarnings = [];
this.lines = [];
this.tab = "";
this.cache = {}; // Node.JS doesn't have Map. Sniff.
this.ignoredLines = {};
this.forinifcheckneeded = false;
this.nameStack = new NameStack();
this.inClassBody = false;
// Blank out non-multi-line-commented lines when ignoring linter errors
this.ignoreLinterErrors = false;
}
};
exports.state = state;
},{"./name-stack.js":15}],19:[function(require,module,exports){
"use strict";
exports.register = function(linter) {
// Check for properties named __proto__. This special property was
// deprecated and then re-introduced for ES6.
linter.on("Identifier", function style_scanProto(data) {
if (linter.getOption("proto")) {
return;
}
if (data.name === "__proto__") {
linter.warn("W103", {
line: data.line,
char: data.char,
data: [ data.name ]
});
}
});
// Check for properties named __iterator__. This is a special property
// available only in browsers with JavaScript 1.7 implementation.
linter.on("Identifier", function style_scanIterator(data) {
if (linter.getOption("iterator")) {
return;
}
if (data.name === "__iterator__") {
linter.warn("W104", {
line: data.line,
char: data.char,
data: [ data.name ]
});
}
});
// Check that all identifiers are using camelCase notation.
// Exceptions: names like MY_VAR and _myVar.
linter.on("Identifier", function style_scanCamelCase(data) {
if (!linter.getOption("camelcase")) {
return;
}
if (data.name.replace(/^_+|_+$/g, "").indexOf("_") > -1 && !data.name.match(/^[A-Z0-9_]*$/)) {
linter.warn("W106", {
line: data.line,
char: data.from,
data: [ data.name ]
});
}
});
// Enforce consistency in style of quoting.
linter.on("String", function style_scanQuotes(data) {
var quotmark = linter.getOption("quotmark");
var code;
if (!quotmark) {
return;
}
// If quotmark is set to 'single' warn about all double-quotes.
if (quotmark === "single" && data.quote !== "'") {
code = "W109";
}
// If quotmark is set to 'double' warn about all single-quotes.
if (quotmark === "double" && data.quote !== "\"") {
code = "W108";
}
// If quotmark is set to true, remember the first quotation style
// and then warn about all others.
if (quotmark === true) {
if (!linter.getCache("quotmark")) {
linter.setCache("quotmark", data.quote);
}
if (linter.getCache("quotmark") !== data.quote) {
code = "W110";
}
}
if (code) {
linter.warn(code, {
line: data.line,
char: data.char,
});
}
});
linter.on("Number", function style_scanNumbers(data) {
if (data.value.charAt(0) === ".") {
// Warn about a leading decimal point.
linter.warn("W008", {
line: data.line,
char: data.char,
data: [ data.value ]
});
}
if (data.value.substr(data.value.length - 1) === ".") {
// Warn about a trailing decimal point.
linter.warn("W047", {
line: data.line,
char: data.char,
data: [ data.value ]
});
}
if (/^00+/.test(data.value)) {
// Multiple leading zeroes.
linter.warn("W046", {
line: data.line,
char: data.char,
data: [ data.value ]
});
}
});
// Warn about script URLs.
linter.on("String", function style_scanJavaScriptURLs(data) {
var re = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i;
if (linter.getOption("scripturl")) {
return;
}
if (re.test(data.value)) {
linter.warn("W107", {
line: data.line,
char: data.char
});
}
});
};
},{}],20:[function(require,module,exports){
// jshint -W001
"use strict";
// Identifiers provided by the ECMAScript standard.
exports.reservedVars = {
arguments : false,
NaN : false
};
exports.ecmaIdentifiers = {
3: {
Array : false,
Boolean : false,
Date : false,
decodeURI : false,
decodeURIComponent : false,
encodeURI : false,
encodeURIComponent : false,
Error : false,
"eval" : false,
EvalError : false,
Function : false,
hasOwnProperty : false,
isFinite : false,
isNaN : false,
Math : false,
Number : false,
Object : false,
parseInt : false,
parseFloat : false,
RangeError : false,
ReferenceError : false,
RegExp : false,
String : false,
SyntaxError : false,
TypeError : false,
URIError : false
},
5: {
JSON : false
},
6: {
Map : false,
Promise : false,
Proxy : false,
Reflect : false,
Set : false,
Symbol : false,
WeakMap : false,
WeakSet : false
}
};
// Global variables commonly provided by a web browser environment.
exports.browser = {
Audio : false,
Blob : false,
addEventListener : false,
applicationCache : false,
atob : false,
blur : false,
btoa : false,
cancelAnimationFrame : false,
CanvasGradient : false,
CanvasPattern : false,
CanvasRenderingContext2D: false,
CSS : false,
clearInterval : false,
clearTimeout : false,
close : false,
closed : false,
Comment : false,
CustomEvent : false,
DOMParser : false,
defaultStatus : false,
Document : false,
document : false,
DocumentFragment : false,
Element : false,
ElementTimeControl : false,
Event : false,
event : false,
fetch : false,
FileReader : false,
FormData : false,
focus : false,
frames : false,
getComputedStyle : false,
HTMLElement : false,
HTMLAnchorElement : false,
HTMLBaseElement : false,
HTMLBlockquoteElement: false,
HTMLBodyElement : false,
HTMLBRElement : false,
HTMLButtonElement : false,
HTMLCanvasElement : false,
HTMLDirectoryElement : false,
HTMLDivElement : false,
HTMLDListElement : false,
HTMLFieldSetElement : false,
HTMLFontElement : false,
HTMLFormElement : false,
HTMLFrameElement : false,
HTMLFrameSetElement : false,
HTMLHeadElement : false,
HTMLHeadingElement : false,
HTMLHRElement : false,
HTMLHtmlElement : false,
HTMLIFrameElement : false,
HTMLImageElement : false,
HTMLInputElement : false,
HTMLIsIndexElement : false,
HTMLLabelElement : false,
HTMLLayerElement : false,
HTMLLegendElement : false,
HTMLLIElement : false,
HTMLLinkElement : false,
HTMLMapElement : false,
HTMLMenuElement : false,
HTMLMetaElement : false,
HTMLModElement : false,
HTMLObjectElement : false,
HTMLOListElement : false,
HTMLOptGroupElement : false,
HTMLOptionElement : false,
HTMLParagraphElement : false,
HTMLParamElement : false,
HTMLPreElement : false,
HTMLQuoteElement : false,
HTMLScriptElement : false,
HTMLSelectElement : false,
HTMLStyleElement : false,
HTMLTableCaptionElement: false,
HTMLTableCellElement : false,
HTMLTableColElement : false,
HTMLTableElement : false,
HTMLTableRowElement : false,
HTMLTableSectionElement: false,
HTMLTemplateElement : false,
HTMLTextAreaElement : false,
HTMLTitleElement : false,
HTMLUListElement : false,
HTMLVideoElement : false,
history : false,
Image : false,
Intl : false,
length : false,
localStorage : false,
location : false,
matchMedia : false,
MessageChannel : false,
MessageEvent : false,
MessagePort : false,
MouseEvent : false,
moveBy : false,
moveTo : false,
MutationObserver : false,
name : false,
Node : false,
NodeFilter : false,
NodeList : false,
Notification : false,
navigator : false,
onbeforeunload : true,
onblur : true,
onerror : true,
onfocus : true,
onload : true,
onresize : true,
onunload : true,
open : false,
openDatabase : false,
opener : false,
Option : false,
parent : false,
print : false,
Range : false,
requestAnimationFrame : false,
removeEventListener : false,
resizeBy : false,
resizeTo : false,
screen : false,
scroll : false,
scrollBy : false,
scrollTo : false,
sessionStorage : false,
setInterval : false,
setTimeout : false,
SharedWorker : false,
status : false,
SVGAElement : false,
SVGAltGlyphDefElement: false,
SVGAltGlyphElement : false,
SVGAltGlyphItemElement: false,
SVGAngle : false,
SVGAnimateColorElement: false,
SVGAnimateElement : false,
SVGAnimateMotionElement: false,
SVGAnimateTransformElement: false,
SVGAnimatedAngle : false,
SVGAnimatedBoolean : false,
SVGAnimatedEnumeration: false,
SVGAnimatedInteger : false,
SVGAnimatedLength : false,
SVGAnimatedLengthList: false,
SVGAnimatedNumber : false,
SVGAnimatedNumberList: false,
SVGAnimatedPathData : false,
SVGAnimatedPoints : false,
SVGAnimatedPreserveAspectRatio: false,
SVGAnimatedRect : false,
SVGAnimatedString : false,
SVGAnimatedTransformList: false,
SVGAnimationElement : false,
SVGCSSRule : false,
SVGCircleElement : false,
SVGClipPathElement : false,
SVGColor : false,
SVGColorProfileElement: false,
SVGColorProfileRule : false,
SVGComponentTransferFunctionElement: false,
SVGCursorElement : false,
SVGDefsElement : false,
SVGDescElement : false,
SVGDocument : false,
SVGElement : false,
SVGElementInstance : false,
SVGElementInstanceList: false,
SVGEllipseElement : false,
SVGExternalResourcesRequired: false,
SVGFEBlendElement : false,
SVGFEColorMatrixElement: false,
SVGFEComponentTransferElement: false,
SVGFECompositeElement: false,
SVGFEConvolveMatrixElement: false,
SVGFEDiffuseLightingElement: false,
SVGFEDisplacementMapElement: false,
SVGFEDistantLightElement: false,
SVGFEFloodElement : false,
SVGFEFuncAElement : false,
SVGFEFuncBElement : false,
SVGFEFuncGElement : false,
SVGFEFuncRElement : false,
SVGFEGaussianBlurElement: false,
SVGFEImageElement : false,
SVGFEMergeElement : false,
SVGFEMergeNodeElement: false,
SVGFEMorphologyElement: false,
SVGFEOffsetElement : false,
SVGFEPointLightElement: false,
SVGFESpecularLightingElement: false,
SVGFESpotLightElement: false,
SVGFETileElement : false,
SVGFETurbulenceElement: false,
SVGFilterElement : false,
SVGFilterPrimitiveStandardAttributes: false,
SVGFitToViewBox : false,
SVGFontElement : false,
SVGFontFaceElement : false,
SVGFontFaceFormatElement: false,
SVGFontFaceNameElement: false,
SVGFontFaceSrcElement: false,
SVGFontFaceUriElement: false,
SVGForeignObjectElement: false,
SVGGElement : false,
SVGGlyphElement : false,
SVGGlyphRefElement : false,
SVGGradientElement : false,
SVGHKernElement : false,
SVGICCColor : false,
SVGImageElement : false,
SVGLangSpace : false,
SVGLength : false,
SVGLengthList : false,
SVGLineElement : false,
SVGLinearGradientElement: false,
SVGLocatable : false,
SVGMPathElement : false,
SVGMarkerElement : false,
SVGMaskElement : false,
SVGMatrix : false,
SVGMetadataElement : false,
SVGMissingGlyphElement: false,
SVGNumber : false,
SVGNumberList : false,
SVGPaint : false,
SVGPathElement : false,
SVGPathSeg : false,
SVGPathSegArcAbs : false,
SVGPathSegArcRel : false,
SVGPathSegClosePath : false,
SVGPathSegCurvetoCubicAbs: false,
SVGPathSegCurvetoCubicRel: false,
SVGPathSegCurvetoCubicSmoothAbs: false,
SVGPathSegCurvetoCubicSmoothRel: false,
SVGPathSegCurvetoQuadraticAbs: false,
SVGPathSegCurvetoQuadraticRel: false,
SVGPathSegCurvetoQuadraticSmoothAbs: false,
SVGPathSegCurvetoQuadraticSmoothRel: false,
SVGPathSegLinetoAbs : false,
SVGPathSegLinetoHorizontalAbs: false,
SVGPathSegLinetoHorizontalRel: false,
SVGPathSegLinetoRel : false,
SVGPathSegLinetoVerticalAbs: false,
SVGPathSegLinetoVerticalRel: false,
SVGPathSegList : false,
SVGPathSegMovetoAbs : false,
SVGPathSegMovetoRel : false,
SVGPatternElement : false,
SVGPoint : false,
SVGPointList : false,
SVGPolygonElement : false,
SVGPolylineElement : false,
SVGPreserveAspectRatio: false,
SVGRadialGradientElement: false,
SVGRect : false,
SVGRectElement : false,
SVGRenderingIntent : false,
SVGSVGElement : false,
SVGScriptElement : false,
SVGSetElement : false,
SVGStopElement : false,
SVGStringList : false,
SVGStylable : false,
SVGStyleElement : false,
SVGSwitchElement : false,
SVGSymbolElement : false,
SVGTRefElement : false,
SVGTSpanElement : false,
SVGTests : false,
SVGTextContentElement: false,
SVGTextElement : false,
SVGTextPathElement : false,
SVGTextPositioningElement: false,
SVGTitleElement : false,
SVGTransform : false,
SVGTransformList : false,
SVGTransformable : false,
SVGURIReference : false,
SVGUnitTypes : false,
SVGUseElement : false,
SVGVKernElement : false,
SVGViewElement : false,
SVGViewSpec : false,
SVGZoomAndPan : false,
Text : false,
TextDecoder : false,
TextEncoder : false,
TimeEvent : false,
top : false,
URL : false,
WebGLActiveInfo : false,
WebGLBuffer : false,
WebGLContextEvent : false,
WebGLFramebuffer : false,
WebGLProgram : false,
WebGLRenderbuffer : false,
WebGLRenderingContext: false,
WebGLShader : false,
WebGLShaderPrecisionFormat: false,
WebGLTexture : false,
WebGLUniformLocation : false,
WebSocket : false,
window : false,
Worker : false,
XDomainRequest : false,
XMLHttpRequest : false,
XMLSerializer : false,
XPathEvaluator : false,
XPathException : false,
XPathExpression : false,
XPathNamespace : false,
XPathNSResolver : false,
XPathResult : false
};
exports.devel = {
alert : false,
confirm: false,
console: false,
Debug : false,
opera : false,
prompt : false
};
exports.worker = {
importScripts : true,
postMessage : true,
self : true,
FileReaderSync : true
};
// Widely adopted global names that are not part of ECMAScript standard
exports.nonstandard = {
escape : false,
unescape: false
};
// Globals provided by popular JavaScript environments.
exports.couch = {
"require" : false,
respond : false,
getRow : false,
emit : false,
send : false,
start : false,
sum : false,
log : false,
exports : false,
module : false,
provides : false
};
exports.node = {
__filename : false,
__dirname : false,
GLOBAL : false,
global : false,
module : false,
require : false,
// These globals are writeable because Node allows the following
// usage pattern: var Buffer = require("buffer").Buffer;
Buffer : true,
console : true,
exports : true,
process : true,
setTimeout : true,
clearTimeout : true,
setInterval : true,
clearInterval : true,
setImmediate : true, // v0.9.1+
clearImmediate: true // v0.9.1+
};
exports.browserify = {
__filename : false,
__dirname : false,
global : false,
module : false,
require : false,
Buffer : true,
exports : true,
process : true
};
exports.phantom = {
phantom : true,
require : true,
WebPage : true,
console : true, // in examples, but undocumented
exports : true // v1.7+
};
exports.qunit = {
asyncTest : false,
deepEqual : false,
equal : false,
expect : false,
module : false,
notDeepEqual : false,
notEqual : false,
notPropEqual : false,
notStrictEqual : false,
ok : false,
propEqual : false,
QUnit : false,
raises : false,
start : false,
stop : false,
strictEqual : false,
test : false,
"throws" : false
};
exports.rhino = {
defineClass : false,
deserialize : false,
gc : false,
help : false,
importClass : false,
importPackage: false,
"java" : false,
load : false,
loadClass : false,
Packages : false,
print : false,
quit : false,
readFile : false,
readUrl : false,
runCommand : false,
seal : false,
serialize : false,
spawn : false,
sync : false,
toint32 : false,
version : false
};
exports.shelljs = {
target : false,
echo : false,
exit : false,
cd : false,
pwd : false,
ls : false,
find : false,
cp : false,
rm : false,
mv : false,
mkdir : false,
test : false,
cat : false,
sed : false,
grep : false,
which : false,
dirs : false,
pushd : false,
popd : false,
env : false,
exec : false,
chmod : false,
config : false,
error : false,
tempdir : false
};
exports.typed = {
ArrayBuffer : false,
ArrayBufferView : false,
DataView : false,
Float32Array : false,
Float64Array : false,
Int16Array : false,
Int32Array : false,
Int8Array : false,
Uint16Array : false,
Uint32Array : false,
Uint8Array : false,
Uint8ClampedArray : false
};
exports.wsh = {
ActiveXObject : true,
Enumerator : true,
GetObject : true,
ScriptEngine : true,
ScriptEngineBuildVersion : true,
ScriptEngineMajorVersion : true,
ScriptEngineMinorVersion : true,
VBArray : true,
WSH : true,
WScript : true,
XDomainRequest : true
};
// Globals provided by popular JavaScript libraries.
exports.dojo = {
dojo : false,
dijit : false,
dojox : false,
define : false,
"require": false
};
exports.jquery = {
"$" : false,
jQuery : false
};
exports.mootools = {
"$" : false,
"$$" : false,
Asset : false,
Browser : false,
Chain : false,
Class : false,
Color : false,
Cookie : false,
Core : false,
Document : false,
DomReady : false,
DOMEvent : false,
DOMReady : false,
Drag : false,
Element : false,
Elements : false,
Event : false,
Events : false,
Fx : false,
Group : false,
Hash : false,
HtmlTable : false,
IFrame : false,
IframeShim : false,
InputValidator: false,
instanceOf : false,
Keyboard : false,
Locale : false,
Mask : false,
MooTools : false,
Native : false,
Options : false,
OverText : false,
Request : false,
Scroller : false,
Slick : false,
Slider : false,
Sortables : false,
Spinner : false,
Swiff : false,
Tips : false,
Type : false,
typeOf : false,
URI : false,
Window : false
};
exports.prototypejs = {
"$" : false,
"$$" : false,
"$A" : false,
"$F" : false,
"$H" : false,
"$R" : false,
"$break" : false,
"$continue" : false,
"$w" : false,
Abstract : false,
Ajax : false,
Class : false,
Enumerable : false,
Element : false,
Event : false,
Field : false,
Form : false,
Hash : false,
Insertion : false,
ObjectRange : false,
PeriodicalExecuter: false,
Position : false,
Prototype : false,
Selector : false,
Template : false,
Toggle : false,
Try : false,
Autocompleter : false,
Builder : false,
Control : false,
Draggable : false,
Draggables : false,
Droppables : false,
Effect : false,
Sortable : false,
SortableObserver : false,
Sound : false,
Scriptaculous : false
};
exports.yui = {
YUI : false,
Y : false,
YUI_config: false
};
exports.mocha = {
// BDD
describe : false,
xdescribe : false,
it : false,
xit : false,
context : false,
xcontext : false,
before : false,
after : false,
beforeEach : false,
afterEach : false,
// TDD
suite : false,
test : false,
setup : false,
teardown : false,
suiteSetup : false,
suiteTeardown : false
};
exports.jasmine = {
jasmine : false,
describe : false,
xdescribe : false,
it : false,
xit : false,
beforeEach : false,
afterEach : false,
setFixtures : false,
loadFixtures: false,
spyOn : false,
expect : false,
// Jasmine 1.3
runs : false,
waitsFor : false,
waits : false,
// Jasmine 2.1
beforeAll : false,
afterAll : false,
fail : false,
fdescribe : false,
fit : false
};
},{}],"jshint":[function(require,module,exports){
/*!
* JSHint, by JSHint Community.
*
* This file (and this file only) is licensed under the same slightly modified
* MIT license that JSLint is. It stops evil-doers everywhere:
*
* Copyright (c) 2002 Douglas Crockford (www.JSLint.com)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* The Software shall be used for Good, not Evil.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jshint quotmark:double */
/*global console:true */
/*exported console */
var _ = require("lodash");
var events = require("events");
var vars = require("./vars.js");
var messages = require("./messages.js");
var Lexer = require("./lex.js").Lexer;
var reg = require("./reg.js");
var state = require("./state.js").state;
var style = require("./style.js");
var options = require("./options.js");
// We need this module here because environments such as IE and Rhino
// don't necessarilly expose the 'console' API and browserify uses
// it to log things. It's a sad state of affair, really.
var console = require("console-browserify");
// We build the application inside a function so that we produce only a singleton
// variable. That function will be invoked immediately, and its return value is
// the JSHINT function itself.
var JSHINT = (function() {
"use strict";
var api, // Extension API
// These are operators that should not be used with the ! operator.
bang = {
"<" : true,
"<=" : true,
"==" : true,
"===": true,
"!==": true,
"!=" : true,
">" : true,
">=" : true,
"+" : true,
"-" : true,
"*" : true,
"/" : true,
"%" : true
},
declared, // Globals that were declared using /*global ... */ syntax.
exported, // Variables that are used outside of the current file.
functionicity = [
"closure", "exception", "global", "label",
"outer", "unused", "var"
],
funct, // The current function
functions, // All of the functions
global, // The global scope
implied, // Implied globals
inblock,
indent,
lookahead,
lex,
member,
membersOnly,
predefined, // Global variables defined by option
scope, // The current scope
stack,
unuseds,
urls,
extraModules = [],
emitter = new events.EventEmitter();
function checkOption(name, t) {
name = name.trim();
if (/^[+-]W\d{3}$/g.test(name)) {
return true;
}
if (options.validNames.indexOf(name) === -1) {
if (t.type !== "jslint" && !_.has(options.removed, name)) {
error("E001", t, name);
return false;
}
}
return true;
}
function isString(obj) {
return Object.prototype.toString.call(obj) === "[object String]";
}
function isIdentifier(tkn, value) {
if (!tkn)
return false;
if (!tkn.identifier || tkn.value !== value)
return false;
return true;
}
function isReserved(token) {
if (!token.reserved) {
return false;
}
var meta = token.meta;
if (meta && meta.isFutureReservedWord && state.inES5()) {
// ES3 FutureReservedWord in an ES5 environment.
if (!meta.es5) {
return false;
}
// Some ES5 FutureReservedWord identifiers are active only
// within a strict mode environment.
if (meta.strictOnly) {
if (!state.option.strict && !state.isStrict()) {
return false;
}
}
if (token.isProperty) {
return false;
}
}
return true;
}
function supplant(str, data) {
return str.replace(/\{([^{}]*)\}/g, function(a, b) {
var r = data[b];
return typeof r === "string" || typeof r === "number" ? r : a;
});
}
function combine(dest, src) {
Object.keys(src).forEach(function(name) {
if (_.has(JSHINT.blacklist, name)) return;
dest[name] = src[name];
});
}
function processenforceall() {
if (state.option.enforceall) {
for (var enforceopt in options.bool.enforcing) {
if (state.option[enforceopt] === undefined &&
!options.noenforceall[enforceopt]) {
state.option[enforceopt] = true;
}
}
for (var relaxopt in options.bool.relaxing) {
if (state.option[relaxopt] === undefined) {
state.option[relaxopt] = false;
}
}
}
}
function assume() {
processenforceall();
if (!state.option.es3) {
combine(predefined, vars.ecmaIdentifiers[5]);
}
if (state.option.esnext) {
combine(predefined, vars.ecmaIdentifiers[6]);
}
if (state.option.module) {
/**
* TODO: Extend this restriction to *all* "environmental" options.
*/
if (!hasParsedCode(funct)) {
error("E055", state.tokens.next, "module");
}
/**
* TODO: Extend this restriction to *all* ES6-specific options.
*/
if (!state.inESNext()) {
warning("W134", state.tokens.next, "module", 6);
}
}
if (state.option.couch) {
combine(predefined, vars.couch);
}
if (state.option.qunit) {
combine(predefined, vars.qunit);
}
if (state.option.rhino) {
combine(predefined, vars.rhino);
}
if (state.option.shelljs) {
combine(predefined, vars.shelljs);
combine(predefined, vars.node);
}
if (state.option.typed) {
combine(predefined, vars.typed);
}
if (state.option.phantom) {
combine(predefined, vars.phantom);
}
if (state.option.prototypejs) {
combine(predefined, vars.prototypejs);
}
if (state.option.node) {
combine(predefined, vars.node);
combine(predefined, vars.typed);
}
if (state.option.devel) {
combine(predefined, vars.devel);
}
if (state.option.dojo) {
combine(predefined, vars.dojo);
}
if (state.option.browser) {
combine(predefined, vars.browser);
combine(predefined, vars.typed);
}
if (state.option.browserify) {
combine(predefined, vars.browser);
combine(predefined, vars.typed);
combine(predefined, vars.browserify);
}
if (state.option.nonstandard) {
combine(predefined, vars.nonstandard);
}
if (state.option.jasmine) {
combine(predefined, vars.jasmine);
}
if (state.option.jquery) {
combine(predefined, vars.jquery);
}
if (state.option.mootools) {
combine(predefined, vars.mootools);
}
if (state.option.worker) {
combine(predefined, vars.worker);
}
if (state.option.wsh) {
combine(predefined, vars.wsh);
}
if (state.option.globalstrict && state.option.strict !== false) {
state.option.strict = true;
}
if (state.option.yui) {
combine(predefined, vars.yui);
}
if (state.option.mocha) {
combine(predefined, vars.mocha);
}
}
// Produce an error warning.
function quit(code, line, chr) {
var percentage = Math.floor((line / state.lines.length) * 100);
var message = messages.errors[code].desc;
throw {
name: "JSHintError",
line: line,
character: chr,
message: message + " (" + percentage + "% scanned).",
raw: message,
code: code
};
}
function isundef(scope, code, token, a) {
if (!state.ignored[code] && state.option.undef !== false) {
JSHINT.undefs.push([scope, code, token, a]);
}
}
function removeIgnoredMessages() {
var ignored = state.ignoredLines;
if (_.isEmpty(ignored)) return;
JSHINT.errors = _.reject(JSHINT.errors, function(err) { return ignored[err.line] });
}
function warning(code, t, a, b, c, d) {
var ch, l, w, msg;
if (/^W\d{3}$/.test(code)) {
if (state.ignored[code])
return;
msg = messages.warnings[code];
} else if (/E\d{3}/.test(code)) {
msg = messages.errors[code];
} else if (/I\d{3}/.test(code)) {
msg = messages.info[code];
}
t = t || state.tokens.next || {};
if (t.id === "(end)") { // `~
t = state.tokens.curr;
}
l = t.line || 0;
ch = t.from || 0;
w = {
id: "(error)",
raw: msg.desc,
code: msg.code,
evidence: state.lines[l - 1] || "",
line: l,
character: ch,
scope: JSHINT.scope,
a: a,
b: b,
c: c,
d: d
};
w.reason = supplant(msg.desc, w);
JSHINT.errors.push(w);
removeIgnoredMessages();
if (JSHINT.errors.length >= state.option.maxerr)
quit("E043", l, ch);
return w;
}
function warningAt(m, l, ch, a, b, c, d) {
return warning(m, {
line: l,
from: ch
}, a, b, c, d);
}
function error(m, t, a, b, c, d) {
warning(m, t, a, b, c, d);
}
function errorAt(m, l, ch, a, b, c, d) {
return error(m, {
line: l,
from: ch
}, a, b, c, d);
}
// Tracking of "internal" scripts, like eval containing a static string
function addInternalSrc(elem, src) {
var i;
i = {
id: "(internal)",
elem: elem,
value: src
};
JSHINT.internals.push(i);
return i;
}
// adds an indentifier to the relevant current scope and creates warnings/errors as necessary
// name: string
// opts: { type: string, token: token, isblockscoped: bool }
function addlabel(name, opts) {
var type = opts.type;
var token = opts.token;
var isblockscoped = opts.isblockscoped;
// Define label in the current function in the current scope.
if (type === "exception") {
if (_.has(funct["(context)"], name)) {
if (funct[name] !== true && !state.option.node) {
warning("W002", state.tokens.next, name);
}
}
}
if (_.has(funct, name) && !funct["(global)"]) {
if (funct[name] === true) {
if (state.option.latedef) {
if ((state.option.latedef === true && _.contains([funct[name], type], "unction")) ||
!_.contains([funct[name], type], "unction")) {
warning("W003", state.tokens.next, name);
}
}
} else {
if ((!state.option.shadow || _.contains([ "inner", "outer" ], state.option.shadow)) &&
type !== "exception" || funct["(blockscope)"].getlabel(name)) {
warning("W004", state.tokens.next, name);
}
}
}
if (funct["(context)"] && _.has(funct["(context)"], name) && type !== "function") {
if (state.option.shadow === "outer") {
warning("W123", state.tokens.next, name);
}
}
// if the identifier is blockscoped (a let or a const), add it only to the current blockscope
if (isblockscoped) {
funct["(blockscope)"].current.add(name, type, state.tokens.curr);
if (funct["(blockscope)"].atTop() && exported[name]) {
state.tokens.curr.exported = true;
}
} else {
funct["(blockscope)"].shadow(name);
funct[name] = type;
if (token) {
funct["(tokens)"][name] = token;
}
if (funct["(global)"]) {
global[name] = funct;
if (_.has(implied, name)) {
if (state.option.latedef) {
if ((state.option.latedef === true && _.contains([funct[name], type], "unction")) ||
!_.contains([funct[name], type], "unction")) {
warning("W003", state.tokens.next, name);
}
}
delete implied[name];
}
} else {
scope[name] = funct;
}
}
}
function doOption() {
var nt = state.tokens.next;
var body = nt.body.split(",").map(function(s) { return s.trim(); });
var predef = {};
if (nt.type === "globals") {
body.forEach(function(g) {
g = g.split(":");
var key = (g[0] || "").trim();
var val = (g[1] || "").trim();
if (key.charAt(0) === "-") {
key = key.slice(1);
val = false;
JSHINT.blacklist[key] = key;
delete predefined[key];
} else {
predef[key] = (val === "true");
}
});
combine(predefined, predef);
for (var key in predef) {
if (_.has(predef, key)) {
declared[key] = nt;
}
}
}
if (nt.type === "exported") {
body.forEach(function(e) {
exported[e] = true;
});
}
if (nt.type === "members") {
membersOnly = membersOnly || {};
body.forEach(function(m) {
var ch1 = m.charAt(0);
var ch2 = m.charAt(m.length - 1);
if (ch1 === ch2 && (ch1 === "\"" || ch1 === "'")) {
m = m
.substr(1, m.length - 2)
.replace("\\\"", "\"");
}
membersOnly[m] = false;
});
}
var numvals = [
"maxstatements",
"maxparams",
"maxdepth",
"maxcomplexity",
"maxerr",
"maxlen",
"indent"
];
if (nt.type === "jshint" || nt.type === "jslint") {
body.forEach(function(g) {
g = g.split(":");
var key = (g[0] || "").trim();
var val = (g[1] || "").trim();
if (!checkOption(key, nt)) {
return;
}
if (numvals.indexOf(key) >= 0) {
// GH988 - numeric options can be disabled by setting them to `false`
if (val !== "false") {
val = +val;
if (typeof val !== "number" || !isFinite(val) || val <= 0 || Math.floor(val) !== val) {
error("E032", nt, g[1].trim());
return;
}
state.option[key] = val;
} else {
state.option[key] = key === "indent" ? 4 : false;
}
return;
}
if (key === "es5") {
if (val === "true" && state.option.es5) {
warning("I003");
}
}
if (key === "validthis") {
// `validthis` is valid only within a function scope.
if (funct["(global)"])
return void error("E009");
if (val !== "true" && val !== "false")
return void error("E002", nt);
state.option.validthis = (val === "true");
return;
}
if (key === "quotmark") {
switch (val) {
case "true":
case "false":
state.option.quotmark = (val === "true");
break;
case "double":
case "single":
state.option.quotmark = val;
break;
default:
error("E002", nt);
}
return;
}
if (key === "shadow") {
switch (val) {
case "true":
state.option.shadow = true;
break;
case "outer":
state.option.shadow = "outer";
break;
case "false":
case "inner":
state.option.shadow = "inner";
break;
default:
error("E002", nt);
}
return;
}
if (key === "unused") {
switch (val) {
case "true":
state.option.unused = true;
break;
case "false":
state.option.unused = false;
break;
case "vars":
case "strict":
state.option.unused = val;
break;
default:
error("E002", nt);
}
return;
}
if (key === "latedef") {
switch (val) {
case "true":
state.option.latedef = true;
break;
case "false":
state.option.latedef = false;
break;
case "nofunc":
state.option.latedef = "nofunc";
break;
default:
error("E002", nt);
}
return;
}
if (key === "ignore") {
switch (val) {
case "start":
state.ignoreLinterErrors = true;
break;
case "end":
state.ignoreLinterErrors = false;
break;
case "line":
state.ignoredLines[nt.line] = true;
removeIgnoredMessages();
break;
default:
error("E002", nt);
}
return;
}
var match = /^([+-])(W\d{3})$/g.exec(key);
if (match) {
// ignore for -W..., unignore for +W...
state.ignored[match[2]] = (match[1] === "-");
return;
}
var tn;
if (val === "true" || val === "false") {
if (nt.type === "jslint") {
tn = options.renamed[key] || key;
state.option[tn] = (val === "true");
if (options.inverted[tn] !== undefined) {
state.option[tn] = !state.option[tn];
}
} else {
state.option[key] = (val === "true");
}
if (key === "newcap") {
state.option["(explicitNewcap)"] = true;
}
return;
}
error("E002", nt);
});
assume();
}
}
// We need a peek function. If it has an argument, it peeks that much farther
// ahead. It is used to distinguish
// for ( var i in ...
// from
// for ( var i = ...
function peek(p) {
var i = p || 0, j = 0, t;
while (j <= i) {
t = lookahead[j];
if (!t) {
t = lookahead[j] = lex.token();
}
j += 1;
}
// Peeking past the end of the program should produce the "(end)" token.
if (!t && state.tokens.next.id === "(end)") {
return state.tokens.next;
}
return t;
}
function peekIgnoreEOL() {
var i = 0;
var t;
do {
t = peek(i++);
} while (t.id === "(endline)");
return t;
}
// Produce the next token. It looks for programming errors.
function advance(id, t) {
switch (state.tokens.curr.id) {
case "(number)":
if (state.tokens.next.id === ".") {
warning("W005", state.tokens.curr);
}
break;
case "-":
if (state.tokens.next.id === "-" || state.tokens.next.id === "--") {
warning("W006");
}
break;
case "+":
if (state.tokens.next.id === "+" || state.tokens.next.id === "++") {
warning("W007");
}
break;
}
if (id && state.tokens.next.id !== id) {
if (t) {
if (state.tokens.next.id === "(end)") {
error("E019", t, t.id);
} else {
error("E020", state.tokens.next, id, t.id, t.line, state.tokens.next.value);
}
} else if (state.tokens.next.type !== "(identifier)" || state.tokens.next.value !== id) {
warning("W116", state.tokens.next, id, state.tokens.next.value);
}
}
state.tokens.prev = state.tokens.curr;
state.tokens.curr = state.tokens.next;
for (;;) {
state.tokens.next = lookahead.shift() || lex.token();
if (!state.tokens.next) { // No more tokens left, give up
quit("E041", state.tokens.curr.line);
}
if (state.tokens.next.id === "(end)" || state.tokens.next.id === "(error)") {
return;
}
if (state.tokens.next.check) {
state.tokens.next.check();
}
if (state.tokens.next.isSpecial) {
doOption();
} else {
if (state.tokens.next.id !== "(endline)") {
break;
}
}
}
}
function isInfix(token) {
return token.infix || (!token.identifier && !token.template && !!token.led);
}
function isEndOfExpr() {
var curr = state.tokens.curr;
var next = state.tokens.next;
if (next.id === ";" || next.id === "}" || next.id === ":") {
return true;
}
if (isInfix(next) === isInfix(curr) || (curr.id === "yield" && state.inMoz())) {
return curr.line !== startLine(next);
}
return false;
}
function isBeginOfExpr(prev) {
return !prev.left && prev.arity !== "unary";
}
// This is the heart of JSHINT, the Pratt parser. In addition to parsing, it
// is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is
// like .nud except that it is only used on the first token of a statement.
// Having .fud makes it much easier to define statement-oriented languages like
// JavaScript. I retained Pratt's nomenclature.
// .nud Null denotation
// .fud First null denotation
// .led Left denotation
// lbp Left binding power
// rbp Right binding power
// They are elements of the parsing method called Top Down Operator Precedence.
function expression(rbp, initial) {
var left, isArray = false, isObject = false, isLetExpr = false;
state.nameStack.push();
// if current expression is a let expression
if (!initial && state.tokens.next.value === "let" && peek(0).value === "(") {
if (!state.inMoz()) {
warning("W118", state.tokens.next, "let expressions");
}
isLetExpr = true;
// create a new block scope we use only for the current expression
funct["(blockscope)"].stack();
advance("let");
advance("(");
state.tokens.prev.fud();
advance(")");
}
if (state.tokens.next.id === "(end)")
error("E006", state.tokens.curr);
var isDangerous =
state.option.asi &&
state.tokens.prev.line !== startLine(state.tokens.curr) &&
_.contains(["]", ")"], state.tokens.prev.id) &&
_.contains(["[", "("], state.tokens.curr.id);
if (isDangerous)
warning("W014", state.tokens.curr, state.tokens.curr.id);
advance();
if (initial) {
funct["(verb)"] = state.tokens.curr.value;
state.tokens.curr.beginsStmt = true;
}
if (initial === true && state.tokens.curr.fud) {
left = state.tokens.curr.fud();
} else {
if (state.tokens.curr.nud) {
left = state.tokens.curr.nud();
} else {
error("E030", state.tokens.curr, state.tokens.curr.id);
}
// TODO: use pratt mechanics rather than special casing template tokens
while ((rbp < state.tokens.next.lbp || state.tokens.next.type === "(template)") &&
!isEndOfExpr()) {
isArray = state.tokens.curr.value === "Array";
isObject = state.tokens.curr.value === "Object";
// #527, new Foo.Array(), Foo.Array(), new Foo.Object(), Foo.Object()
// Line breaks in IfStatement heads exist to satisfy the checkJSHint
// "Line too long." error.
if (left && (left.value || (left.first && left.first.value))) {
// If the left.value is not "new", or the left.first.value is a "."
// then safely assume that this is not "new Array()" and possibly
// not "new Object()"...
if (left.value !== "new" ||
(left.first && left.first.value && left.first.value === ".")) {
isArray = false;
// ...In the case of Object, if the left.value and state.tokens.curr.value
// are not equal, then safely assume that this not "new Object()"
if (left.value !== state.tokens.curr.value) {
isObject = false;
}
}
}
advance();
if (isArray && state.tokens.curr.id === "(" && state.tokens.next.id === ")") {
warning("W009", state.tokens.curr);
}
if (isObject && state.tokens.curr.id === "(" && state.tokens.next.id === ")") {
warning("W010", state.tokens.curr);
}
if (left && state.tokens.curr.led) {
left = state.tokens.curr.led(left);
} else {
error("E033", state.tokens.curr, state.tokens.curr.id);
}
}
}
if (isLetExpr) {
funct["(blockscope)"].unstack();
}
state.nameStack.pop();
return left;
}
// Functions for conformance of style.
function startLine(token) {
return token.startLine || token.line;
}
function nobreaknonadjacent(left, right) {
left = left || state.tokens.curr;
right = right || state.tokens.next;
if (!state.option.laxbreak && left.line !== startLine(right)) {
warning("W014", right, right.value);
}
}
function nolinebreak(t) {
t = t || state.tokens.curr;
if (t.line !== startLine(state.tokens.next)) {
warning("E022", t, t.value);
}
}
function nobreakcomma(left, right) {
if (left.line !== startLine(right)) {
if (!state.option.laxcomma) {
if (comma.first) {
warning("I001");
comma.first = false;
}
warning("W014", left, right.value);
}
}
}
function comma(opts) {
opts = opts || {};
if (!opts.peek) {
nobreakcomma(state.tokens.curr, state.tokens.next);
advance(",");
} else {
nobreakcomma(state.tokens.prev, state.tokens.curr);
}
if (state.tokens.next.identifier && !(opts.property && state.inES5())) {
// Keywords that cannot follow a comma operator.
switch (state.tokens.next.value) {
case "break":
case "case":
case "catch":
case "continue":
case "default":
case "do":
case "else":
case "finally":
case "for":
case "if":
case "in":
case "instanceof":
case "return":
case "switch":
case "throw":
case "try":
case "var":
case "let":
case "while":
case "with":
error("E024", state.tokens.next, state.tokens.next.value);
return false;
}
}
if (state.tokens.next.type === "(punctuator)") {
switch (state.tokens.next.value) {
case "}":
case "]":
case ",":
if (opts.allowTrailing) {
return true;
}
/* falls through */
case ")":
error("E024", state.tokens.next, state.tokens.next.value);
return false;
}
}
return true;
}
// Functional constructors for making the symbols that will be inherited by
// tokens.
function symbol(s, p) {
var x = state.syntax[s];
if (!x || typeof x !== "object") {
state.syntax[s] = x = {
id: s,
lbp: p,
value: s
};
}
return x;
}
function delim(s) {
var x = symbol(s, 0);
x.delim = true;
return x;
}
function stmt(s, f) {
var x = delim(s);
x.identifier = x.reserved = true;
x.fud = f;
return x;
}
function blockstmt(s, f) {
var x = stmt(s, f);
x.block = true;
return x;
}
function reserveName(x) {
var c = x.id.charAt(0);
if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) {
x.identifier = x.reserved = true;
}
return x;
}
function prefix(s, f) {
var x = symbol(s, 150);
reserveName(x);
x.nud = (typeof f === "function") ? f : function() {
this.arity = "unary";
this.right = expression(150);
if (this.id === "++" || this.id === "--") {
if (state.option.plusplus) {
warning("W016", this, this.id);
} else if (this.right && (!this.right.identifier || isReserved(this.right)) &&
this.right.id !== "." && this.right.id !== "[") {
warning("W017", this);
}
// detect increment/decrement of a const
// in the case of a.b, right will be the "." punctuator
if (this.right && this.right.identifier) {
if (funct["(blockscope)"].labeltype(this.right.value) === "const") {
error("E013", this, this.right.value);
}
}
}
return this;
};
return x;
}
function type(s, f) {
var x = delim(s);
x.type = s;
x.nud = f;
return x;
}
function reserve(name, func) {
var x = type(name, func);
x.identifier = true;
x.reserved = true;
return x;
}
function FutureReservedWord(name, meta) {
var x = type(name, (meta && meta.nud) || function() {
return this;
});
meta = meta || {};
meta.isFutureReservedWord = true;
x.value = name;
x.identifier = true;
x.reserved = true;
x.meta = meta;
return x;
}
function reservevar(s, v) {
return reserve(s, function() {
if (typeof v === "function") {
v(this);
}
return this;
});
}
function infix(s, f, p, w) {
var x = symbol(s, p);
reserveName(x);
x.infix = true;
x.led = function(left) {
if (!w) {
nobreaknonadjacent(state.tokens.prev, state.tokens.curr);
}
if ((s === "in" || s === "instanceof") && left.id === "!") {
warning("W018", left, "!");
}
if (typeof f === "function") {
return f(left, this);
} else {
this.left = left;
this.right = expression(p);
return this;
}
};
return x;
}
function application(s) {
var x = symbol(s, 42);
x.led = function(left) {
nobreaknonadjacent(state.tokens.prev, state.tokens.curr);
this.left = left;
this.right = doFunction({ type: "arrow", loneArg: left });
return this;
};
return x;
}
function relation(s, f) {
var x = symbol(s, 100);
x.led = function(left) {
nobreaknonadjacent(state.tokens.prev, state.tokens.curr);
this.left = left;
var right = this.right = expression(100);
if (isIdentifier(left, "NaN") || isIdentifier(right, "NaN")) {
warning("W019", this);
} else if (f) {
f.apply(this, [left, right]);
}
if (!left || !right) {
quit("E041", state.tokens.curr.line);
}
if (left.id === "!") {
warning("W018", left, "!");
}
if (right.id === "!") {
warning("W018", right, "!");
}
return this;
};
return x;
}
function isPoorRelation(node) {
return node &&
((node.type === "(number)" && +node.value === 0) ||
(node.type === "(string)" && node.value === "") ||
(node.type === "null" && !state.option.eqnull) ||
node.type === "true" ||
node.type === "false" ||
node.type === "undefined");
}
var typeofValues = {};
typeofValues.legacy = [
// E4X extended the `typeof` operator to return "xml" for the XML and
// XMLList types it introduced.
// Ref: 11.3.2 The typeof Operator
// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf
"xml",
// IE<9 reports "unknown" when the `typeof` operator is applied to an
// object existing across a COM+ bridge. In lieu of official documentation
// (which does not exist), see:
// http://robertnyman.com/2005/12/21/what-is-typeof-unknown/
"unknown"
];
typeofValues.es3 = [
"undefined", "boolean", "number", "string", "function", "object",
];
typeofValues.es3 = typeofValues.es3.concat(typeofValues.legacy);
typeofValues.es6 = typeofValues.es3.concat("symbol");
// Checks whether the 'typeof' operator is used with the correct
// value. For docs on 'typeof' see:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
function isTypoTypeof(left, right, state) {
var values;
if (state.option.notypeof)
return false;
if (!left || !right)
return false;
values = state.inESNext() ? typeofValues.es6 : typeofValues.es3;
if (right.type === "(identifier)" && right.value === "typeof" && left.type === "(string)")
return !_.contains(values, left.value);
return false;
}
function isGlobalEval(left, state, funct) {
var isGlobal = false;
// permit methods to refer to an "eval" key in their own context
if (left.type === "this" && funct["(context)"] === null) {
isGlobal = true;
}
// permit use of "eval" members of objects
else if (left.type === "(identifier)") {
if (state.option.node && left.value === "global") {
isGlobal = true;
}
else if (state.option.browser && (left.value === "window" || left.value === "document")) {
isGlobal = true;
}
}
return isGlobal;
}
function findNativePrototype(left) {
var natives = [
"Array", "ArrayBuffer", "Boolean", "Collator", "DataView", "Date",
"DateTimeFormat", "Error", "EvalError", "Float32Array", "Float64Array",
"Function", "Infinity", "Intl", "Int16Array", "Int32Array", "Int8Array",
"Iterator", "Number", "NumberFormat", "Object", "RangeError",
"ReferenceError", "RegExp", "StopIteration", "String", "SyntaxError",
"TypeError", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray",
"URIError"
];
function walkPrototype(obj) {
if (typeof obj !== "object") return;
return obj.right === "prototype" ? obj : walkPrototype(obj.left);
}
function walkNative(obj) {
while (!obj.identifier && typeof obj.left === "object")
obj = obj.left;
if (obj.identifier && natives.indexOf(obj.value) >= 0)
return obj.value;
}
var prototype = walkPrototype(left);
if (prototype) return walkNative(prototype);
}
function assignop(s, f, p) {
var x = infix(s, typeof f === "function" ? f : function(left, that) {
that.left = left;
if (left) {
if (state.option.freeze) {
var nativeObject = findNativePrototype(left);
if (nativeObject)
warning("W121", left, nativeObject);
}
if (predefined[left.value] === false &&
scope[left.value]["(global)"] === true) {
warning("W020", left);
} else if (left["function"]) {
warning("W021", left, left.value);
}
if (funct["(blockscope)"].labeltype(left.value) === "const") {
error("E013", left, left.value);
}
if (left.id === ".") {
if (!left.left) {
warning("E031", that);
} else if (left.left.value === "arguments" && !state.isStrict()) {
warning("E031", that);
}
state.nameStack.set(state.tokens.prev);
that.right = expression(10);
return that;
} else if (left.id === "[") {
if (state.tokens.curr.left.first) {
state.tokens.curr.left.first.forEach(function(t) {
if (t && funct[t.value] === "const") {
error("E013", t, t.value);
}
});
} else if (!left.left) {
warning("E031", that);
} else if (left.left.value === "arguments" && !state.isStrict()) {
warning("E031", that);
}
state.nameStack.set(left.right);
that.right = expression(10);
return that;
} else if (left.identifier && !isReserved(left)) {
if (funct[left.value] === "exception") {
warning("W022", left);
}
state.nameStack.set(left);
that.right = expression(10);
return that;
}
if (left === state.syntax["function"]) {
warning("W023", state.tokens.curr);
}
}
error("E031", that);
}, p);
x.exps = true;
x.assign = true;
return x;
}
function bitwise(s, f, p) {
var x = symbol(s, p);
reserveName(x);
x.led = (typeof f === "function") ? f : function(left) {
if (state.option.bitwise) {
warning("W016", this, this.id);
}
this.left = left;
this.right = expression(p);
return this;
};
return x;
}
function bitwiseassignop(s) {
return assignop(s, function(left, that) {
if (state.option.bitwise) {
warning("W016", that, that.id);
}
if (left) {
if (left.id === "." || left.id === "[" ||
(left.identifier && !isReserved(left))) {
expression(10);
return that;
}
if (left === state.syntax["function"]) {
warning("W023", state.tokens.curr);
}
return that;
}
error("E031", that);
}, 20);
}
function suffix(s) {
var x = symbol(s, 150);
x.led = function(left) {
// this = suffix e.g. "++" punctuator
// left = symbol operated e.g. "a" identifier or "a.b" punctuator
if (state.option.plusplus) {
warning("W016", this, this.id);
} else if ((!left.identifier || isReserved(left)) && left.id !== "." && left.id !== "[") {
warning("W017", this);
}
// detect increment/decrement of a const
// in the case of a.b, left will be the "." punctuator
if (left && left.identifier) {
if (funct["(blockscope)"].labeltype(left.value) === "const") {
error("E013", this, left.value);
}
}
this.left = left;
return this;
};
return x;
}
// fnparam means that this identifier is being defined as a function
// argument (see identifier())
// prop means that this identifier is that of an object property
function optionalidentifier(fnparam, prop, preserve) {
if (!state.tokens.next.identifier) {
return;
}
if (!preserve) {
advance();
}
var curr = state.tokens.curr;
var val = state.tokens.curr.value;
if (!isReserved(curr)) {
return val;
}
if (prop) {
if (state.inES5()) {
return val;
}
}
if (fnparam && val === "undefined") {
return val;
}
warning("W024", state.tokens.curr, state.tokens.curr.id);
return val;
}
// fnparam means that this identifier is being defined as a function
// argument
// prop means that this identifier is that of an object property
function identifier(fnparam, prop) {
var i = optionalidentifier(fnparam, prop, false);
if (i) {
return i;
}
// parameter destructuring with rest operator
if (state.tokens.next.value === "...") {
if (!state.option.esnext) {
warning("W119", state.tokens.next, "spread/rest operator");
}
advance();
if (checkPunctuators(state.tokens.next, ["..."])) {
warning("E024", state.tokens.next, "...");
while (checkPunctuators(state.tokens.next, ["..."])) {
advance();
}
}
if (!state.tokens.next.identifier) {
warning("E024", state.tokens.curr, "...");
return;
}
return identifier(fnparam, prop);
} else {
error("E030", state.tokens.next, state.tokens.next.value);
// The token should be consumed after a warning is issued so the parser
// can continue as though an identifier were found. The semicolon token
// should not be consumed in this way so that the parser interprets it as
// a statement delimeter;
if (state.tokens.next.id !== ";") {
advance();
}
}
}
function reachable(controlToken) {
var i = 0, t;
if (state.tokens.next.id !== ";" || controlToken.inBracelessBlock) {
return;
}
for (;;) {
do {
t = peek(i);
i += 1;
} while (t.id !== "(end)" && t.id === "(comment)");
if (t.reach) {
return;
}
if (t.id !== "(endline)") {
if (t.id === "function") {
if (state.option.latedef === true) {
warning("W026", t);
}
break;
}
warning("W027", t, t.value, controlToken.value);
break;
}
}
}
function parseFinalSemicolon() {
if (state.tokens.next.id !== ";") {
// don't complain about unclosed templates / strings
if (state.tokens.next.isUnclosed) return advance();
if (!state.option.asi) {
// If this is the last statement in a block that ends on
// the same line *and* option lastsemic is on, ignore the warning.
// Otherwise, complain about missing semicolon.
if (!state.option.lastsemic || state.tokens.next.id !== "}" ||
startLine(state.tokens.next) !== state.tokens.curr.line) {
warningAt("W033", state.tokens.curr.line, state.tokens.curr.character);
}
}
} else {
advance(";");
}
}
function statement() {
var i = indent, r, s = scope, t = state.tokens.next;
if (t.id === ";") {
advance(";");
return;
}
// Is this a labelled statement?
var res = isReserved(t);
// We're being more tolerant here: if someone uses
// a FutureReservedWord as a label, we warn but proceed
// anyway.
if (res && t.meta && t.meta.isFutureReservedWord && peek().id === ":") {
warning("W024", t, t.id);
res = false;
}
// detect a module import declaration
if (t.value === "module" && t.type === "(identifier)") {
if (peek().type === "(identifier)") {
if (!state.inESNext()) {
warning("W119", state.tokens.curr, "module");
}
advance("module");
var name = identifier();
addlabel(name, { type: "unused", token: state.tokens.curr });
advance("from");
advance("(string)");
parseFinalSemicolon();
return;
}
}
if (t.identifier && !res && peek().id === ":") {
advance();
advance(":");
scope = Object.create(s);
addlabel(t.value, { type: "label" });
if (!state.tokens.next.labelled && state.tokens.next.value !== "{") {
warning("W028", state.tokens.next, t.value, state.tokens.next.value);
}
state.tokens.next.label = t.value;
t = state.tokens.next;
}
// Is it a lonely block?
if (t.id === "{") {
// Is it a switch case block?
//
// switch (foo) {
// case bar: { <= here.
// ...
// }
// }
var iscase = (funct["(verb)"] === "case" && state.tokens.curr.value === ":");
block(true, true, false, false, iscase);
return;
}
// Parse the statement.
r = expression(0, true);
if (r && (!r.identifier || r.value !== "function") && (r.type !== "(punctuator)")) {
if (!state.isStrict() &&
state.option.globalstrict &&
state.option.strict) {
warning("E007");
}
}
// Look for the final semicolon.
if (!t.block) {
if (!state.option.expr && (!r || !r.exps)) {
warning("W030", state.tokens.curr);
} else if (state.option.nonew && r && r.left && r.id === "(" && r.left.id === "new") {
warning("W031", t);
}
parseFinalSemicolon();
}
// Restore the indentation.
indent = i;
scope = s;
return r;
}
function statements() {
var a = [], p;
while (!state.tokens.next.reach && state.tokens.next.id !== "(end)") {
if (state.tokens.next.id === ";") {
p = peek();
if (!p || (p.id !== "(" && p.id !== "[")) {
warning("W032");
}
advance(";");
} else {
a.push(statement());
}
}
return a;
}
/*
* read all directives
* recognizes a simple form of asi, but always
* warns, if it is used
*/
function directives() {
var i, p, pn;
while (state.tokens.next.id === "(string)") {
p = peek(0);
if (p.id === "(endline)") {
i = 1;
do {
pn = peek(i++);
} while (pn.id === "(endline)");
if (pn.id === ";") {
p = pn;
} else if (pn.value === "[" || pn.value === ".") {
// string -> [ | . is a valid production
return;
} else if (!state.option.asi || pn.value === "(") {
// string -> ( is not a valid production
warning("W033", state.tokens.next);
}
} else if (p.id === "." || p.id === "[") {
return;
} else if (p.id !== ";") {
warning("W033", p);
}
advance();
if (state.directive[state.tokens.curr.value]) {
warning("W034", state.tokens.curr, state.tokens.curr.value);
}
if (state.tokens.curr.value === "use strict") {
if (!state.option["(explicitNewcap)"]) {
state.option.newcap = true;
}
state.option.undef = true;
}
// there's no directive negation, so always set to true
state.directive[state.tokens.curr.value] = true;
if (p.id === ";") {
advance(";");
}
}
}
/*
* Parses a single block. A block is a sequence of statements wrapped in
* braces.
*
* ordinary - true for everything but function bodies and try blocks.
* stmt - true if block can be a single statement (e.g. in if/for/while).
* isfunc - true if block is a function body
* isfatarrow - true if its a body of a fat arrow function
* iscase - true if block is a switch case block
*/
function block(ordinary, stmt, isfunc, isfatarrow, iscase) {
var a,
b = inblock,
old_indent = indent,
m,
s = scope,
t,
line,
d;
inblock = ordinary;
if (!ordinary || !state.option.funcscope)
scope = Object.create(scope);
t = state.tokens.next;
var metrics = funct["(metrics)"];
metrics.nestedBlockDepth += 1;
metrics.verifyMaxNestedBlockDepthPerFunction();
if (state.tokens.next.id === "{") {
advance("{");
// create a new block scope
funct["(blockscope)"].stack();
line = state.tokens.curr.line;
if (state.tokens.next.id !== "}") {
indent += state.option.indent;
while (!ordinary && state.tokens.next.from > indent) {
indent += state.option.indent;
}
if (isfunc) {
m = {};
for (d in state.directive) {
if (_.has(state.directive, d)) {
m[d] = state.directive[d];
}
}
directives();
if (state.option.strict && funct["(context)"]["(global)"]) {
if (!m["use strict"] && !state.isStrict()) {
warning("E007");
}
}
}
a = statements();
metrics.statementCount += a.length;
if (isfunc) {
state.directive = m;
}
indent -= state.option.indent;
}
advance("}", t);
funct["(blockscope)"].unstack();
indent = old_indent;
} else if (!ordinary) {
if (isfunc) {
m = {};
if (stmt && !isfatarrow && !state.inMoz()) {
error("W118", state.tokens.curr, "function closure expressions");
}
if (!stmt) {
for (d in state.directive) {
if (_.has(state.directive, d)) {
m[d] = state.directive[d];
}
}
}
expression(10);
if (state.option.strict && funct["(context)"]["(global)"]) {
if (!m["use strict"] && !state.isStrict()) {
warning("E007");
}
}
} else {
error("E021", state.tokens.next, "{", state.tokens.next.value);
}
} else {
// check to avoid let declaration not within a block
funct["(noblockscopedvar)"] = true;
if (!stmt || state.option.curly) {
warning("W116", state.tokens.next, "{", state.tokens.next.value);
}
state.tokens.next.inBracelessBlock = true;
indent += state.option.indent;
// test indentation only if statement is in new line
a = [statement()];
indent -= state.option.indent;
delete funct["(noblockscopedvar)"];
}
// Don't clear and let it propagate out if it is "break", "return" or similar in switch case
switch (funct["(verb)"]) {
case "break":
case "continue":
case "return":
case "throw":
if (iscase) {
break;
}
/* falls through */
default:
funct["(verb)"] = null;
}
if (!ordinary || !state.option.funcscope) scope = s;
inblock = b;
if (ordinary && state.option.noempty && (!a || a.length === 0)) {
warning("W035", state.tokens.prev);
}
metrics.nestedBlockDepth -= 1;
return a;
}
function countMember(m) {
if (membersOnly && typeof membersOnly[m] !== "boolean") {
warning("W036", state.tokens.curr, m);
}
if (typeof member[m] === "number") {
member[m] += 1;
} else {
member[m] = 1;
}
}
function note_implied(tkn) {
var name = tkn.value;
var desc = Object.getOwnPropertyDescriptor(implied, name);
if (!desc)
implied[name] = [tkn.line];
else
desc.value.push(tkn.line);
}
// Build the syntax table by declaring the syntactic elements of the language.
type("(number)", function() {
return this;
});
type("(string)", function() {
return this;
});
state.syntax["(identifier)"] = {
type: "(identifier)",
lbp: 0,
identifier: true,
nud: function() {
var v = this.value;
// s will be either the function object 'funct' that the identifier points at
// or it will be a boolean if it is a predefined variable
var s = scope[v];
var f;
var block;
// If this identifier is the lone parameter to a shorthand "fat arrow"
// function definition, i.e.
//
// x => x;
//
// ...it should not be considered as a variable in the current scope. It
// will be added to the scope of the new function when the next token is
// parsed, so it can be safely ignored for now.
if (state.tokens.next.id === "=>") {
return this;
}
block = funct["(blockscope)"].getlabel(v);
if (typeof s === "function") {
// Protection against accidental inheritance.
s = undefined;
} else if (!block && typeof s === "boolean") {
f = funct;
funct = functions[0];
addlabel(v, { type: "var" });
s = funct;
funct = f;
}
// The name is in scope and defined in the current function or it exists in the blockscope.
if (funct === s || block) {
// Change 'unused' to 'var', and reject labels.
// the name is in a block scope.
switch (block ? block[v]["(type)"] : funct[v]) {
case "unused":
if (block) block[v]["(type)"] = "var";
else funct[v] = "var";
break;
case "unction":
if (block) block[v]["(type)"] = "function";
else funct[v] = "function";
this["function"] = true;
break;
case "const":
// consts can only exist inside block
// because they are never added to the scope, s
block[v]["(unused)"] = false;
break;
case "function":
this["function"] = true;
break;
case "label":
warning("W037", state.tokens.curr, v);
break;
}
} else {
// If the name is already defined in the current
// function, but not as outer, then there is a scope error.
switch (funct[v]) {
case "closure":
case "function":
case "var":
case "unused":
warning("W038", state.tokens.curr, v);
break;
case "label":
warning("W037", state.tokens.curr, v);
break;
case "outer":
case "global":
break;
default:
// If the name is defined in an outer function, make an outer entry,
// and if it was unused, make it var.
if (s === true) {
funct[v] = true;
} else if (s === null) {
warning("W039", state.tokens.curr, v);
note_implied(state.tokens.curr);
} else if (typeof s !== "object") {
// if we're in a list comprehension, variables are declared
// locally and used before being defined. So we check
// the presence of the given variable in the comp array
// before declaring it undefined.
if (!funct["(comparray)"].check(v)) {
isundef(funct, "W117", state.tokens.curr, v);
}
// Explicitly mark the variable as used within function scopes
if (!funct["(global)"]) {
funct[v] = true;
}
note_implied(state.tokens.curr);
} else {
switch (s[v]) {
case "function":
case "unction":
this["function"] = true;
s[v] = "closure";
funct[v] = s["(global)"] ? "global" : "outer";
break;
case "var":
case "unused":
s[v] = "closure";
funct[v] = s["(global)"] ? "global" : "outer";
break;
case "closure":
funct[v] = s["(global)"] ? "global" : "outer";
break;
case "label":
warning("W037", state.tokens.curr, v);
}
}
}
}
return this;
},
led: function() {
error("E033", state.tokens.next, state.tokens.next.value);
}
};
var baseTemplateSyntax = {
lbp: 0,
identifier: false,
template: true,
};
state.syntax["(template)"] = _.extend({
type: "(template)",
nud: doTemplateLiteral,
led: doTemplateLiteral,
noSubst: false
}, baseTemplateSyntax);
state.syntax["(template middle)"] = _.extend({
type: "(template middle)",
middle: true,
noSubst: false
}, baseTemplateSyntax);
state.syntax["(template tail)"] = _.extend({
type: "(template tail)",
tail: true,
noSubst: false
}, baseTemplateSyntax);
state.syntax["(no subst template)"] = _.extend({
type: "(template)",
nud: doTemplateLiteral,
led: doTemplateLiteral,
noSubst: true,
tail: true // mark as tail, since it's always the last component
}, baseTemplateSyntax);
type("(regexp)", function() {
return this;
});
// ECMAScript parser
delim("(endline)");
delim("(begin)");
delim("(end)").reach = true;
delim("(error)").reach = true;
delim("}").reach = true;
delim(")");
delim("]");
delim("\"").reach = true;
delim("'").reach = true;
delim(";");
delim(":").reach = true;
delim("#");
reserve("else");
reserve("case").reach = true;
reserve("catch");
reserve("default").reach = true;
reserve("finally");
reservevar("arguments", function(x) {
if (state.isStrict() && funct["(global)"]) {
warning("E008", x);
}
});
reservevar("eval");
reservevar("false");
reservevar("Infinity");
reservevar("null");
reservevar("this", function(x) {
if (state.isStrict() && !isMethod() &&
!state.option.validthis && ((funct["(statement)"] &&
funct["(name)"].charAt(0) > "Z") || funct["(global)"])) {
warning("W040", x);
}
});
reservevar("true");
reservevar("undefined");
assignop("=", "assign", 20);
assignop("+=", "assignadd", 20);
assignop("-=", "assignsub", 20);
assignop("*=", "assignmult", 20);
assignop("/=", "assigndiv", 20).nud = function() {
error("E014");
};
assignop("%=", "assignmod", 20);
bitwiseassignop("&=");
bitwiseassignop("|=");
bitwiseassignop("^=");
bitwiseassignop("<<=");
bitwiseassignop(">>=");
bitwiseassignop(">>>=");
infix(",", function(left, that) {
var expr;
that.exprs = [left];
if (state.option.nocomma) {
warning("W127");
}
if (!comma({ peek: true })) {
return that;
}
while (true) {
if (!(expr = expression(10))) {
break;
}
that.exprs.push(expr);
if (state.tokens.next.value !== "," || !comma()) {
break;
}
}
return that;
}, 10, true);
infix("?", function(left, that) {
increaseComplexityCount();
that.left = left;
that.right = expression(10);
advance(":");
that["else"] = expression(10);
return that;
}, 30);
var orPrecendence = 40;
infix("||", function(left, that) {
increaseComplexityCount();
that.left = left;
that.right = expression(orPrecendence);
return that;
}, orPrecendence);
infix("&&", "and", 50);
bitwise("|", "bitor", 70);
bitwise("^", "bitxor", 80);
bitwise("&", "bitand", 90);
relation("==", function(left, right) {
var eqnull = state.option.eqnull && (left.value === "null" || right.value === "null");
switch (true) {
case !eqnull && state.option.eqeqeq:
this.from = this.character;
warning("W116", this, "===", "==");
break;
case isPoorRelation(left):
warning("W041", this, "===", left.value);
break;
case isPoorRelation(right):
warning("W041", this, "===", right.value);
break;
case isTypoTypeof(right, left, state):
warning("W122", this, right.value);
break;
case isTypoTypeof(left, right, state):
warning("W122", this, left.value);
break;
}
return this;
});
relation("===", function(left, right) {
if (isTypoTypeof(right, left, state)) {
warning("W122", this, right.value);
} else if (isTypoTypeof(left, right, state)) {
warning("W122", this, left.value);
}
return this;
});
relation("!=", function(left, right) {
var eqnull = state.option.eqnull &&
(left.value === "null" || right.value === "null");
if (!eqnull && state.option.eqeqeq) {
this.from = this.character;
warning("W116", this, "!==", "!=");
} else if (isPoorRelation(left)) {
warning("W041", this, "!==", left.value);
} else if (isPoorRelation(right)) {
warning("W041", this, "!==", right.value);
} else if (isTypoTypeof(right, left, state)) {
warning("W122", this, right.value);
} else if (isTypoTypeof(left, right, state)) {
warning("W122", this, left.value);
}
return this;
});
relation("!==", function(left, right) {
if (isTypoTypeof(right, left, state)) {
warning("W122", this, right.value);
} else if (isTypoTypeof(left, right, state)) {
warning("W122", this, left.value);
}
return this;
});
relation("<");
relation(">");
relation("<=");
relation(">=");
bitwise("<<", "shiftleft", 120);
bitwise(">>", "shiftright", 120);
bitwise(">>>", "shiftrightunsigned", 120);
infix("in", "in", 120);
infix("instanceof", "instanceof", 120);
infix("+", function(left, that) {
var right;
that.left = left;
that.right = right = expression(130);
if (left && right && left.id === "(string)" && right.id === "(string)") {
left.value += right.value;
left.character = right.character;
if (!state.option.scripturl && reg.javascriptURL.test(left.value)) {
warning("W050", left);
}
return left;
}
return that;
}, 130);
prefix("+", "num");
prefix("+++", function() {
warning("W007");
this.arity = "unary";
this.right = expression(150);
return this;
});
infix("+++", function(left) {
warning("W007");
this.left = left;
this.right = expression(130);
return this;
}, 130);
infix("-", "sub", 130);
prefix("-", "neg");
prefix("---", function() {
warning("W006");
this.arity = "unary";
this.right = expression(150);
return this;
});
infix("---", function(left) {
warning("W006");
this.left = left;
this.right = expression(130);
return this;
}, 130);
infix("*", "mult", 140);
infix("/", "div", 140);
infix("%", "mod", 140);
suffix("++");
prefix("++", "preinc");
state.syntax["++"].exps = true;
suffix("--");
prefix("--", "predec");
state.syntax["--"].exps = true;
prefix("delete", function() {
var p = expression(10);
if (!p) {
return this;
}
if (p.id !== "." && p.id !== "[") {
warning("W051");
}
this.first = p;
// The `delete` operator accepts unresolvable references when not in strict
// mode, so the operand may be undefined.
if (p.identifier && !state.isStrict()) {
p.forgiveUndef = true;
}
return this;
}).exps = true;
prefix("~", function() {
if (state.option.bitwise) {
warning("W016", this, "~");
}
this.arity = "unary";
expression(150);
return this;
});
prefix("...", function() {
if (!state.option.esnext) {
warning("W119", this, "spread/rest operator");
}
// TODO: Allow all AssignmentExpression
// once parsing permits.
//
// How to handle eg. number, boolean when the built-in
// prototype of may have an @@iterator definition?
//
// Number.prototype[Symbol.iterator] = function * () {
// yield this.valueOf();
// };
//
// var a = [ ...1 ];
// console.log(a); // [1];
//
// for (let n of [...10]) {
// console.log(n);
// }
// // 10
//
//
// Boolean.prototype[Symbol.iterator] = function * () {
// yield this.valueOf();
// };
//
// var a = [ ...true ];
// console.log(a); // [true];
//
// for (let n of [...false]) {
// console.log(n);
// }
// // false
//
if (!state.tokens.next.identifier &&
state.tokens.next.type !== "(string)" &&
!checkPunctuators(state.tokens.next, ["[", "("])) {
error("E030", state.tokens.next, state.tokens.next.value);
}
expression(150);
return this;
});
prefix("!", function() {
this.arity = "unary";
this.right = expression(150);
if (!this.right) { // '!' followed by nothing? Give up.
quit("E041", this.line || 0);
}
if (bang[this.right.id] === true) {
warning("W018", this, "!");
}
return this;
});
prefix("typeof", (function() {
var p = expression(150);
this.first = p;
// The `typeof` operator accepts unresolvable references, so the operand
// may be undefined.
if (p.identifier) {
p.forgiveUndef = true;
}
return this;
}));
prefix("new", function() {
var c = expression(155), i;
if (c && c.id !== "function") {
if (c.identifier) {
c["new"] = true;
switch (c.value) {
case "Number":
case "String":
case "Boolean":
case "Math":
case "JSON":
warning("W053", state.tokens.prev, c.value);
break;
case "Symbol":
if (state.option.esnext) {
warning("W053", state.tokens.prev, c.value);
}
break;
case "Function":
if (!state.option.evil) {
warning("W054");
}
break;
case "Date":
case "RegExp":
case "this":
break;
default:
if (c.id !== "function") {
i = c.value.substr(0, 1);
if (state.option.newcap && (i < "A" || i > "Z") && !_.has(global, c.value)) {
warning("W055", state.tokens.curr);
}
}
}
} else {
if (c.id !== "." && c.id !== "[" && c.id !== "(") {
warning("W056", state.tokens.curr);
}
}
} else {
if (!state.option.supernew)
warning("W057", this);
}
if (state.tokens.next.id !== "(" && !state.option.supernew) {
warning("W058", state.tokens.curr, state.tokens.curr.value);
}
this.first = c;
return this;
});
state.syntax["new"].exps = true;
prefix("void").exps = true;
infix(".", function(left, that) {
var m = identifier(false, true);
if (typeof m === "string") {
countMember(m);
}
that.left = left;
that.right = m;
if (m && m === "hasOwnProperty" && state.tokens.next.value === "=") {
warning("W001");
}
if (left && left.value === "arguments" && (m === "callee" || m === "caller")) {
if (state.option.noarg)
warning("W059", left, m);
else if (state.isStrict())
error("E008");
} else if (!state.option.evil && left && left.value === "document" &&
(m === "write" || m === "writeln")) {
warning("W060", left);
}
if (!state.option.evil && (m === "eval" || m === "execScript")) {
if (isGlobalEval(left, state, funct)) {
warning("W061");
}
}
return that;
}, 160, true);
infix("(", function(left, that) {
if (state.option.immed && left && !left.immed && left.id === "function") {
warning("W062");
}
var n = 0;
var p = [];
if (left) {
if (left.type === "(identifier)") {
if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) {
if ("Number String Boolean Date Object Error Symbol".indexOf(left.value) === -1) {
if (left.value === "Math") {
warning("W063", left);
} else if (state.option.newcap) {
warning("W064", left);
}
}
}
}
}
if (state.tokens.next.id !== ")") {
for (;;) {
p[p.length] = expression(10);
n += 1;
if (state.tokens.next.id !== ",") {
break;
}
comma();
}
}
advance(")");
if (typeof left === "object") {
if (state.inES3() && left.value === "parseInt" && n === 1) {
warning("W065", state.tokens.curr);
}
if (!state.option.evil) {
if (left.value === "eval" || left.value === "Function" ||
left.value === "execScript") {
warning("W061", left);
if (p[0] && [0].id === "(string)") {
addInternalSrc(left, p[0].value);
}
} else if (p[0] && p[0].id === "(string)" &&
(left.value === "setTimeout" ||
left.value === "setInterval")) {
warning("W066", left);
addInternalSrc(left, p[0].value);
// window.setTimeout/setInterval
} else if (p[0] && p[0].id === "(string)" &&
left.value === "." &&
left.left.value === "window" &&
(left.right === "setTimeout" ||
left.right === "setInterval")) {
warning("W066", left);
addInternalSrc(left, p[0].value);
}
}
if (!left.identifier && left.id !== "." && left.id !== "[" &&
left.id !== "(" && left.id !== "&&" && left.id !== "||" &&
left.id !== "?" && !(state.option.esnext && left["(name)"])) {
warning("W067", that);
}
}
that.left = left;
return that;
}, 155, true).exps = true;
prefix("(", function() {
var pn = state.tokens.next, pn1, i = -1;
var ret, triggerFnExpr, first, last;
var parens = 1;
var opening = state.tokens.curr;
var preceeding = state.tokens.prev;
var isNecessary = !state.option.singleGroups;
do {
if (pn.value === "(") {
parens += 1;
} else if (pn.value === ")") {
parens -= 1;
}
i += 1;
pn1 = pn;
pn = peek(i);
} while (!(parens === 0 && pn1.value === ")") && pn.value !== ";" && pn.type !== "(end)");
if (state.tokens.next.id === "function") {
triggerFnExpr = state.tokens.next.immed = true;
}
// If the balanced grouping operator is followed by a "fat arrow", the
// current token marks the beginning of a "fat arrow" function and parsing
// should proceed accordingly.
if (pn.value === "=>") {
return doFunction({ type: "arrow", parsedOpening: true });
}
var exprs = [];
if (state.tokens.next.id !== ")") {
for (;;) {
exprs.push(expression(10));
if (state.tokens.next.id !== ",") {
break;
}
if (state.option.nocomma) {
warning("W127");
}
comma();
}
}
advance(")", this);
if (state.option.immed && exprs[0] && exprs[0].id === "function") {
if (state.tokens.next.id !== "(" &&
state.tokens.next.id !== "." && state.tokens.next.id !== "[") {
warning("W068", this);
}
}
if (!exprs.length) {
return;
}
if (exprs.length > 1) {
ret = Object.create(state.syntax[","]);
ret.exprs = exprs;
first = exprs[0];
last = exprs[exprs.length - 1];
if (!isNecessary) {
isNecessary = preceeding.assign || preceeding.delim;
}
} else {
ret = first = last = exprs[0];
if (!isNecessary) {
isNecessary =
// Used to distinguish from an ExpressionStatement which may not
// begin with the `{` and `function` tokens
(opening.beginsStmt && (ret.id === "{" || triggerFnExpr || isFunctor(ret))) ||
// Used to signal that a function expression is being supplied to
// some other operator.
(triggerFnExpr &&
// For parenthesis wrapping a function expression to be considered
// necessary, the grouping operator should be the left-hand-side of
// some other operator--either within the parenthesis or directly
// following them.
(!isEndOfExpr() || state.tokens.prev.id !== "}")) ||
// Used to demarcate an arrow function as the left-hand side of some
// operator.
(isFunctor(ret) && !isEndOfExpr()) ||
// Used as the return value of a single-statement arrow function
(ret.id === "{" && preceeding.id === "=>");
}
}
if (ret) {
// The operator may be necessary to override the default binding power of
// neighboring operators (whenever there is an operator in use within the
// first expression *or* the current group contains multiple expressions)
if (!isNecessary && (first.left || ret.exprs)) {
isNecessary =
(!isBeginOfExpr(preceeding) && first.lbp <= preceeding.lbp) ||
(!isEndOfExpr() && last.lbp < state.tokens.next.lbp);
}
if (!isNecessary) {
warning("W126", opening);
}
ret.paren = true;
}
return ret;
});
application("=>");
infix("[", function(left, that) {
var e = expression(10), s;
if (e && e.type === "(string)") {
if (!state.option.evil && (e.value === "eval" || e.value === "execScript")) {
if (isGlobalEval(left, state, funct)) {
warning("W061");
}
}
countMember(e.value);
if (!state.option.sub && reg.identifier.test(e.value)) {
s = state.syntax[e.value];
if (!s || !isReserved(s)) {
warning("W069", state.tokens.prev, e.value);
}
}
}
advance("]", that);
if (e && e.value === "hasOwnProperty" && state.tokens.next.value === "=") {
warning("W001");
}
that.left = left;
that.right = e;
return that;
}, 160, true);
function comprehensiveArrayExpression() {
var res = {};
res.exps = true;
funct["(comparray)"].stack();
// Handle reversed for expressions, used in spidermonkey
var reversed = false;
if (state.tokens.next.value !== "for") {
reversed = true;
if (!state.inMoz()) {
warning("W116", state.tokens.next, "for", state.tokens.next.value);
}
funct["(comparray)"].setState("use");
res.right = expression(10);
}
advance("for");
if (state.tokens.next.value === "each") {
advance("each");
if (!state.inMoz()) {
warning("W118", state.tokens.curr, "for each");
}
}
advance("(");
funct["(comparray)"].setState("define");
res.left = expression(130);
if (_.contains(["in", "of"], state.tokens.next.value)) {
advance();
} else {
error("E045", state.tokens.curr);
}
funct["(comparray)"].setState("generate");
expression(10);
advance(")");
if (state.tokens.next.value === "if") {
advance("if");
advance("(");
funct["(comparray)"].setState("filter");
res.filter = expression(10);
advance(")");
}
if (!reversed) {
funct["(comparray)"].setState("use");
res.right = expression(10);
}
advance("]");
funct["(comparray)"].unstack();
return res;
}
prefix("[", function() {
var blocktype = lookupBlockType();
if (blocktype.isCompArray) {
if (!state.inESNext()) {
warning("W119", state.tokens.curr, "array comprehension");
}
return comprehensiveArrayExpression();
} else if (blocktype.isDestAssign && !state.inESNext()) {
warning("W104", state.tokens.curr, "destructuring assignment");
}
var b = state.tokens.curr.line !== startLine(state.tokens.next);
this.first = [];
if (b) {
indent += state.option.indent;
if (state.tokens.next.from === indent + state.option.indent) {
indent += state.option.indent;
}
}
while (state.tokens.next.id !== "(end)") {
while (state.tokens.next.id === ",") {
if (!state.option.elision) {
if (!state.inES5()) {
// Maintain compat with old options --- ES5 mode without
// elision=true will warn once per comma
warning("W070");
} else {
warning("W128");
do {
advance(",");
} while (state.tokens.next.id === ",");
continue;
}
}
advance(",");
}
if (state.tokens.next.id === "]") {
break;
}
this.first.push(expression(10));
if (state.tokens.next.id === ",") {
comma({ allowTrailing: true });
if (state.tokens.next.id === "]" && !state.inES5(true)) {
warning("W070", state.tokens.curr);
break;
}
} else {
break;
}
}
if (b) {
indent -= state.option.indent;
}
advance("]", this);
return this;
});
function isMethod() {
return funct["(statement)"] && funct["(statement)"].type === "class" ||
funct["(context)"] && funct["(context)"]["(verb)"] === "class";
}
function isPropertyName(token) {
return token.identifier || token.id === "(string)" || token.id === "(number)";
}
function propertyName(preserveOrToken) {
var id;
var preserve = true;
if (typeof preserveOrToken === "object") {
id = preserveOrToken;
} else {
preserve = preserveOrToken;
id = optionalidentifier(false, true, preserve);
}
if (!id) {
if (state.tokens.next.id === "(string)") {
id = state.tokens.next.value;
if (!preserve) {
advance();
}
} else if (state.tokens.next.id === "(number)") {
id = state.tokens.next.value.toString();
if (!preserve) {
advance();
}
}
} else if (typeof id === "object") {
if (id.id === "(string)" || id.id === "(identifier)") id = id.value;
else if (id.id === "(number)") id = id.value.toString();
}
if (id === "hasOwnProperty") {
warning("W001");
}
return id;
}
/**
* @param {Object} [options]
* @param {token} [options.loneArg] The argument to the function in cases
* where it was defined using the
* single-argument shorthand.
* @param {bool} [options.parsedOpening] Whether the opening parenthesis has
* already been parsed.
*/
function functionparams(options) {
var next;
var params = [];
var ident;
var tokens = [];
var t;
var pastDefault = false;
var pastRest = false;
var loneArg = options && options.loneArg;
if (loneArg && loneArg.identifier === true) {
addlabel(loneArg.value, { type: "unused", token: loneArg });
return [loneArg.value];
}
next = state.tokens.next;
if (!options || !options.parsedOpening) {
advance("(");
}
if (state.tokens.next.id === ")") {
advance(")");
return;
}
for (;;) {
if (_.contains(["{", "["], state.tokens.next.id)) {
tokens = destructuringExpression();
for (t in tokens) {
t = tokens[t];
if (t.id) {
params.push(t.id);
addlabel(t.id, { type: "unused", token: t.token });
}
}
} else {
if (checkPunctuators(state.tokens.next, ["..."])) pastRest = true;
ident = identifier(true);
if (ident) {
params.push(ident);
addlabel(ident, { type: "unused", token: state.tokens.curr });
} else {
// Skip invalid parameter.
while (!checkPunctuators(state.tokens.next, [",", ")"])) advance();
}
}
// it is a syntax error to have a regular argument after a default argument
if (pastDefault) {
if (state.tokens.next.id !== "=") {
error("E051", state.tokens.current);
}
}
if (state.tokens.next.id === "=") {
if (!state.inESNext()) {
warning("W119", state.tokens.next, "default parameters");
}
advance("=");
pastDefault = true;
expression(10);
}
if (state.tokens.next.id === ",") {
if (pastRest) {
warning("W131", state.tokens.next);
}
comma();
} else {
advance(")", next);
return params;
}
}
}
function functor(name, token, scope, overwrites) {
var funct = {
"(name)" : name,
"(breakage)" : 0,
"(loopage)" : 0,
"(scope)" : scope,
"(tokens)" : {},
"(properties)": {},
"(catch)" : false,
"(global)" : false,
"(line)" : null,
"(character)" : null,
"(metrics)" : null,
"(statement)" : null,
"(context)" : null,
"(blockscope)": null,
"(comparray)" : null,
"(generator)" : null,
"(params)" : null
};
if (token) {
_.extend(funct, {
"(line)" : token.line,
"(character)": token.character,
"(metrics)" : createMetrics(token)
});
}
_.extend(funct, overwrites);
if (funct["(context)"]) {
funct["(blockscope)"] = funct["(context)"]["(blockscope)"];
funct["(comparray)"] = funct["(context)"]["(comparray)"];
}
return funct;
}
function isFunctor(token) {
return "(scope)" in token;
}
/**
* Determine if the parser has begun parsing executable code.
*
* @param {Token} funct - The current "functor" token
*
* @returns {boolean}
*/
function hasParsedCode(funct) {
return funct["(global)"] && !funct["(verb)"];
}
function doTemplateLiteral(left) {
// ASSERT: this.type === "(template)"
// jshint validthis: true
var ctx = this.context;
var noSubst = this.noSubst;
var depth = this.depth;
if (!noSubst) {
while (!end()) {
if (!state.tokens.next.template || state.tokens.next.depth > depth) {
expression(0); // should probably have different rbp?
} else {
// skip template start / middle
advance();
}
}
}
return {
id: "(template)",
type: "(template)",
tag: left
};
function end() {
if (state.tokens.curr.template && state.tokens.curr.tail &&
state.tokens.curr.context === ctx) return true;
var complete = (state.tokens.next.template && state.tokens.next.tail &&
state.tokens.next.context === ctx);
if (complete) advance();
return complete || state.tokens.next.isUnclosed;
}
}
/**
* @param {Object} [options]
* @param {token} [options.name] The identifier belonging to the function (if
* any)
* @param {boolean} [options.statement] The statement that triggered creation
* of the current function.
* @param {string} [options.type] If specified, either "generator" or "arrow"
* @param {token} [options.loneArg] The argument to the function in cases
* where it was defined using the
* single-argument shorthand
* @param {bool} [options.parsedOpening] Whether the opening parenthesis has
* already been parsed
* @param {token} [options.classExprBinding] Define a function with this
* identifier in the new function's
* scope, mimicking the bahavior of
* class expression names within
* the body of member functions.
*/
function doFunction(options) {
var f, name, statement, classExprBinding, isGenerator, isArrow;
var oldOption = state.option;
var oldIgnored = state.ignored;
var oldScope = scope;
if (options) {
name = options.name;
statement = options.statement;
classExprBinding = options.classExprBinding;
isGenerator = options.type === "generator";
isArrow = options.type === "arrow";
}
state.option = Object.create(state.option);
state.ignored = Object.create(state.ignored);
scope = Object.create(scope);
funct = functor(name || state.nameStack.infer(), state.tokens.next, scope, {
"(statement)": statement,
"(context)": funct,
"(generator)": isGenerator
});
f = funct;
state.tokens.curr.funct = funct;
functions.push(funct);
if (name) {
addlabel(name, { type: "function" });
}
if (classExprBinding) {
addlabel(classExprBinding, { type: "function" });
}
funct["(params)"] = functionparams(options);
funct["(metrics)"].verifyMaxParametersPerFunction(funct["(params)"]);
if (isArrow) {
if (!state.option.esnext) {
warning("W119", state.tokens.curr, "arrow function syntax (=>)");
}
if (!options.loneArg) {
advance("=>");
}
}
block(false, true, true, isArrow);
if (!state.option.noyield && isGenerator &&
funct["(generator)"] !== "yielded") {
warning("W124", state.tokens.curr);
}
funct["(metrics)"].verifyMaxStatementsPerFunction();
funct["(metrics)"].verifyMaxComplexityPerFunction();
funct["(unusedOption)"] = state.option.unused;
scope = oldScope;
state.option = oldOption;
state.ignored = oldIgnored;
funct["(last)"] = state.tokens.curr.line;
funct["(lastcharacter)"] = state.tokens.curr.character;
_.map(Object.keys(funct), function(key) {
if (key[0] === "(") return;
funct["(blockscope)"].unshadow(key);
});
funct = funct["(context)"];
return f;
}
function createMetrics(functionStartToken) {
return {
statementCount: 0,
nestedBlockDepth: -1,
ComplexityCount: 1,
verifyMaxStatementsPerFunction: function() {
if (state.option.maxstatements &&
this.statementCount > state.option.maxstatements) {
warning("W071", functionStartToken, this.statementCount);
}
},
verifyMaxParametersPerFunction: function(params) {
params = params || [];
if (_.isNumber(state.option.maxparams) && params.length > state.option.maxparams) {
warning("W072", functionStartToken, params.length);
}
},
verifyMaxNestedBlockDepthPerFunction: function() {
if (state.option.maxdepth &&
this.nestedBlockDepth > 0 &&
this.nestedBlockDepth === state.option.maxdepth + 1) {
warning("W073", null, this.nestedBlockDepth);
}
},
verifyMaxComplexityPerFunction: function() {
var max = state.option.maxcomplexity;
var cc = this.ComplexityCount;
if (max && cc > max) {
warning("W074", functionStartToken, cc);
}
}
};
}
function increaseComplexityCount() {
funct["(metrics)"].ComplexityCount += 1;
}
// Parse assignments that were found instead of conditionals.
// For example: if (a = 1) { ... }
function checkCondAssignment(expr) {
var id, paren;
if (expr) {
id = expr.id;
paren = expr.paren;
if (id === "," && (expr = expr.exprs[expr.exprs.length - 1])) {
id = expr.id;
paren = paren || expr.paren;
}
}
switch (id) {
case "=":
case "+=":
case "-=":
case "*=":
case "%=":
case "&=":
case "|=":
case "^=":
case "/=":
if (!paren && !state.option.boss) {
warning("W084");
}
}
}
/**
* @param {object} props Collection of property descriptors for a given
* object.
*/
function checkProperties(props) {
// Check for lonely setters if in the ES5 mode.
if (state.inES5()) {
for (var name in props) {
if (_.has(props, name) && props[name].setterToken && !props[name].getterToken) {
warning("W078", props[name].setterToken);
}
}
}
}
(function(x) {
x.nud = function() {
var b, f, i, p, t, isGeneratorMethod = false, nextVal;
var props = {}; // All properties, including accessors
b = state.tokens.curr.line !== startLine(state.tokens.next);
if (b) {
indent += state.option.indent;
if (state.tokens.next.from === indent + state.option.indent) {
indent += state.option.indent;
}
}
for (;;) {
if (state.tokens.next.id === "}") {
break;
}
nextVal = state.tokens.next.value;
if (state.tokens.next.identifier &&
(peekIgnoreEOL().id === "," || peekIgnoreEOL().id === "}")) {
if (!state.inESNext()) {
warning("W104", state.tokens.next, "object short notation");
}
i = propertyName(true);
saveProperty(props, i, state.tokens.next);
expression(10);
} else if (peek().id !== ":" && (nextVal === "get" || nextVal === "set")) {
advance(nextVal);
if (!state.inES5()) {
error("E034");
}
i = propertyName();
// ES6 allows for get() {...} and set() {...} method
// definition shorthand syntax, so we don't produce an error
// if the esnext option is enabled.
if (!i && !state.inESNext()) {
error("E035");
}
// We don't want to save this getter unless it's an actual getter
// and not an ES6 concise method
if (i) {
saveAccessor(nextVal, props, i, state.tokens.curr);
}
t = state.tokens.next;
f = doFunction();
p = f["(params)"];
// Don't warn about getter/setter pairs if this is an ES6 concise method
if (nextVal === "get" && i && p) {
warning("W076", t, p[0], i);
} else if (nextVal === "set" && i && (!p || p.length !== 1)) {
warning("W077", t, i);
}
} else {
if (state.tokens.next.value === "*" && state.tokens.next.type === "(punctuator)") {
if (!state.inESNext()) {
warning("W104", state.tokens.next, "generator functions");
}
advance("*");
isGeneratorMethod = true;
} else {
isGeneratorMethod = false;
}
if (state.tokens.next.id === "[") {
i = computedPropertyName();
state.nameStack.set(i);
} else {
state.nameStack.set(state.tokens.next);
i = propertyName();
saveProperty(props, i, state.tokens.next);
if (typeof i !== "string") {
break;
}
}
if (state.tokens.next.value === "(") {
if (!state.inESNext()) {
warning("W104", state.tokens.curr, "concise methods");
}
doFunction({ type: isGeneratorMethod ? "generator" : null });
} else {
advance(":");
expression(10);
}
}
countMember(i);
if (state.tokens.next.id === ",") {
comma({ allowTrailing: true, property: true });
if (state.tokens.next.id === ",") {
warning("W070", state.tokens.curr);
} else if (state.tokens.next.id === "}" && !state.inES5(true)) {
warning("W070", state.tokens.curr);
}
} else {
break;
}
}
if (b) {
indent -= state.option.indent;
}
advance("}", this);
checkProperties(props);
return this;
};
x.fud = function() {
error("E036", state.tokens.curr);
};
}(delim("{")));
function destructuringExpression() {
var id, ids;
var identifiers = [];
if (!state.inESNext()) {
warning("W104", state.tokens.curr, "destructuring expression");
}
var nextInnerDE = function() {
var ident;
if (checkPunctuators(state.tokens.next, ["[", "{"])) {
ids = destructuringExpression();
for (var id in ids) {
id = ids[id];
identifiers.push({ id: id.id, token: id.token });
}
} else if (checkPunctuators(state.tokens.next, [","])) {
identifiers.push({ id: null, token: state.tokens.curr });
} else if (checkPunctuators(state.tokens.next, ["("])) {
advance("(");
nextInnerDE();
advance(")");
} else {
var is_rest = checkPunctuators(state.tokens.next, ["..."]);
ident = identifier();
if (ident)
identifiers.push({ id: ident, token: state.tokens.curr });
return is_rest;
}
return false;
};
if (checkPunctuators(state.tokens.next, ["["])) {
advance("[");
var element_after_rest = false;
if (nextInnerDE() && checkPunctuators(state.tokens.next, [","]) &&
!element_after_rest) {
warning("W130", state.tokens.next);
element_after_rest = true;
}
while (!checkPunctuators(state.tokens.next, ["]"])) {
advance(",");
if (checkPunctuators(state.tokens.next, ["]"])) {
// Trailing comma
break;
}
if (nextInnerDE() && checkPunctuators(state.tokens.next, [","]) &&
!element_after_rest) {
warning("W130", state.tokens.next);
element_after_rest = true;
}
}
advance("]");
} else if (checkPunctuators(state.tokens.next, ["{"])) {
advance("{");
id = identifier();
if (checkPunctuators(state.tokens.next, [":"])) {
advance(":");
nextInnerDE();
} else {
identifiers.push({ id: id, token: state.tokens.curr });
}
while (!checkPunctuators(state.tokens.next, ["}"])) {
advance(",");
if (checkPunctuators(state.tokens.next, ["}"])) {
// Trailing comma
// ObjectBindingPattern: { BindingPropertyList , }
break;
}
id = identifier();
if (checkPunctuators(state.tokens.next, [":"])) {
advance(":");
nextInnerDE();
} else {
identifiers.push({ id: id, token: state.tokens.curr });
}
}
advance("}");
}
return identifiers;
}
function destructuringExpressionMatch(tokens, value) {
var first = value.first;
if (!first)
return;
_.zip(tokens, Array.isArray(first) ? first : [ first ]).forEach(function(val) {
var token = val[0];
var value = val[1];
if (token && value)
token.first = value;
else if (token && token.first && !value)
warning("W080", token.first, token.first.value);
});
}
function blockVariableStatement(type, statement, context) {
// used for both let and const statements
var prefix = context && context.prefix;
var inexport = context && context.inexport;
var isLet = type === "let";
var isConst = type === "const";
var tokens, lone, value, letblock;
if (!state.inESNext()) {
warning("W104", state.tokens.curr, type);
}
if (isLet && state.tokens.next.value === "(") {
if (!state.inMoz()) {
warning("W118", state.tokens.next, "let block");
}
advance("(");
funct["(blockscope)"].stack();
letblock = true;
} else if (funct["(noblockscopedvar)"]) {
error("E048", state.tokens.curr, isConst ? "Const" : "Let");
}
statement.first = [];
for (;;) {
var names = [];
if (_.contains(["{", "["], state.tokens.next.value)) {
tokens = destructuringExpression();
lone = false;
} else {
tokens = [ { id: identifier(), token: state.tokens.curr } ];
lone = true;
if (inexport) {
exported[state.tokens.curr.value] = true;
state.tokens.curr.exported = true;
}
}
for (var t in tokens) {
if (tokens.hasOwnProperty(t)) {
t = tokens[t];
if (state.inESNext()) {
// only look in the latest scope because we can shadow
if (funct["(blockscope)"].current.labeltype(t.id) === "const") {
warning("E011", null, t.id);
}
}
if (funct["(global)"]) {
if (predefined[t.id] === false) {
warning("W079", t.token, t.id);
}
}
if (t.id && !funct["(noblockscopedvar)"]) {
addlabel(t.id, {
type: isConst ? "const" : "unused",
token: t.token,
isblockscoped: true });
names.push(t.token);
}
}
}
statement.first = statement.first.concat(names);
if (!prefix && isConst && state.tokens.next.id !== "=") {
warning("E012", state.tokens.curr, state.tokens.curr.value);
}
if (state.tokens.next.id === "=") {
advance("=");
if (!prefix && state.tokens.next.id === "undefined") {
warning("W080", state.tokens.prev, state.tokens.prev.value);
}
if (!prefix && peek(0).id === "=" && state.tokens.next.identifier) {
warning("W120", state.tokens.next, state.tokens.next.value);
}
// don't accept `in` in expression if prefix is used for ForIn/Of loop.
value = expression(prefix ? 120 : 10);
if (lone) {
tokens[0].first = value;
} else {
destructuringExpressionMatch(names, value);
}
}
if (state.tokens.next.id !== ",") {
break;
}
comma();
}
if (letblock) {
advance(")");
block(true, true);
statement.block = true;
funct["(blockscope)"].unstack();
}
return statement;
}
var conststatement = stmt("const", function(context) {
return blockVariableStatement("const", this, context);
});
conststatement.exps = true;
var letstatement = stmt("let", function(context) {
return blockVariableStatement("let", this, context);
});
letstatement.exps = true;
var varstatement = stmt("var", function(context) {
var prefix = context && context.prefix;
var inexport = context && context.inexport;
var tokens, lone, value;
// If the `implied` option is set, bindings are set differently.
var implied = context && context.implied;
var report = !(context && context.ignore);
this.first = [];
for (;;) {
var names = [];
if (_.contains(["{", "["], state.tokens.next.value)) {
tokens = destructuringExpression();
lone = false;
} else {
tokens = [ { id: identifier(), token: state.tokens.curr } ];
lone = true;
if (inexport) {
exported[state.tokens.curr.value] = true;
state.tokens.curr.exported = true;
}
}
for (var t in tokens) {
if (tokens.hasOwnProperty(t)) {
t = tokens[t];
if (state.inESNext()) {
// because var is function scoped, look in the whole function
if (funct["(blockscope)"].labeltype(t.id) === "const") {
warning("E011", null, t.id);
}
}
if (!implied && funct["(global)"]) {
if (predefined[t.id] === false) {
warning("W079", t.token, t.id);
} else if (state.option.futurehostile === false) {
if ((!state.inES5() && vars.ecmaIdentifiers[5][t.id] === false) ||
(!state.inESNext() && vars.ecmaIdentifiers[6][t.id] === false)) {
warning("W129", t.token, t.id);
}
}
}
if (t.id) {
if (implied === "for") {
var ident = t.token.value;
switch (funct[ident]) {
case "unused":
funct[ident] = "var";
break;
case "var":
break;
default:
if (!funct["(blockscope)"].getlabel(ident) &&
!(scope[ident] || {})[ident]) {
if (report) warning("W088", t.token, ident);
}
}
} else {
addlabel(t.id, { type: "unused", token: t.token });
}
names.push(t.token);
}
}
}
if (!prefix && report && state.option.varstmt) {
warning("W132", this);
}
this.first = this.first.concat(names);
if (state.tokens.next.id === "=") {
state.nameStack.set(state.tokens.curr);
advance("=");
if (!prefix && report && state.tokens.next.id === "undefined") {
warning("W080", state.tokens.prev, state.tokens.prev.value);
}
if (peek(0).id === "=" && state.tokens.next.identifier) {
if (!prefix && report &&
!funct["(params)"] || funct["(params)"].indexOf(state.tokens.next.value) === -1) {
warning("W120", state.tokens.next, state.tokens.next.value);
}
}
// don't accept `in` in expression if prefix is used for ForIn/Of loop.
value = expression(prefix ? 120 : 10);
if (lone) {
tokens[0].first = value;
} else {
destructuringExpressionMatch(names, value);
}
}
if (state.tokens.next.id !== ",") {
break;
}
comma();
}
return this;
});
varstatement.exps = true;
blockstmt("class", function() {
return classdef.call(this, true);
});
function classdef(isStatement) {
/*jshint validthis:true */
if (!state.inESNext()) {
warning("W104", state.tokens.curr, "class");
}
if (isStatement) {
// BindingIdentifier
this.name = identifier();
addlabel(this.name, { type: "unused", token: state.tokens.curr });
} else if (state.tokens.next.identifier && state.tokens.next.value !== "extends") {
// BindingIdentifier(opt)
this.name = identifier();
this.namedExpr = true;
} else {
this.name = state.nameStack.infer();
}
classtail(this);
return this;
}
function classtail(c) {
var wasInClassBody = state.inClassBody;
// ClassHeritage(opt)
if (state.tokens.next.value === "extends") {
advance("extends");
c.heritage = expression(10);
}
state.inClassBody = true;
advance("{");
// ClassBody(opt)
c.body = classbody(c);
advance("}");
state.inClassBody = wasInClassBody;
}
function classbody(c) {
var name;
var isStatic;
var isGenerator;
var getset;
var props = {};
var staticProps = {};
var computed;
for (var i = 0; state.tokens.next.id !== "}"; ++i) {
name = state.tokens.next;
isStatic = false;
isGenerator = false;
getset = null;
// The ES6 grammar for ClassElement includes the `;` token, but it is
// defined only as a placeholder to facilitate future language
// extensions. In ES6 code, it serves no purpose.
if (name.id === ";") {
warning("W032");
advance(";");
continue;
}
if (name.id === "*") {
isGenerator = true;
advance("*");
name = state.tokens.next;
}
if (name.id === "[") {
name = computedPropertyName();
computed = true;
} else if (isPropertyName(name)) {
// Non-Computed PropertyName
advance();
computed = false;
if (name.identifier && name.value === "static") {
if (checkPunctuators(state.tokens.next, ["*"])) {
isGenerator = true;
advance("*");
}
if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") {
computed = state.tokens.next.id === "[";
isStatic = true;
name = state.tokens.next;
if (state.tokens.next.id === "[") {
name = computedPropertyName();
} else advance();
}
}
if (name.identifier && (name.value === "get" || name.value === "set")) {
if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") {
computed = state.tokens.next.id === "[";
getset = name;
name = state.tokens.next;
if (state.tokens.next.id === "[") {
name = computedPropertyName();
} else advance();
}
}
} else {
warning("W052", state.tokens.next, state.tokens.next.value || state.tokens.next.type);
advance();
continue;
}
if (!checkPunctuators(state.tokens.next, ["("])) {
// error --- class properties must be methods
error("E054", state.tokens.next, state.tokens.next.value);
while (state.tokens.next.id !== "}" &&
!checkPunctuators(state.tokens.next, ["("])) {
advance();
}
if (state.tokens.next.value !== "(") {
doFunction({ statement: c });
}
}
if (!computed) {
// We don't know how to determine if we have duplicate computed property names :(
if (getset) {
saveAccessor(
getset.value, isStatic ? staticProps : props, name.value, name, true, isStatic);
} else {
if (name.value === "constructor") {
state.nameStack.set(c);
} else {
state.nameStack.set(name);
}
saveProperty(isStatic ? staticProps : props, name.value, name, true, isStatic);
}
}
if (getset && name.value === "constructor") {
var propDesc = getset.value === "get" ? "class getter method" : "class setter method";
error("E049", name, propDesc, "constructor");
} else if (name.value === "prototype") {
error("E049", name, "class method", "prototype");
}
propertyName(name);
doFunction({
statement: c,
type: isGenerator ? "generator" : null,
classExprBinding: c.namedExpr ? c.name : null
});
}
checkProperties(props);
}
blockstmt("function", function() {
var generator = false;
if (state.tokens.next.value === "*") {
advance("*");
if (state.inESNext({ strict: true })) {
generator = true;
} else {
warning("W119", state.tokens.curr, "function*");
}
}
if (inblock) {
warning("W082", state.tokens.curr);
}
var i = optionalidentifier();
if (i === undefined) {
warning("W025");
}
// check if a identifier with the same name is already defined
// in the blockscope as a const
if (funct["(blockscope)"].labeltype(i) === "const") {
warning("E011", null, i);
}
addlabel(i, { type: "unction", token: state.tokens.curr });
doFunction({
name: i,
statement: this,
type: generator ? "generator" : null
});
if (state.tokens.next.id === "(" && state.tokens.next.line === state.tokens.curr.line) {
error("E039");
}
return this;
});
prefix("function", function() {
var generator = false;
if (state.tokens.next.value === "*") {
if (!state.inESNext()) {
warning("W119", state.tokens.curr, "function*");
}
advance("*");
generator = true;
}
var i = optionalidentifier();
var fn = doFunction({ name: i, type: generator ? "generator" : null });
function isVariable(name) { return name[0] !== "("; }
function isLocal(name) { return fn[name] === "var"; }
if (!state.option.loopfunc && funct["(loopage)"]) {
// If the function we just parsed accesses any non-local variables
// trigger a warning. Otherwise, the function is safe even within
// a loop.
if (_.some(fn, function(val, name) { return isVariable(name) && !isLocal(name); })) {
warning("W083");
}
}
return this;
});
blockstmt("if", function() {
var t = state.tokens.next;
increaseComplexityCount();
state.condition = true;
advance("(");
var expr = expression(0);
checkCondAssignment(expr);
// When the if is within a for-in loop, check if the condition
// starts with a negation operator
var forinifcheck = null;
if (state.option.forin && state.forinifcheckneeded) {
state.forinifcheckneeded = false; // We only need to analyze the first if inside the loop
forinifcheck = state.forinifchecks[state.forinifchecks.length - 1];
if (expr.type === "(punctuator)" && expr.value === "!") {
forinifcheck.type = "(negative)";
} else {
forinifcheck.type = "(positive)";
}
}
advance(")", t);
state.condition = false;
var s = block(true, true);
// When the if is within a for-in loop and the condition has a negative form,
// check if the body contains nothing but a continue statement
if (forinifcheck && forinifcheck.type === "(negative)") {
if (s && s.length === 1 && s[0].type === "(identifier)" && s[0].value === "continue") {
forinifcheck.type = "(negative-with-continue)";
}
}
if (state.tokens.next.id === "else") {
advance("else");
if (state.tokens.next.id === "if" || state.tokens.next.id === "switch") {
statement();
} else {
block(true, true);
}
}
return this;
});
blockstmt("try", function() {
var b;
function doCatch() {
var oldScope = scope;
var e;
advance("catch");
advance("(");
scope = Object.create(oldScope);
e = state.tokens.next.value;
if (state.tokens.next.type !== "(identifier)") {
e = null;
warning("E030", state.tokens.next, e);
}
advance();
funct = functor("(catch)", state.tokens.next, scope, {
"(context)" : funct,
"(breakage)" : funct["(breakage)"],
"(loopage)" : funct["(loopage)"],
"(statement)": false,
"(catch)" : true
});
if (e) {
addlabel(e, { type: "exception" });
}
if (state.tokens.next.value === "if") {
if (!state.inMoz()) {
warning("W118", state.tokens.curr, "catch filter");
}
advance("if");
expression(0);
}
advance(")");
state.tokens.curr.funct = funct;
functions.push(funct);
block(false);
scope = oldScope;
funct["(last)"] = state.tokens.curr.line;
funct["(lastcharacter)"] = state.tokens.curr.character;
funct = funct["(context)"];
}
block(true);
while (state.tokens.next.id === "catch") {
increaseComplexityCount();
if (b && (!state.inMoz())) {
warning("W118", state.tokens.next, "multiple catch blocks");
}
doCatch();
b = true;
}
if (state.tokens.next.id === "finally") {
advance("finally");
block(true);
return;
}
if (!b) {
error("E021", state.tokens.next, "catch", state.tokens.next.value);
}
return this;
});
blockstmt("while", function() {
var t = state.tokens.next;
funct["(breakage)"] += 1;
funct["(loopage)"] += 1;
increaseComplexityCount();
advance("(");
checkCondAssignment(expression(0));
advance(")", t);
block(true, true);
funct["(breakage)"] -= 1;
funct["(loopage)"] -= 1;
return this;
}).labelled = true;
blockstmt("with", function() {
var t = state.tokens.next;
if (state.isStrict()) {
error("E010", state.tokens.curr);
} else if (!state.option.withstmt) {
warning("W085", state.tokens.curr);
}
advance("(");
expression(0);
advance(")", t);
block(true, true);
return this;
});
blockstmt("switch", function() {
var t = state.tokens.next;
var g = false;
var noindent = false;
funct["(breakage)"] += 1;
advance("(");
checkCondAssignment(expression(0));
advance(")", t);
t = state.tokens.next;
advance("{");
if (state.tokens.next.from === indent)
noindent = true;
if (!noindent)
indent += state.option.indent;
this.cases = [];
for (;;) {
switch (state.tokens.next.id) {
case "case":
switch (funct["(verb)"]) {
case "yield":
case "break":
case "case":
case "continue":
case "return":
case "switch":
case "throw":
break;
default:
// You can tell JSHint that you don't use break intentionally by
// adding a comment /* falls through */ on a line just before
// the next `case`.
if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) {
warning("W086", state.tokens.curr, "case");
}
}
advance("case");
this.cases.push(expression(0));
increaseComplexityCount();
g = true;
advance(":");
funct["(verb)"] = "case";
break;
case "default":
switch (funct["(verb)"]) {
case "yield":
case "break":
case "continue":
case "return":
case "throw":
break;
default:
// Do not display a warning if 'default' is the first statement or if
// there is a special /* falls through */ comment.
if (this.cases.length) {
if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) {
warning("W086", state.tokens.curr, "default");
}
}
}
advance("default");
g = true;
advance(":");
break;
case "}":
if (!noindent)
indent -= state.option.indent;
advance("}", t);
funct["(breakage)"] -= 1;
funct["(verb)"] = undefined;
return;
case "(end)":
error("E023", state.tokens.next, "}");
return;
default:
indent += state.option.indent;
if (g) {
switch (state.tokens.curr.id) {
case ",":
error("E040");
return;
case ":":
g = false;
statements();
break;
default:
error("E025", state.tokens.curr);
return;
}
} else {
if (state.tokens.curr.id === ":") {
advance(":");
error("E024", state.tokens.curr, ":");
statements();
} else {
error("E021", state.tokens.next, "case", state.tokens.next.value);
return;
}
}
indent -= state.option.indent;
}
}
}).labelled = true;
stmt("debugger", function() {
if (!state.option.debug) {
warning("W087", this);
}
return this;
}).exps = true;
(function() {
var x = stmt("do", function() {
funct["(breakage)"] += 1;
funct["(loopage)"] += 1;
increaseComplexityCount();
this.first = block(true, true);
advance("while");
var t = state.tokens.next;
advance("(");
checkCondAssignment(expression(0));
advance(")", t);
funct["(breakage)"] -= 1;
funct["(loopage)"] -= 1;
return this;
});
x.labelled = true;
x.exps = true;
}());
blockstmt("for", function() {
var s, t = state.tokens.next;
var letscope = false;
var foreachtok = null;
if (t.value === "each") {
foreachtok = t;
advance("each");
if (!state.inMoz()) {
warning("W118", state.tokens.curr, "for each");
}
}
funct["(breakage)"] += 1;
funct["(loopage)"] += 1;
increaseComplexityCount();
advance("(");
// what kind of for(…) statement it is? for(…of…)? for(…in…)? for(…;…;…)?
var nextop; // contains the token of the "in" or "of" operator
var i = 0;
var inof = ["in", "of"];
var level = 0; // BindingPattern "level" --- level 0 === no BindingPattern
var comma; // First comma punctuator at level 0
var initializer; // First initializer at level 0
// If initial token is a BindingPattern, count it as such.
if (checkPunctuators(state.tokens.next, ["{", "["])) ++level;
do {
nextop = peek(i);
++i;
if (checkPunctuators(nextop, ["{", "["])) ++level;
else if (checkPunctuators(nextop, ["}", "]"])) --level;
if (level < 0) break;
if (level === 0) {
if (!comma && checkPunctuators(nextop, [","])) comma = nextop;
else if (!initializer && checkPunctuators(nextop, ["="])) initializer = nextop;
}
} while (level > 0 || !_.contains(inof, nextop.value) && nextop.value !== ";" &&
nextop.type !== "(end)"); // Is this a JSCS bug? This looks really weird.
// if we're in a for (… in|of …) statement
if (_.contains(inof, nextop.value)) {
if (!state.inESNext() && nextop.value === "of") {
error("W104", nextop, "for of");
}
var ok = !(initializer || comma);
if (initializer) {
error("W133", comma, nextop.value, "initializer is forbidden");
}
if (comma) {
error("W133", comma, nextop.value, "more than one ForBinding");
}
if (state.tokens.next.id === "var") {
advance("var");
state.tokens.curr.fud({ prefix: true });
} else if (state.tokens.next.id === "let" || state.tokens.next.id === "const") {
advance(state.tokens.next.id);
// create a new block scope
letscope = true;
funct["(blockscope)"].stack();
state.tokens.curr.fud({ prefix: true });
} else {
// Parse as a var statement, with implied bindings. Ignore errors if an error
// was already reported
Object.create(varstatement).fud({ prefix: true, implied: "for", ignore: !ok });
}
advance(nextop.value);
expression(20);
advance(")", t);
if (nextop.value === "in" && state.option.forin) {
state.forinifcheckneeded = true;
if (state.forinifchecks === undefined) {
state.forinifchecks = [];
}
// Push a new for-in-if check onto the stack. The type will be modified
// when the loop's body is parsed and a suitable if statement exists.
state.forinifchecks.push({
type: "(none)"
});
}
s = block(true, true);
if (nextop.value === "in" && state.option.forin) {
if (state.forinifchecks && state.forinifchecks.length > 0) {
var check = state.forinifchecks.pop();
if (// No if statement or not the first statement in loop body
s && s.length > 0 && (typeof s[0] !== "object" || s[0].value !== "if") ||
// Positive if statement is not the only one in loop body
check.type === "(positive)" && s.length > 1 ||
// Negative if statement but no continue
check.type === "(negative)") {
warning("W089", this);
}
}
// Reset the flag in case no if statement was contained in the loop body
state.forinifcheckneeded = false;
}
funct["(breakage)"] -= 1;
funct["(loopage)"] -= 1;
} else {
if (foreachtok) {
error("E045", foreachtok);
}
if (state.tokens.next.id !== ";") {
if (state.tokens.next.id === "var") {
advance("var");
state.tokens.curr.fud();
} else if (state.tokens.next.id === "let") {
advance("let");
// create a new block scope
letscope = true;
funct["(blockscope)"].stack();
state.tokens.curr.fud();
} else {
for (;;) {
expression(0, "for");
if (state.tokens.next.id !== ",") {
break;
}
comma();
}
}
}
nolinebreak(state.tokens.curr);
advance(";");
if (state.tokens.next.id !== ";") {
checkCondAssignment(expression(0));
}
nolinebreak(state.tokens.curr);
advance(";");
if (state.tokens.next.id === ";") {
error("E021", state.tokens.next, ")", ";");
}
if (state.tokens.next.id !== ")") {
for (;;) {
expression(0, "for");
if (state.tokens.next.id !== ",") {
break;
}
comma();
}
}
advance(")", t);
block(true, true);
funct["(breakage)"] -= 1;
funct["(loopage)"] -= 1;
}
// unstack loop blockscope
if (letscope) {
funct["(blockscope)"].unstack();
}
return this;
}).labelled = true;
stmt("break", function() {
var v = state.tokens.next.value;
if (funct["(breakage)"] === 0)
warning("W052", state.tokens.next, this.value);
if (!state.option.asi)
nolinebreak(this);
if (state.tokens.next.id !== ";" && !state.tokens.next.reach) {
if (state.tokens.curr.line === startLine(state.tokens.next)) {
if (funct[v] !== "label") {
warning("W090", state.tokens.next, v);
} else if (scope[v] !== funct) {
warning("W091", state.tokens.next, v);
}
this.first = state.tokens.next;
advance();
}
}
reachable(this);
return this;
}).exps = true;
stmt("continue", function() {
var v = state.tokens.next.value;
if (funct["(breakage)"] === 0)
warning("W052", state.tokens.next, this.value);
if (!state.option.asi)
nolinebreak(this);
if (state.tokens.next.id !== ";" && !state.tokens.next.reach) {
if (state.tokens.curr.line === startLine(state.tokens.next)) {
if (funct[v] !== "label") {
warning("W090", state.tokens.next, v);
} else if (scope[v] !== funct) {
warning("W091", state.tokens.next, v);
}
this.first = state.tokens.next;
advance();
}
} else if (!funct["(loopage)"]) {
warning("W052", state.tokens.next, this.value);
}
reachable(this);
return this;
}).exps = true;
stmt("return", function() {
if (this.line === startLine(state.tokens.next)) {
if (state.tokens.next.id !== ";" && !state.tokens.next.reach) {
this.first = expression(0);
if (this.first &&
this.first.type === "(punctuator)" && this.first.value === "=" &&
!this.first.paren && !state.option.boss) {
warningAt("W093", this.first.line, this.first.character);
}
}
} else {
if (state.tokens.next.type === "(punctuator)" &&
["[", "{", "+", "-"].indexOf(state.tokens.next.value) > -1) {
nolinebreak(this); // always warn (Line breaking error)
}
}
reachable(this);
return this;
}).exps = true;
(function(x) {
x.exps = true;
x.lbp = 25;
}(prefix("yield", function() {
var prev = state.tokens.prev;
if (state.inESNext(true) && !funct["(generator)"]) {
// If it's a yield within a catch clause inside a generator then that's ok
if (!("(catch)" === funct["(name)"] && funct["(context)"]["(generator)"])) {
error("E046", state.tokens.curr, "yield");
}
} else if (!state.inESNext()) {
warning("W104", state.tokens.curr, "yield");
}
funct["(generator)"] = "yielded";
var delegatingYield = false;
if (state.tokens.next.value === "*") {
delegatingYield = true;
advance("*");
}
if (this.line === startLine(state.tokens.next) || !state.inMoz()) {
if (delegatingYield ||
(state.tokens.next.id !== ";" && !state.tokens.next.reach && state.tokens.next.nud)) {
nobreaknonadjacent(state.tokens.curr, state.tokens.next);
this.first = expression(10);
if (this.first.type === "(punctuator)" && this.first.value === "=" &&
!this.first.paren && !state.option.boss) {
warningAt("W093", this.first.line, this.first.character);
}
}
if (state.inMoz() && state.tokens.next.id !== ")" &&
(prev.lbp > 30 || (!prev.assign && !isEndOfExpr()) || prev.id === "yield")) {
error("E050", this);
}
} else if (!state.option.asi) {
nolinebreak(this); // always warn (Line breaking error)
}
return this;
})));
stmt("throw", function() {
nolinebreak(this);
this.first = expression(20);
reachable(this);
return this;
}).exps = true;
stmt("import", function() {
if (!state.inESNext()) {
warning("W119", state.tokens.curr, "import");
}
if (state.tokens.next.type === "(string)") {
// ModuleSpecifier :: StringLiteral
advance("(string)");
return this;
}
if (state.tokens.next.identifier) {
// ImportClause :: ImportedDefaultBinding
this.name = identifier();
addlabel(this.name, { type: "unused", token: state.tokens.curr });
if (state.tokens.next.value === ",") {
// ImportClause :: ImportedDefaultBinding , NameSpaceImport
// ImportClause :: ImportedDefaultBinding , NamedImports
advance(",");
// At this point, we intentionally fall through to continue matching
// either NameSpaceImport or NamedImports.
// Discussion:
// https://github.com/jshint/jshint/pull/2144#discussion_r23978406
} else {
advance("from");
advance("(string)");
return this;
}
}
if (state.tokens.next.id === "*") {
// ImportClause :: NameSpaceImport
advance("*");
advance("as");
if (state.tokens.next.identifier) {
this.name = identifier();
addlabel(this.name, { type: "unused", token: state.tokens.curr });
}
} else {
// ImportClause :: NamedImports
advance("{");
for (;;) {
if (state.tokens.next.value === "}") {
advance("}");
break;
}
var importName;
if (state.tokens.next.type === "default") {
importName = "default";
advance("default");
} else {
importName = identifier();
}
if (state.tokens.next.value === "as") {
advance("as");
importName = identifier();
}
addlabel(importName, { type: "unused", token: state.tokens.curr });
if (state.tokens.next.value === ",") {
advance(",");
} else if (state.tokens.next.value === "}") {
advance("}");
break;
} else {
error("E024", state.tokens.next, state.tokens.next.value);
break;
}
}
}
// FromClause
advance("from");
advance("(string)");
return this;
}).exps = true;
stmt("export", function() {
var ok = true;
var token;
var identifier;
if (!state.inESNext()) {
warning("W119", state.tokens.curr, "export");
ok = false;
}
if (!funct["(global)"] || !funct["(blockscope)"].atTop()) {
error("E053", state.tokens.curr);
ok = false;
}
if (state.tokens.next.value === "*") {
// ExportDeclaration :: export * FromClause
advance("*");
advance("from");
advance("(string)");
return this;
}
if (state.tokens.next.type === "default") {
// ExportDeclaration :: export default HoistableDeclaration
// ExportDeclaration :: export default ClassDeclaration
state.nameStack.set(state.tokens.next);
advance("default");
if (state.tokens.next.id === "function" || state.tokens.next.id === "class") {
this.block = true;
}
token = peek();
expression(10);
if (state.tokens.next.id === "class") {
identifier = token.name;
} else {
identifier = token.value;
}
addlabel(identifier, {
type: "function", token: token
});
return this;
}
if (state.tokens.next.value === "{") {
// ExportDeclaration :: export ExportClause
advance("{");
var exportedTokens = [];
for (;;) {
if (!state.tokens.next.identifier) {
error("E030", state.tokens.next, state.tokens.next.value);
}
advance();
state.tokens.curr.exported = ok;
exportedTokens.push(state.tokens.curr);
if (state.tokens.next.value === "as") {
advance("as");
if (!state.tokens.next.identifier) {
error("E030", state.tokens.next, state.tokens.next.value);
}
advance();
}
if (state.tokens.next.value === ",") {
advance(",");
} else if (state.tokens.next.value === "}") {
advance("}");
break;
} else {
error("E024", state.tokens.next, state.tokens.next.value);
break;
}
}
if (state.tokens.next.value === "from") {
// ExportDeclaration :: export ExportClause FromClause
advance("from");
advance("(string)");
} else if (ok) {
exportedTokens.forEach(function(token) {
if (!funct[token.value]) {
isundef(funct, "W117", token, token.value);
}
exported[token.value] = true;
funct["(blockscope)"].setExported(token.value);
});
}
return this;
}
if (state.tokens.next.id === "var") {
// ExportDeclaration :: export VariableStatement
advance("var");
state.tokens.curr.fud({ inexport:true });
} else if (state.tokens.next.id === "let") {
// ExportDeclaration :: export VariableStatement
advance("let");
state.tokens.curr.fud({ inexport:true });
} else if (state.tokens.next.id === "const") {
// ExportDeclaration :: export VariableStatement
advance("const");
state.tokens.curr.fud({ inexport:true });
} else if (state.tokens.next.id === "function") {
// ExportDeclaration :: export Declaration
this.block = true;
advance("function");
exported[state.tokens.next.value] = ok;
state.tokens.next.exported = true;
state.syntax["function"].fud();
} else if (state.tokens.next.id === "class") {
// ExportDeclaration :: export Declaration
this.block = true;
advance("class");
exported[state.tokens.next.value] = ok;
state.tokens.next.exported = true;
state.syntax["class"].fud();
} else {
error("E024", state.tokens.next, state.tokens.next.value);
}
return this;
}).exps = true;
// Future Reserved Words
FutureReservedWord("abstract");
FutureReservedWord("boolean");
FutureReservedWord("byte");
FutureReservedWord("char");
FutureReservedWord("class", { es5: true, nud: classdef });
FutureReservedWord("double");
FutureReservedWord("enum", { es5: true });
FutureReservedWord("export", { es5: true });
FutureReservedWord("extends", { es5: true });
FutureReservedWord("final");
FutureReservedWord("float");
FutureReservedWord("goto");
FutureReservedWord("implements", { es5: true, strictOnly: true });
FutureReservedWord("import", { es5: true });
FutureReservedWord("int");
FutureReservedWord("interface", { es5: true, strictOnly: true });
FutureReservedWord("long");
FutureReservedWord("native");
FutureReservedWord("package", { es5: true, strictOnly: true });
FutureReservedWord("private", { es5: true, strictOnly: true });
FutureReservedWord("protected", { es5: true, strictOnly: true });
FutureReservedWord("public", { es5: true, strictOnly: true });
FutureReservedWord("short");
FutureReservedWord("static", { es5: true, strictOnly: true });
FutureReservedWord("super", { es5: true });
FutureReservedWord("synchronized");
FutureReservedWord("transient");
FutureReservedWord("volatile");
// this function is used to determine whether a squarebracket or a curlybracket
// expression is a comprehension array, destructuring assignment or a json value.
var lookupBlockType = function() {
var pn, pn1;
var i = -1;
var bracketStack = 0;
var ret = {};
if (checkPunctuators(state.tokens.curr, ["[", "{"]))
bracketStack += 1;
do {
pn = (i === -1) ? state.tokens.next : peek(i);
pn1 = peek(i + 1);
i = i + 1;
if (checkPunctuators(pn, ["[", "{"])) {
bracketStack += 1;
} else if (checkPunctuators(pn, ["]", "}"])) {
bracketStack -= 1;
}
if (pn.identifier && pn.value === "for" && bracketStack === 1) {
ret.isCompArray = true;
ret.notJson = true;
break;
}
if (checkPunctuators(pn, ["}", "]"]) && bracketStack === 0) {
if (pn1.value === "=") {
ret.isDestAssign = true;
ret.notJson = true;
break;
} else if (pn1.value === ".") {
ret.notJson = true;
break;
}
}
if (pn.value === ";") {
ret.isBlock = true;
ret.notJson = true;
}
} while (bracketStack > 0 && pn.id !== "(end)");
return ret;
};
function saveProperty(props, name, tkn, isClass, isStatic) {
var msg = ["key", "class method", "static class method"];
msg = msg[(isClass || false) + (isStatic || false)];
if (tkn.identifier) {
name = tkn.value;
}
if (props[name] && _.has(props, name)) {
warning("W075", state.tokens.next, msg, name);
} else {
props[name] = {};
}
props[name].basic = true;
props[name].basictkn = tkn;
}
/**
* @param {string} accessorType - Either "get" or "set"
* @param {object} props - a collection of all properties of the object to
* which the current accessor is being assigned
* @param {object} tkn - the identifier token representing the accessor name
* @param {boolean} isClass - whether the accessor is part of an ES6 Class
* definition
* @param {boolean} isStatic - whether the accessor is a static method
*/
function saveAccessor(accessorType, props, name, tkn, isClass, isStatic) {
var flagName = accessorType === "get" ? "getterToken" : "setterToken";
var msg = "";
if (isClass) {
if (isStatic) {
msg += "static ";
}
msg += accessorType + "ter method";
} else {
msg = "key";
}
state.tokens.curr.accessorType = accessorType;
state.nameStack.set(tkn);
if (props[name] && _.has(props, name)) {
if (props[name].basic || props[name][flagName]) {
warning("W075", state.tokens.next, msg, name);
}
} else {
props[name] = {};
}
props[name][flagName] = tkn;
}
function computedPropertyName() {
advance("[");
if (!state.option.esnext) {
warning("W119", state.tokens.curr, "computed property names");
}
var value = expression(10);
advance("]");
return value;
}
// Test whether a given token is a punctuator matching one of the specified values
function checkPunctuators(token, values) {
return token.type === "(punctuator)" && _.contains(values, token.value);
}
// Check whether this function has been reached for a destructuring assign with undeclared values
function destructuringAssignOrJsonValue() {
// lookup for the assignment (esnext only)
// if it has semicolons, it is a block, so go parse it as a block
// or it's not a block, but there are assignments, check for undeclared variables
var block = lookupBlockType();
if (block.notJson) {
if (!state.inESNext() && block.isDestAssign) {
warning("W104", state.tokens.curr, "destructuring assignment");
}
statements();
// otherwise parse json value
} else {
state.option.laxbreak = true;
state.jsonMode = true;
jsonValue();
}
}
// array comprehension parsing function
// parses and defines the three states of the list comprehension in order
// to avoid defining global variables, but keeping them to the list comprehension scope
// only. The order of the states are as follows:
// * "use" which will be the returned iterative part of the list comprehension
// * "define" which will define the variables local to the list comprehension
// * "filter" which will help filter out values
var arrayComprehension = function() {
var CompArray = function() {
this.mode = "use";
this.variables = [];
};
var _carrays = [];
var _current;
function declare(v) {
var l = _current.variables.filter(function(elt) {
// if it has, change its undef state
if (elt.value === v) {
elt.undef = false;
return v;
}
}).length;
return l !== 0;
}
function use(v) {
var l = _current.variables.filter(function(elt) {
// and if it has been defined
if (elt.value === v && !elt.undef) {
if (elt.unused === true) {
elt.unused = false;
}
return v;
}
}).length;
// otherwise we warn about it
return (l === 0);
}
return { stack: function() {
_current = new CompArray();
_carrays.push(_current);
},
unstack: function() {
_current.variables.filter(function(v) {
if (v.unused)
warning("W098", v.token, v.raw_text || v.value);
if (v.undef)
isundef(v.funct, "W117", v.token, v.value);
});
_carrays.splice(-1, 1);
_current = _carrays[_carrays.length - 1];
},
setState: function(s) {
if (_.contains(["use", "define", "generate", "filter"], s))
_current.mode = s;
},
check: function(v) {
if (!_current) {
return;
}
// When we are in "use" state of the list comp, we enqueue that var
if (_current && _current.mode === "use") {
if (use(v)) {
_current.variables.push({
funct: funct,
token: state.tokens.curr,
value: v,
undef: true,
unused: false
});
}
return true;
// When we are in "define" state of the list comp,
} else if (_current && _current.mode === "define") {
// check if the variable has been used previously
if (!declare(v)) {
_current.variables.push({
funct: funct,
token: state.tokens.curr,
value: v,
undef: false,
unused: true
});
}
return true;
// When we are in the "generate" state of the list comp,
} else if (_current && _current.mode === "generate") {
isundef(funct, "W117", state.tokens.curr, v);
return true;
// When we are in "filter" state,
} else if (_current && _current.mode === "filter") {
// we check whether current variable has been declared
if (use(v)) {
// if not we warn about it
isundef(funct, "W117", state.tokens.curr, v);
}
return true;
}
return false;
}
};
};
// Parse JSON
function jsonValue() {
function jsonObject() {
var o = {}, t = state.tokens.next;
advance("{");
if (state.tokens.next.id !== "}") {
for (;;) {
if (state.tokens.next.id === "(end)") {
error("E026", state.tokens.next, t.line);
} else if (state.tokens.next.id === "}") {
warning("W094", state.tokens.curr);
break;
} else if (state.tokens.next.id === ",") {
error("E028", state.tokens.next);
} else if (state.tokens.next.id !== "(string)") {
warning("W095", state.tokens.next, state.tokens.next.value);
}
if (o[state.tokens.next.value] === true) {
warning("W075", state.tokens.next, "key", state.tokens.next.value);
} else if ((state.tokens.next.value === "__proto__" &&
!state.option.proto) || (state.tokens.next.value === "__iterator__" &&
!state.option.iterator)) {
warning("W096", state.tokens.next, state.tokens.next.value);
} else {
o[state.tokens.next.value] = true;
}
advance();
advance(":");
jsonValue();
if (state.tokens.next.id !== ",") {
break;
}
advance(",");
}
}
advance("}");
}
function jsonArray() {
var t = state.tokens.next;
advance("[");
if (state.tokens.next.id !== "]") {
for (;;) {
if (state.tokens.next.id === "(end)") {
error("E027", state.tokens.next, t.line);
} else if (state.tokens.next.id === "]") {
warning("W094", state.tokens.curr);
break;
} else if (state.tokens.next.id === ",") {
error("E028", state.tokens.next);
}
jsonValue();
if (state.tokens.next.id !== ",") {
break;
}
advance(",");
}
}
advance("]");
}
switch (state.tokens.next.id) {
case "{":
jsonObject();
break;
case "[":
jsonArray();
break;
case "true":
case "false":
case "null":
case "(number)":
case "(string)":
advance();
break;
case "-":
advance("-");
advance("(number)");
break;
default:
error("E003", state.tokens.next);
}
}
var warnUnused = function(name, tkn, type, unused_opt) {
var line = tkn.line;
var chr = tkn.from;
var raw_name = tkn.raw_text || name;
if (unused_opt === undefined) {
unused_opt = state.option.unused;
}
if (unused_opt === true) {
unused_opt = "last-param";
}
var warnable_types = {
"vars": ["var"],
"last-param": ["var", "param"],
"strict": ["var", "param", "last-param"]
};
if (unused_opt) {
if (warnable_types[unused_opt] && warnable_types[unused_opt].indexOf(type) !== -1) {
if (!tkn.exported) {
warningAt("W098", line, chr, raw_name);
}
}
}
unuseds.push({
name: name,
line: line,
character: chr
});
};
var blockScope = function() {
var _current = {};
var _variables = [_current];
function _checkBlockLabels() {
for (var t in _current) {
var label = _current[t],
labelType = label["(type)"];
if (labelType === "unused" || (labelType === "const" && label["(unused)"])) {
if (state.option.unused) {
var tkn = _current[t]["(token)"];
// Don't report exported labels as unused
if (tkn.exported) {
continue;
}
warnUnused(t, tkn, "var");
}
}
}
}
function _getLabel(l) {
for (var i = _variables.length - 1 ; i >= 0; --i) {
if (_.has(_variables[i], l) && !_variables[i][l]["(shadowed)"]) {
return _variables[i];
}
}
}
return {
stack: function() {
_current = {};
_variables.push(_current);
},
unstack: function() {
_checkBlockLabels();
_variables.splice(_variables.length - 1, 1);
_current = _.last(_variables);
},
getlabel: _getLabel,
labeltype: function(l) {
// returns a labels type or null if not present
var block = _getLabel(l);
if (block) {
return block[l]["(type)"];
}
return null;
},
shadow: function(name) {
for (var i = _variables.length - 1; i >= 0; i--) {
if (_.has(_variables[i], name)) {
_variables[i][name]["(shadowed)"] = true;
}
}
},
unshadow: function(name) {
for (var i = _variables.length - 1; i >= 0; i--) {
if (_.has(_variables[i], name)) {
_variables[i][name]["(shadowed)"] = false;
}
}
},
atTop: function() {
return _variables.length === 1;
},
setExported: function(id) {
if (funct["(blockscope)"].atTop()) {
var item = _current[id];
if (item && item["(token)"]) {
item["(token)"].exported = true;
}
}
},
current: {
labeltype: function(t) {
if (_current[t]) {
return _current[t]["(type)"];
}
return null;
},
has: function(t) {
return _.has(_current, t);
},
add: function(t, type, tok) {
_current[t] = { "(type)" : type, "(token)": tok, "(shadowed)": false, "(unused)": true };
}
}
};
};
var escapeRegex = function(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
};
// The actual JSHINT function itself.
var itself = function(s, o, g) {
var i, k, x, reIgnoreStr, reIgnore;
var optionKeys;
var newOptionObj = {};
var newIgnoredObj = {};
o = _.clone(o);
state.reset();
if (o && o.scope) {
JSHINT.scope = o.scope;
} else {
JSHINT.errors = [];
JSHINT.undefs = [];
JSHINT.internals = [];
JSHINT.blacklist = {};
JSHINT.scope = "(main)";
}
predefined = Object.create(null);
combine(predefined, vars.ecmaIdentifiers[3]);
combine(predefined, vars.reservedVars);
combine(predefined, g || {});
declared = Object.create(null);
exported = Object.create(null);
function each(obj, cb) {
if (!obj)
return;
if (!Array.isArray(obj) && typeof obj === "object")
obj = Object.keys(obj);
obj.forEach(cb);
}
if (o) {
each(o.predef || null, function(item) {
var slice, prop;
if (item[0] === "-") {
slice = item.slice(1);
JSHINT.blacklist[slice] = slice;
// remove from predefined if there
delete predefined[slice];
} else {
prop = Object.getOwnPropertyDescriptor(o.predef, item);
predefined[item] = prop ? prop.value : false;
}
});
each(o.exported || null, function(item) {
exported[item] = true;
});
delete o.predef;
delete o.exported;
optionKeys = Object.keys(o);
for (x = 0; x < optionKeys.length; x++) {
if (/^-W\d{3}$/g.test(optionKeys[x])) {
newIgnoredObj[optionKeys[x].slice(1)] = true;
} else {
var optionKey = optionKeys[x];
newOptionObj[optionKey] = o[optionKey];
if (optionKey === "es5") {
if (o[optionKey]) {
warning("I003");
}
}
if (optionKeys[x] === "newcap" && o[optionKey] === false)
newOptionObj["(explicitNewcap)"] = true;
}
}
}
state.option = newOptionObj;
state.ignored = newIgnoredObj;
state.option.indent = state.option.indent || 4;
state.option.maxerr = state.option.maxerr || 50;
indent = 1;
global = Object.create(predefined);
scope = global;
funct = functor("(global)", null, scope, {
"(global)" : true,
"(blockscope)": blockScope(),
"(comparray)" : arrayComprehension(),
"(metrics)" : createMetrics(state.tokens.next)
});
functions = [funct];
urls = [];
stack = null;
member = {};
membersOnly = null;
implied = {};
inblock = false;
lookahead = [];
unuseds = [];
if (!isString(s) && !Array.isArray(s)) {
errorAt("E004", 0);
return false;
}
api = {
get isJSON() {
return state.jsonMode;
},
getOption: function(name) {
return state.option[name] || null;
},
getCache: function(name) {
return state.cache[name];
},
setCache: function(name, value) {
state.cache[name] = value;
},
warn: function(code, data) {
warningAt.apply(null, [ code, data.line, data.char ].concat(data.data));
},
on: function(names, listener) {
names.split(" ").forEach(function(name) {
emitter.on(name, listener);
}.bind(this));
}
};
emitter.removeAllListeners();
(extraModules || []).forEach(function(func) {
func(api);
});
state.tokens.prev = state.tokens.curr = state.tokens.next = state.syntax["(begin)"];
if (o && o.ignoreDelimiters) {
if (!Array.isArray(o.ignoreDelimiters)) {
o.ignoreDelimiters = [o.ignoreDelimiters];
}
o.ignoreDelimiters.forEach(function(delimiterPair) {
if (!delimiterPair.start || !delimiterPair.end)
return;
reIgnoreStr = escapeRegex(delimiterPair.start) +
"[\\s\\S]*?" +
escapeRegex(delimiterPair.end);
reIgnore = new RegExp(reIgnoreStr, "ig");
s = s.replace(reIgnore, function(match) {
return match.replace(/./g, " ");
});
});
}
lex = new Lexer(s);
lex.on("warning", function(ev) {
warningAt.apply(null, [ ev.code, ev.line, ev.character].concat(ev.data));
});
lex.on("error", function(ev) {
errorAt.apply(null, [ ev.code, ev.line, ev.character ].concat(ev.data));
});
lex.on("fatal", function(ev) {
quit("E041", ev.line, ev.from);
});
lex.on("Identifier", function(ev) {
emitter.emit("Identifier", ev);
});
lex.on("String", function(ev) {
emitter.emit("String", ev);
});
lex.on("Number", function(ev) {
emitter.emit("Number", ev);
});
lex.start();
// Check options
for (var name in o) {
if (_.has(o, name)) {
checkOption(name, state.tokens.curr);
}
}
assume();
// combine the passed globals after we've assumed all our options
combine(predefined, g || {});
//reset values
comma.first = true;
try {
advance();
switch (state.tokens.next.id) {
case "{":
case "[":
destructuringAssignOrJsonValue();
break;
default:
directives();
if (state.isStrict()) {
if (!state.option.globalstrict) {
if (!(state.option.module || state.option.node || state.option.phantom ||
state.option.browserify)) {
warning("W097", state.tokens.prev);
}
}
}
statements();
}
if (state.tokens.next.id !== "(end)") {
quit("E041", state.tokens.curr.line);
}
funct["(blockscope)"].unstack();
var markDefined = function(name, context) {
do {
if (typeof context[name] === "string") {
// JSHINT marks unused variables as 'unused' and
// unused function declaration as 'unction'. This
// code changes such instances back 'var' and
// 'closure' so that the code in JSHINT.data()
// doesn't think they're unused.
if (context[name] === "unused")
context[name] = "var";
else if (context[name] === "unction")
context[name] = "closure";
return true;
}
context = context["(context)"];
} while (context);
return false;
};
var clearImplied = function(name, line) {
if (!implied[name])
return;
var newImplied = [];
for (var i = 0; i < implied[name].length; i += 1) {
if (implied[name][i] !== line)
newImplied.push(implied[name][i]);
}
if (newImplied.length === 0)
delete implied[name];
else
implied[name] = newImplied;
};
var checkUnused = function(func, key) {
var type = func[key];
var tkn = func["(tokens)"][key];
if (key.charAt(0) === "(")
return;
if (type !== "unused" && type !== "unction")
return;
// Params are checked separately from other variables.
if (func["(params)"] && func["(params)"].indexOf(key) !== -1)
return;
// Variable is in global scope and defined as exported.
if (func["(global)"] && _.has(exported, key))
return;
warnUnused(key, tkn, "var");
};
// Check queued 'x is not defined' instances to see if they're still undefined.
for (i = 0; i < JSHINT.undefs.length; i += 1) {
k = JSHINT.undefs[i].slice(0);
if (markDefined(k[2].value, k[0]) || k[2].forgiveUndef) {
clearImplied(k[2].value, k[2].line);
} else if (state.option.undef) {
warning.apply(warning, k.slice(1));
}
}
functions.forEach(function(func) {
if (func["(unusedOption)"] === false) {
return;
}
for (var key in func) {
if (_.has(func, key)) {
checkUnused(func, key);
}
}
if (!func["(params)"])
return;
var params = func["(params)"].slice();
var param = params.pop();
var type, unused_opt;
while (param) {
type = func[param];
unused_opt = func["(unusedOption)"] || state.option.unused;
unused_opt = unused_opt === true ? "last-param" : unused_opt;
// 'undefined' is a special case for (function(window, undefined) { ... })();
// patterns.
if (param === "undefined")
return;
if (type === "unused" || type === "unction") {
warnUnused(param, func["(tokens)"][param], "param", func["(unusedOption)"]);
} else if (unused_opt === "last-param") {
return;
}
param = params.pop();
}
});
for (var key in declared) {
if (_.has(declared, key) && !_.has(global, key) && !_.has(exported, key)) {
warnUnused(key, declared[key], "var");
}
}
} catch (err) {
if (err && err.name === "JSHintError") {
var nt = state.tokens.next || {};
JSHINT.errors.push({
scope : "(main)",
raw : err.raw,
code : err.code,
reason : err.message,
line : err.line || nt.line,
character : err.character || nt.from
}, null);
} else {
throw err;
}
}
// Loop over the listed "internals", and check them as well.
if (JSHINT.scope === "(main)") {
o = o || {};
for (i = 0; i < JSHINT.internals.length; i += 1) {
k = JSHINT.internals[i];
o.scope = k.elem;
itself(k.value, o, g);
}
}
return JSHINT.errors.length === 0;
};
// Modules.
itself.addModule = function(func) {
extraModules.push(func);
};
itself.addModule(style.register);
// Data summary.
itself.data = function() {
var data = {
functions: [],
options: state.option
};
var implieds = [];
var members = [];
var fu, f, i, j, n, globals;
if (itself.errors.length) {
data.errors = itself.errors;
}
if (state.jsonMode) {
data.json = true;
}
for (n in implied) {
if (_.has(implied, n)) {
implieds.push({
name: n,
line: implied[n]
});
}
}
if (implieds.length > 0) {
data.implieds = implieds;
}
if (urls.length > 0) {
data.urls = urls;
}
globals = Object.keys(scope);
if (globals.length > 0) {
data.globals = globals;
}
for (i = 1; i < functions.length; i += 1) {
f = functions[i];
fu = {};
for (j = 0; j < functionicity.length; j += 1) {
fu[functionicity[j]] = [];
}
for (j = 0; j < functionicity.length; j += 1) {
if (fu[functionicity[j]].length === 0) {
delete fu[functionicity[j]];
}
}
fu.name = f["(name)"];
fu.param = f["(params)"];
fu.line = f["(line)"];
fu.character = f["(character)"];
fu.last = f["(last)"];
fu.lastcharacter = f["(lastcharacter)"];
fu.metrics = {
complexity: f["(metrics)"].ComplexityCount,
parameters: (f["(params)"] || []).length,
statements: f["(metrics)"].statementCount
};
data.functions.push(fu);
}
if (unuseds.length > 0) {
data.unused = unuseds;
}
members = [];
for (n in member) {
if (typeof member[n] === "number") {
data.member = member;
break;
}
}
return data;
};
itself.jshint = itself;
return itself;
}());
// Make JSHINT a Node module, if possible.
if (typeof exports === "object" && exports) {
exports.JSHINT = JSHINT;
}
},{"./lex.js":13,"./messages.js":14,"./options.js":16,"./reg.js":17,"./state.js":18,"./style.js":19,"./vars.js":20,"console-browserify":10,"events":5,"lodash":12}]},{},[]);
JSHINT = require('jshint').JSHINT;
if (typeof exports === 'object' && exports) exports.JSHINT = JSHINT;
}());