(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 var BeautylogPlugins; (function (BeautylogPlugins) { BeautylogPlugins.init = function () { var plugins = { smartenv: require("smartenv") }; return plugins; }; })(BeautylogPlugins || (BeautylogPlugins = {})); /// var tableHelpers = { makeRow: function (cellCounterArg, colorArg) { if (cellCounterArg === void 0) { cellCounterArg = 2; } if (colorArg === void 0) { colorArg = "cyan"; } var rowArray = []; for (var i = 0; i < (cellCounterArg); i++) { rowArray.push(String(i + 1).cyan); } return rowArray; } }; var ConsoleTable = (function () { function ConsoleTable(tableTypeArg, tableHeadArrayArg) { if (tableHeadArrayArg === void 0) { tableHeadArrayArg = tableHelpers.makeRow(); } switch (tableTypeArg) { case "checks": this.tableHead = ['Check Item:'.cyan, 'Status:'.cyan]; break; case "custom": this.tableHead = tableHeadArrayArg; break; default: break; } this.rows = []; this.type = tableTypeArg; } ConsoleTable.prototype.push = function (row) { this.rows.push(row); }; ConsoleTable.prototype.print = function () { var table = new BeautylogOsTable.cliTable({ head: this.tableHead }); for (var row in this.rows) { if (this.rows[row][1] == "success") { this.rows[row][1] = ' '.bgGreen + ' ' + this.rows[row][1]; } else if (this.rows[row][1] == "error") { this.rows[row][1] = ' '.bgRed + ' ' + this.rows[row][1]; } table.push(this.rows[row]); } ; console.log(table.toString()); }; return ConsoleTable; })(); /// var BeautylogNode; (function (BeautylogNode) { function init() { var colors = require("colors"); var clc = require("cli-color"); var beautylogNode = {}; //object to append to all public facing functions var localBl; // object to append to all private params and functions localBl = {}; localBl.dirPrefix = clc.bgXterm(39).xterm(231).bold(' DIR ') + ' '; localBl.errorPrefix = ' Error: '.bgRed.white.bold + ' '; localBl.infoPrefix = clc.bgXterm(198).xterm(231).bold(' INFO ') + ' '; localBl.normalPrefix = ' Log: '.bgCyan.white.bold + ' '; localBl.okPrefix = ' '.bgGreen + ' OK! '.bgBlack.green.bold + ' '; localBl.successPrefix = ' Success: '.bgGreen.white.bold + ' '; localBl.warnPrefix = ' '.bgYellow + ' Warn: '.bgBlack.yellow.bold + ' '; /** * * @param logText * @param logType * @returns {boolean} */ beautylogNode.log = function (logText, logType) { if (logText === void 0) { logText = 'empty log'; } if (logType === void 0) { logType = 'normal'; } try { switch (logType) { case 'dir': logText = localBl.dirPrefix + clc.xterm(26)(logText); break; case 'error': logText = localBl.errorPrefix + logText.red.bold; break; case 'info': logText = localBl.infoPrefix + clc.xterm(198)(logText); break; case 'normal': logText = localBl.normalPrefix + logText.cyan.bold; break; case 'ok': logText = localBl.okPrefix + logText.bold; break; case 'success': logText = localBl.successPrefix + logText.green.bold; break; case 'warn': logText = localBl.warnPrefix + logText.bold; break; case 'log': default: logText.blue.bold; console.log(('unknown logType for "' + logText + '"').red.bold); break; } console.log(logText); return true; } catch (error) { console.log(localBl.errorPrefix + 'You seem to have tried logging something strange'.red.bold + error); return false; } }; /** * logs an directory to console * @param logText * @returns {boolean} */ beautylogNode.dir = function (logText) { return beautylogNode.log(logText, 'dir'); }; /** * logs an error to console * @param logText * @returns {boolean} */ beautylogNode.error = function (logText) { return beautylogNode.log(logText, 'error'); }; /** * logs an info to console * @param logText * @returns {boolean} */ beautylogNode.info = function (logText) { return beautylogNode.log(logText, 'info'); }; /** * logs an 'OK!' message to console * @param logText * @returns {boolean} */ beautylogNode.ok = function (logText) { return beautylogNode.log(logText, 'ok'); }; /** * logs a success to console * @param logText string to log as error * @returns {boolean} */ beautylogNode.success = function (logText) { return beautylogNode.log(logText, 'success'); }; /** * logs a 'warn:' message to console * @param logText string to log as error * @returns {boolean} */ beautylogNode.warn = function (logText) { return beautylogNode.log(logText, 'warn'); }; beautylogNode.table = BeautylogOsTable.init(); return beautylogNode; } BeautylogNode.init = init; })(BeautylogNode || (BeautylogNode = {})); /// var BeautylogOsTable; (function (BeautylogOsTable) { function init() { BeautylogOsTable.cliTable = require("cli-table2"); var beautylogOsTable = {}; beautylogOsTable.new = function (typeArg, tableHeadArrayArg) { var newConsoleTable = new ConsoleTable(typeArg, tableHeadArrayArg); return newConsoleTable; }; return beautylogOsTable; } BeautylogOsTable.init = init; })(BeautylogOsTable || (BeautylogOsTable = {})); /// var BeautylogBrowser; (function (BeautylogBrowser) { function init() { var beautylogBrowser = {}; beautylogBrowser.log = function (message) { console.log('%c Log: %c ' + message, "background:#42A5F5;color:#ffffff", "color:#42A5F5;"); }; beautylogBrowser.info = function (message) { console.log('%c Info: %c ' + message, 'background:#EC407A;color:#ffffff;', 'color:#EC407A;'); }; beautylogBrowser.ok = function (message) { console.log('%c OK: %c ' + message, "background:#000000;color:#8BC34A;", "color:#000000;"); }; beautylogBrowser.success = function (message) { console.log('%c Success: %c ' + message, "background:#8BC34A;color:#ffffff;", "color:#8BC34A;"); }; beautylogBrowser.warn = function (message) { console.log('%c Warn: %c ' + message, "background:#000000;color:#FB8C00;", "color:#000000;"); }; return beautylogBrowser; } BeautylogBrowser.init = init; })(BeautylogBrowser || (BeautylogBrowser = {})); /// /// /// /// /// /// var plugins = BeautylogPlugins.init(); var beautylog = (function () { switch (plugins.smartenv.getEnv().runtimeEnv) { case "node": var beautylogOs = BeautylogNode.init(); return beautylogOs; break; case "browser": var beautylogBrowser = BeautylogBrowser.init(); return beautylogBrowser; break; default: console.log("something is strange about the platform in which you try to use beautylog"); break; } })(); module.exports = beautylog; },{"cli-color":9,"cli-table2":122,"colors":142,"smartenv":150}],3:[function(require,module,exports){ 'use strict'; var object = require('es5-ext/object/valid-object') , stringifiable = require('es5-ext/object/validate-stringifiable-value') , forOf = require('es6-iterator/for-of'); module.exports = function (text, style) { var result = ''; text = stringifiable(text); object(style); forOf(text, function (char) { result += style[char] || char; }); return result; }; },{"es5-ext/object/valid-object":69,"es5-ext/object/validate-stringifiable-value":71,"es6-iterator/for-of":82}],4:[function(require,module,exports){ (function (process){ 'use strict'; var d = require('d') , assign = require('es5-ext/object/assign') , forEach = require('es5-ext/object/for-each') , map = require('es5-ext/object/map') , primitiveSet = require('es5-ext/object/primitive-set') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , memoize = require('memoizee') , memoizeMethods = require('memoizee/methods') , sgr = require('./lib/sgr') , mods = sgr.mods , join = Array.prototype.join, defineProperty = Object.defineProperty , max = Math.max, min = Math.min , variantModes = primitiveSet('_fg', '_bg') , xtermMatch, getFn; // Some use cli-color as: console.log(clc.red('Error!')); // Which is inefficient as on each call it configures new clc object // with memoization we reuse once created object var memoized = memoize(function (scope, mod) { return defineProperty(getFn(), '_cliColorData', d(assign({}, scope._cliColorData, mod))); }); var proto = Object.create(Function.prototype, assign(map(mods, function (mod) { return d.gs(function () { return memoized(this, mod); }); }), memoizeMethods({ // xterm (255) color xterm: d(function (code) { code = isNaN(code) ? 255 : min(max(code, 0), 255); return defineProperty(getFn(), '_cliColorData', d(assign({}, this._cliColorData, { _fg: [xtermMatch ? xtermMatch[code] : ('38;5;' + code), 39] }))); }), bgXterm: d(function (code) { code = isNaN(code) ? 255 : min(max(code, 0), 255); return defineProperty(getFn(), '_cliColorData', d(assign({}, this._cliColorData, { _bg: [xtermMatch ? (xtermMatch[code] + 10) : ('48;5;' + code), 49] }))); }) }))); var getEndRe = memoize(function (code) { return new RegExp('\x1b\\[' + code + 'm', 'g'); }, { primitive: true }); if (process.platform === 'win32') xtermMatch = require('./lib/xterm-match'); getFn = function () { return setPrototypeOf(function self(/*…msg*/) { var start = '', end = '', msg = join.call(arguments, ' '), conf = self._cliColorData , hasAnsi = sgr.hasCSI(msg); forEach(conf, function (mod, key) { end = sgr(mod[1]) + end; start += sgr(mod[0]); if (hasAnsi) { msg = msg.replace(getEndRe(mod[1]), variantModes[key] ? sgr(mod[0]) : ''); } }, null, true); return start + msg + end; }, proto); }; module.exports = Object.defineProperties(getFn(), { xtermSupported: d(!xtermMatch), _cliColorData: d('', {}) }); }).call(this,require('_process')) },{"./lib/sgr":10,"./lib/xterm-match":12,"_process":149,"d":16,"es5-ext/object/assign":48,"es5-ext/object/for-each":54,"es5-ext/object/map":61,"es5-ext/object/primitive-set":64,"es5-ext/object/set-prototype-of":65,"memoizee":98,"memoizee/methods":105}],5:[function(require,module,exports){ 'use strict'; module.exports = '\x07'; },{}],6:[function(require,module,exports){ 'use strict'; var from = require('es5-ext/array/from') , iterable = require('es5-ext/iterable/validate-object') , stringifiable = require('es5-ext/object/validate-stringifiable') , pad = require('es5-ext/string/#/pad'); module.exports = function (rows/*, options*/) { var options = Object(arguments[1]), cols = []; return from(iterable(rows), function (row, index) { return from(iterable(row), function (str, index) { var col = cols[index]; if (!col) col = cols[index] = { width: 0 }; str = stringifiable(str); if (str.length > col.width) col.width = str.length; return str; }); }).map(function (row) { return row.map(function (item, index) { return pad.call(item, ' ', -cols[index].width); }).join((options.sep == null) ? ' | ' : options.sep); }).join('\n') + '\n'; }; },{"es5-ext/array/from":22,"es5-ext/iterable/validate-object":33,"es5-ext/object/validate-stringifiable":72,"es5-ext/string/#/pad":76}],7:[function(require,module,exports){ 'use strict'; module.exports = { screen: '\x1b[2J', screenLeft: '\x1b[1J', screenRight: '\x1b[J', line: '\x1b[2K', lineLeft: '\x1b[1K', lineRight: '\x1b[K' }; },{}],8:[function(require,module,exports){ 'use strict'; /* * get actual length of ANSI-formatted string */ var strip = require('./strip'); module.exports = function (str) { return strip(str).length; }; },{"./strip":119}],9:[function(require,module,exports){ 'use strict'; var d = require('d'); module.exports = Object.defineProperties(require('./bare'), { windowSize: d(require('./window-size')), erase: d(require('./erase')), move: d(require('./move')), beep: d(require('./beep')), columns: d(require('./columns')), strip: d(require('./strip')), getStrippedLength: d(require('./get-stripped-length')), slice: d(require('./slice')), throbber: d(require('./throbber')), reset: d(require('./reset')), art: d(require('./art')) }); },{"./art":3,"./bare":4,"./beep":5,"./columns":6,"./erase":7,"./get-stripped-length":8,"./move":13,"./reset":117,"./slice":118,"./strip":119,"./throbber":120,"./window-size":121,"d":16}],10:[function(require,module,exports){ 'use strict'; /* CSI - control sequence introducer */ /* SGR - set graphic rendition */ var assign = require('es5-ext/object/assign') , includes = require('es5-ext/string/#/contains') , forOwn = require('es5-ext/object/for-each') , onlyKey = require('es5-ext/object/first-key') , forEachRight = require('es5-ext/array/#/for-each-right') , uniq = require('es5-ext/array/#/uniq.js'); var CSI = '\x1b['; var sgr = function (code) { return CSI + code + 'm'; }; sgr.CSI = CSI; var mods = assign({ // Style bold: { _bold: [1, 22] }, italic: { _italic: [3, 23] }, underline: { _underline: [4, 24] }, blink: { _blink: [5, 25] }, inverse: { _inverse: [7, 27] }, strike: { _strike: [9, 29] } // Color }, ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] .reduce(function (obj, color, index) { // foreground obj[color] = { _fg: [30 + index, 39] }; obj[color + 'Bright'] = { _fg: [90 + index, 39] }; // background obj['bg' + color[0].toUpperCase() + color.slice(1)] = { _bg: [40 + index, 49] }; obj['bg' + color[0].toUpperCase() + color.slice(1) + 'Bright'] = { _bg: [100 + index, 49] }; return obj; }, {})); sgr.mods = mods; sgr.openers = {}; sgr.closers = {}; forOwn(mods, function (mod) { var modPair = mod[onlyKey(mod)]; sgr.openers[modPair[0]] = modPair; sgr.closers[modPair[1]] = modPair; }); sgr.openStyle = function (mods, code) { mods.push(sgr.openers[code]); }; sgr.closeStyle = function (mods, code) { forEachRight.call(mods, function (modPair, index) { if (modPair[1] === code) { mods.splice(index, 1); } }); }; /* prepend openers */ sgr.prepend = function (mods) { return mods.map(function (modPair, key) { return sgr(modPair[0]); }); }; /* complete non-closed openers with corresponding closers */ sgr.complete = function (mods, closerCodes) { closerCodes.forEach(function (code) { sgr.closeStyle(mods, code); }); // mods must be closed from the last opened to first opened mods = mods.reverse(); mods = mods.map(function (modPair, key) { return modPair[1]; }); // one closer can close many openers (31, 32 -> 39) mods = uniq.call(mods); return mods.map(sgr); }; var hasCSI = function (str) { return includes.call(str, CSI); }; sgr.hasCSI = hasCSI; var extractCode = function (csi) { var code = csi.slice(2, -1); code = Number(code); return code; }; sgr.extractCode = extractCode; module.exports = sgr; },{"es5-ext/array/#/for-each-right":20,"es5-ext/array/#/uniq.js":21,"es5-ext/object/assign":48,"es5-ext/object/first-key":53,"es5-ext/object/for-each":54,"es5-ext/string/#/contains":73}],11:[function(require,module,exports){ 'use strict'; module.exports = [ "000000", "800000", "008000", "808000", "000080", "800080", "008080", "c0c0c0", "808080", "ff0000", "00ff00", "ffff00", "0000ff", "ff00ff", "00ffff", "ffffff", "000000", "00005f", "000087", "0000af", "0000d7", "0000ff", "005f00", "005f5f", "005f87", "005faf", "005fd7", "005fff", "008700", "00875f", "008787", "0087af", "0087d7", "0087ff", "00af00", "00af5f", "00af87", "00afaf", "00afd7", "00afff", "00d700", "00d75f", "00d787", "00d7af", "00d7d7", "00d7ff", "00ff00", "00ff5f", "00ff87", "00ffaf", "00ffd7", "00ffff", "5f0000", "5f005f", "5f0087", "5f00af", "5f00d7", "5f00ff", "5f5f00", "5f5f5f", "5f5f87", "5f5faf", "5f5fd7", "5f5fff", "5f8700", "5f875f", "5f8787", "5f87af", "5f87d7", "5f87ff", "5faf00", "5faf5f", "5faf87", "5fafaf", "5fafd7", "5fafff", "5fd700", "5fd75f", "5fd787", "5fd7af", "5fd7d7", "5fd7ff", "5fff00", "5fff5f", "5fff87", "5fffaf", "5fffd7", "5fffff", "870000", "87005f", "870087", "8700af", "8700d7", "8700ff", "875f00", "875f5f", "875f87", "875faf", "875fd7", "875fff", "878700", "87875f", "878787", "8787af", "8787d7", "8787ff", "87af00", "87af5f", "87af87", "87afaf", "87afd7", "87afff", "87d700", "87d75f", "87d787", "87d7af", "87d7d7", "87d7ff", "87ff00", "87ff5f", "87ff87", "87ffaf", "87ffd7", "87ffff", "af0000", "af005f", "af0087", "af00af", "af00d7", "af00ff", "af5f00", "af5f5f", "af5f87", "af5faf", "af5fd7", "af5fff", "af8700", "af875f", "af8787", "af87af", "af87d7", "af87ff", "afaf00", "afaf5f", "afaf87", "afafaf", "afafd7", "afafff", "afd700", "afd75f", "afd787", "afd7af", "afd7d7", "afd7ff", "afff00", "afff5f", "afff87", "afffaf", "afffd7", "afffff", "d70000", "d7005f", "d70087", "d700af", "d700d7", "d700ff", "d75f00", "d75f5f", "d75f87", "d75faf", "d75fd7", "d75fff", "d78700", "d7875f", "d78787", "d787af", "d787d7", "d787ff", "d7af00", "d7af5f", "d7af87", "d7afaf", "d7afd7", "d7afff", "d7d700", "d7d75f", "d7d787", "d7d7af", "d7d7d7", "d7d7ff", "d7ff00", "d7ff5f", "d7ff87", "d7ffaf", "d7ffd7", "d7ffff", "ff0000", "ff005f", "ff0087", "ff00af", "ff00d7", "ff00ff", "ff5f00", "ff5f5f", "ff5f87", "ff5faf", "ff5fd7", "ff5fff", "ff8700", "ff875f", "ff8787", "ff87af", "ff87d7", "ff87ff", "ffaf00", "ffaf5f", "ffaf87", "ffafaf", "ffafd7", "ffafff", "ffd700", "ffd75f", "ffd787", "ffd7af", "ffd7d7", "ffd7ff", "ffff00", "ffff5f", "ffff87", "ffffaf", "ffffd7", "ffffff", "080808", "121212", "1c1c1c", "262626", "303030", "3a3a3a", "444444", "4e4e4e", "585858", "626262", "6c6c6c", "767676", "808080", "8a8a8a", "949494", "9e9e9e", "a8a8a8", "b2b2b2", "bcbcbc", "c6c6c6", "d0d0d0", "dadada", "e4e4e4", "eeeeee" ]; },{}],12:[function(require,module,exports){ 'use strict'; var push = Array.prototype.push, reduce = Array.prototype.reduce, abs = Math.abs , colors, match, result, i; colors = require('./xterm-colors').map(function (color) { return { r: parseInt(color.slice(0, 2), 16), g: parseInt(color.slice(2, 4), 16), b: parseInt(color.slice(4), 16) }; }); match = colors.slice(0, 16); module.exports = result = []; i = 0; while (i < 8) { result.push(30 + i++); } i = 0; while (i < 8) { result.push(90 + i++); } push.apply(result, colors.slice(16).map(function (data) { var index, diff = Infinity; match.every(function (match, i) { var ndiff = reduce.call('rgb', function (diff, channel) { diff += abs(match[channel] - data[channel]); return diff; }, 0); if (ndiff < diff) { index = i; diff = ndiff; } return ndiff; }); return result[index]; })); },{"./xterm-colors":11}],13:[function(require,module,exports){ 'use strict'; var d = require('d') , trunc = require('es5-ext/math/trunc') , up, down, right, left , abs = Math.abs, floor = Math.floor, max = Math.max; var getMove = function (control) { return function (num) { num = isNaN(num) ? 0 : max(floor(num), 0); return num ? ('\x1b[' + num + control) : ''; }; }; module.exports = Object.defineProperties(function (x, y) { x = isNaN(x) ? 0 : floor(x); y = isNaN(y) ? 0 : floor(y); return ((x > 0) ? right(x) : left(-x)) + ((y > 0) ? down(y) : up(-y)); }, { up: d(up = getMove('A')), down: d(down = getMove('B')), right: d(right = getMove('C')), left: d(left = getMove('D')), to: d(function (x, y) { x = isNaN(x) ? 1 : (max(floor(x), 0) + 1); y = isNaN(y) ? 1 : (max(floor(y), 0) + 1); return '\x1b[' + y + ';' + x + 'H'; }), lines: d(function (n) { var dir; n = trunc(n) || 0; dir = (n >= 0) ? 'E' : 'F'; n = floor(abs(n)); return '\x1b[' + n + dir; }) }); },{"d":16,"es5-ext/math/trunc":37}],14:[function(require,module,exports){ 'use strict'; module.exports = function () { return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; }; },{}],15:[function(require,module,exports){ 'use strict'; var copy = require('es5-ext/object/copy') , map = require('es5-ext/object/map') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , bind = Function.prototype.bind, defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; define = function (name, desc, bindTo) { var value = validValue(desc) && callable(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (hasOwnProperty.call(this, name)) return value; desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); defineProperty(this, name, desc); return this[name]; }; return dgs; }; module.exports = function (props/*, bindTo*/) { var bindTo = arguments[1]; return map(props, function (desc, name) { return define(name, desc, bindTo); }); }; },{"es5-ext/object/copy":51,"es5-ext/object/map":61,"es5-ext/object/valid-callable":68,"es5-ext/object/valid-value":70}],16:[function(require,module,exports){ 'use strict'; var assign = require('es5-ext/object/assign') , normalizeOpts = require('es5-ext/object/normalize-options') , isCallable = require('es5-ext/object/is-callable') , contains = require('es5-ext/string/#/contains') , d; d = module.exports = function (dscr, value/*, options*/) { var c, e, w, options, desc; if ((arguments.length < 2) || (typeof dscr !== 'string')) { options = value; value = dscr; dscr = null; } else { options = arguments[2]; } if (dscr == null) { c = w = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); w = contains.call(dscr, 'w'); } desc = { value: value, configurable: c, enumerable: e, writable: w }; return !options ? desc : assign(normalizeOpts(options), desc); }; d.gs = function (dscr, get, set/*, options*/) { var c, e, options, desc; if (typeof dscr !== 'string') { options = set; set = get; get = dscr; dscr = null; } else { options = arguments[3]; } if (get == null) { get = undefined; } else if (!isCallable(get)) { options = get; get = set = undefined; } else if (set == null) { set = undefined; } else if (!isCallable(set)) { options = set; set = undefined; } if (dscr == null) { c = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); } desc = { get: get, set: set, configurable: c, enumerable: e }; return !options ? desc : assign(normalizeOpts(options), desc); }; },{"es5-ext/object/assign":48,"es5-ext/object/is-callable":56,"es5-ext/object/normalize-options":63,"es5-ext/string/#/contains":73}],17:[function(require,module,exports){ 'use strict'; var map = require('es5-ext/object/map') , isCallable = require('es5-ext/object/is-callable') , validValue = require('es5-ext/object/valid-value') , contains = require('es5-ext/string/#/contains') , call = Function.prototype.call , defineProperty = Object.defineProperty , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor , getPrototypeOf = Object.getPrototypeOf , hasOwnProperty = Object.prototype.hasOwnProperty , cacheDesc = { configurable: false, enumerable: false, writable: false, value: null } , define; define = function (name, options) { var value, dgs, cacheName, desc, writable = false, resolvable , flat; options = Object(validValue(options)); cacheName = options.cacheName; flat = options.flat; if (cacheName == null) cacheName = name; delete options.cacheName; value = options.value; resolvable = isCallable(value); delete options.value; dgs = { configurable: Boolean(options.configurable), enumerable: Boolean(options.enumerable) }; if (name !== cacheName) { dgs.get = function () { if (hasOwnProperty.call(this, cacheName)) return this[cacheName]; cacheDesc.value = resolvable ? call.call(value, this, options) : value; cacheDesc.writable = writable; defineProperty(this, cacheName, cacheDesc); cacheDesc.value = null; if (desc) defineProperty(this, name, desc); return this[cacheName]; }; } else if (!flat) { dgs.get = function self() { var ownDesc; if (hasOwnProperty.call(this, name)) { ownDesc = getOwnPropertyDescriptor(this, name); // It happens in Safari, that getter is still called after property // was defined with a value, following workarounds that if (ownDesc.hasOwnProperty('value')) return ownDesc.value; if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) { return ownDesc.get.call(this); } return value; } desc.value = resolvable ? call.call(value, this, options) : value; defineProperty(this, name, desc); desc.value = null; return this[name]; }; } else { dgs.get = function self() { var base = this, ownDesc; if (hasOwnProperty.call(this, name)) { // It happens in Safari, that getter is still called after property // was defined with a value, following workarounds that ownDesc = getOwnPropertyDescriptor(this, name); if (ownDesc.hasOwnProperty('value')) return ownDesc.value; if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) { return ownDesc.get.call(this); } } while (!hasOwnProperty.call(base, name)) base = getPrototypeOf(base); desc.value = resolvable ? call.call(value, base, options) : value; defineProperty(base, name, desc); desc.value = null; return base[name]; }; } dgs.set = function (value) { dgs.get.call(this); this[cacheName] = value; }; if (options.desc) { desc = { configurable: contains.call(options.desc, 'c'), enumerable: contains.call(options.desc, 'e') }; if (cacheName === name) { desc.writable = contains.call(options.desc, 'w'); desc.value = null; } else { writable = contains.call(options.desc, 'w'); desc.get = dgs.get; desc.set = dgs.set; } delete options.desc; } else if (cacheName === name) { desc = { configurable: Boolean(options.configurable), enumerable: Boolean(options.enumerable), writable: Boolean(options.writable), value: null }; } delete options.configurable; delete options.enumerable; delete options.writable; return dgs; }; module.exports = function (props) { return map(props, function (desc, name) { return define(name, desc); }); }; },{"es5-ext/object/is-callable":56,"es5-ext/object/map":61,"es5-ext/object/valid-value":70,"es5-ext/string/#/contains":73}],18:[function(require,module,exports){ // Inspired by Google Closure: // http://closure-library.googlecode.com/svn/docs/ // closure_goog_array_array.js.html#goog.array.clear 'use strict'; var value = require('../../object/valid-value'); module.exports = function () { value(this).length = 0; return this; }; },{"../../object/valid-value":70}],19:[function(require,module,exports){ 'use strict'; var toPosInt = require('../../number/to-pos-integer') , value = require('../../object/valid-value') , indexOf = Array.prototype.indexOf , hasOwnProperty = Object.prototype.hasOwnProperty , abs = Math.abs, floor = Math.floor; module.exports = function (searchElement/*, fromIndex*/) { var i, l, fromIndex, val; if (searchElement === searchElement) { //jslint: ignore return indexOf.apply(this, arguments); } l = toPosInt(value(this).length); fromIndex = arguments[1]; if (isNaN(fromIndex)) fromIndex = 0; else if (fromIndex >= 0) fromIndex = floor(fromIndex); else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); for (i = fromIndex; i < l; ++i) { if (hasOwnProperty.call(this, i)) { val = this[i]; if (val !== val) return i; //jslint: ignore } } return -1; }; },{"../../number/to-pos-integer":46,"../../object/valid-value":70}],20:[function(require,module,exports){ 'use strict'; var toPosInt = require('../../number/to-pos-integer') , callable = require('../../object/valid-callable') , value = require('../../object/valid-value') , hasOwnProperty = Object.prototype.hasOwnProperty , call = Function.prototype.call; module.exports = function (cb/*, thisArg*/) { var i, self, thisArg; self = Object(value(this)); callable(cb); thisArg = arguments[1]; for (i = (toPosInt(self.length) - 1); i >= 0; --i) { if (hasOwnProperty.call(self, i)) call.call(cb, thisArg, self[i], i, self); } }; },{"../../number/to-pos-integer":46,"../../object/valid-callable":68,"../../object/valid-value":70}],21:[function(require,module,exports){ 'use strict'; var indexOf = require('./e-index-of') , filter = Array.prototype.filter , isFirst; isFirst = function (value, index) { return indexOf.call(this, value) === index; }; module.exports = function () { return filter.call(this, isFirst, this); }; },{"./e-index-of":19}],22:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Array.from : require('./shim'); },{"./is-implemented":23,"./shim":24}],23:[function(require,module,exports){ 'use strict'; module.exports = function () { var from = Array.from, arr, result; if (typeof from !== 'function') return false; arr = ['raz', 'dwa']; result = from(arr); return Boolean(result && (result !== arr) && (result[1] === 'dwa')); }; },{}],24:[function(require,module,exports){ 'use strict'; var iteratorSymbol = require('es6-symbol').iterator , isArguments = require('../../function/is-arguments') , isFunction = require('../../function/is-function') , toPosInt = require('../../number/to-pos-integer') , callable = require('../../object/valid-callable') , validValue = require('../../object/valid-value') , isString = require('../../string/is-string') , isArray = Array.isArray, call = Function.prototype.call , desc = { configurable: true, enumerable: true, writable: true, value: null } , defineProperty = Object.defineProperty; module.exports = function (arrayLike/*, mapFn, thisArg*/) { var mapFn = arguments[1], thisArg = arguments[2], Constructor, i, j, arr, l, code, iterator , result, getIterator, value; arrayLike = Object(validValue(arrayLike)); if (mapFn != null) callable(mapFn); if (!this || (this === Array) || !isFunction(this)) { // Result: Plain array if (!mapFn) { if (isArguments(arrayLike)) { // Source: Arguments l = arrayLike.length; if (l !== 1) return Array.apply(null, arrayLike); arr = new Array(1); arr[0] = arrayLike[0]; return arr; } if (isArray(arrayLike)) { // Source: Array arr = new Array(l = arrayLike.length); for (i = 0; i < l; ++i) arr[i] = arrayLike[i]; return arr; } } arr = []; } else { // Result: Non plain array Constructor = this; } if (!isArray(arrayLike)) { if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { // Source: Iterator iterator = callable(getIterator).call(arrayLike); if (Constructor) arr = new Constructor(); result = iterator.next(); i = 0; while (!result.done) { value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; if (!Constructor) { arr[i] = value; } else { desc.value = value; defineProperty(arr, i, desc); } result = iterator.next(); ++i; } l = i; } else if (isString(arrayLike)) { // Source: String l = arrayLike.length; if (Constructor) arr = new Constructor(); for (i = 0, j = 0; i < l; ++i) { value = arrayLike[i]; if ((i + 1) < l) { code = value.charCodeAt(0); if ((code >= 0xD800) && (code <= 0xDBFF)) value += arrayLike[++i]; } value = mapFn ? call.call(mapFn, thisArg, value, j) : value; if (!Constructor) { arr[j] = value; } else { desc.value = value; defineProperty(arr, j, desc); } ++j; } l = j; } } if (l === undefined) { // Source: array or array-like l = toPosInt(arrayLike.length); if (Constructor) arr = new Constructor(l); for (i = 0; i < l; ++i) { value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; if (!Constructor) { arr[i] = value; } else { desc.value = value; defineProperty(arr, i, desc); } } } if (Constructor) { desc.value = null; arr.length = l; } return arr; }; },{"../../function/is-arguments":29,"../../function/is-function":30,"../../number/to-pos-integer":46,"../../object/valid-callable":68,"../../object/valid-value":70,"../../string/is-string":80,"es6-symbol":40}],25:[function(require,module,exports){ 'use strict'; var from = require('./from') , isArray = Array.isArray; module.exports = function (arrayLike) { return isArray(arrayLike) ? arrayLike : from(arrayLike); }; },{"./from":22}],26:[function(require,module,exports){ 'use strict'; var assign = require('../object/assign') , captureStackTrace = Error.captureStackTrace; exports = module.exports = function (message/*, code, ext*/) { var err = new Error(), code = arguments[1], ext = arguments[2]; if (ext == null) { if (code && (typeof code === 'object')) { ext = code; code = null; } } if (ext != null) assign(err, ext); err.message = String(message); if (code != null) err.code = String(code); if (captureStackTrace) captureStackTrace(err, exports); return err; }; },{"../object/assign":48}],27:[function(require,module,exports){ 'use strict'; var callable = require('../../object/valid-callable') , aFrom = require('../../array/from') , apply = Function.prototype.apply, call = Function.prototype.call , callFn = function (arg, fn) { return call.call(fn, this, arg); }; module.exports = function (fn/*, …fnn*/) { var fns, first; if (!fn) callable(fn); fns = [this].concat(aFrom(arguments)); fns.forEach(callable); fns = fns.reverse(); first = fns[0]; fns = fns.slice(1); return function (arg) { return fns.reduce(callFn, apply.call(first, this, arguments)); }; }; },{"../../array/from":22,"../../object/valid-callable":68}],28:[function(require,module,exports){ 'use strict'; var toPosInt = require('../number/to-pos-integer') , test = function (a, b) {}, desc, defineProperty , generate, mixin; try { Object.defineProperty(test, 'length', { configurable: true, writable: false, enumerable: false, value: 1 }); } catch (ignore) {} if (test.length === 1) { // ES6 desc = { configurable: true, writable: false, enumerable: false }; defineProperty = Object.defineProperty; module.exports = function (fn, length) { length = toPosInt(length); if (fn.length === length) return fn; desc.value = length; return defineProperty(fn, 'length', desc); }; } else { mixin = require('../object/mixin'); generate = (function () { var cache = []; return function (l) { var args, i = 0; if (cache[l]) return cache[l]; args = []; while (l--) args.push('a' + (++i).toString(36)); return new Function('fn', 'return function (' + args.join(', ') + ') { return fn.apply(this, arguments); };'); }; }()); module.exports = function (src, length) { var target; length = toPosInt(length); if (src.length === length) return src; target = generate(length)(src); try { mixin(target, src); } catch (ignore) {} return target; }; } },{"../number/to-pos-integer":46,"../object/mixin":62}],29:[function(require,module,exports){ 'use strict'; var toString = Object.prototype.toString , id = toString.call((function () { return arguments; }())); module.exports = function (x) { return (toString.call(x) === id); }; },{}],30:[function(require,module,exports){ 'use strict'; var toString = Object.prototype.toString , id = toString.call(require('./noop')); module.exports = function (f) { return (typeof f === "function") && (toString.call(f) === id); }; },{"./noop":31}],31:[function(require,module,exports){ 'use strict'; module.exports = function () {}; },{}],32:[function(require,module,exports){ 'use strict'; var iteratorSymbol = require('es6-symbol').iterator , isArrayLike = require('../object/is-array-like'); module.exports = function (x) { if (x == null) return false; if (typeof x[iteratorSymbol] === 'function') return true; return isArrayLike(x); }; },{"../object/is-array-like":55,"es6-symbol":40}],33:[function(require,module,exports){ 'use strict'; var isObject = require('../object/is-object') , is = require('./is'); module.exports = function (x) { if (is(x) && isObject(x)) return x; throw new TypeError(x + " is not an iterable or array-like object"); }; },{"../object/is-object":57,"./is":32}],34:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Math.sign : require('./shim'); },{"./is-implemented":35,"./shim":36}],35:[function(require,module,exports){ 'use strict'; module.exports = function () { var sign = Math.sign; if (typeof sign !== 'function') return false; return ((sign(10) === 1) && (sign(-20) === -1)); }; },{}],36:[function(require,module,exports){ 'use strict'; module.exports = function (value) { value = Number(value); if (isNaN(value) || (value === 0)) return value; return (value > 0) ? 1 : -1; }; },{}],37:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Math.trunc : require('./shim'); },{"./is-implemented":38,"./shim":39}],38:[function(require,module,exports){ 'use strict'; module.exports = function () { var trunc = Math.trunc; if (typeof trunc !== 'function') return false; return (trunc(13.67) === 13) && (trunc(-13.67) === -13); }; },{}],39:[function(require,module,exports){ 'use strict'; var floor = Math.floor; module.exports = function (x) { if (isNaN(x)) return NaN; x = Number(x); if (x === 0) return x; if (x === Infinity) return Infinity; if (x === -Infinity) return -Infinity; if (x > 0) return floor(x); return -floor(-x); }; },{}],40:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); },{"./is-implemented":41,"./polyfill":43}],41:[function(require,module,exports){ 'use strict'; module.exports = function () { var symbol; if (typeof Symbol !== 'function') return false; symbol = Symbol('test symbol'); try { String(symbol); } catch (e) { return false; } if (typeof Symbol.iterator === 'symbol') return true; // Return 'true' for polyfills if (typeof Symbol.isConcatSpreadable !== 'object') return false; if (typeof Symbol.iterator !== 'object') return false; if (typeof Symbol.toPrimitive !== 'object') return false; if (typeof Symbol.toStringTag !== 'object') return false; if (typeof Symbol.unscopables !== 'object') return false; return true; }; },{}],42:[function(require,module,exports){ 'use strict'; module.exports = function (x) { return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; }; },{}],43:[function(require,module,exports){ // ES2015 Symbol polyfill for environments that do not support it (or partially support it_ 'use strict'; var d = require('d') , validateSymbol = require('./validate-symbol') , create = Object.create, defineProperties = Object.defineProperties , defineProperty = Object.defineProperty, objPrototype = Object.prototype , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null); if (typeof Symbol === 'function') NativeSymbol = Symbol; var generateName = (function () { var created = create(null); return function (desc) { var postfix = 0, name, ie11BugWorkaround; while (created[desc + (postfix || '')]) ++postfix; desc += (postfix || ''); created[desc] = true; name = '@@' + desc; defineProperty(objPrototype, name, d.gs(null, function (value) { // For IE11 issue see: // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ // ie11-broken-getters-on-dom-objects // https://github.com/medikoo/es6-symbol/issues/12 if (ie11BugWorkaround) return; ie11BugWorkaround = true; defineProperty(this, name, d(value)); ie11BugWorkaround = false; })); return name; }; }()); // Internal constructor (not one exposed) for creating Symbol instances. // This one is used to ensure that `someSymbol instanceof Symbol` always return false HiddenSymbol = function Symbol(description) { if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor'); return SymbolPolyfill(description); }; // Exposed `Symbol` constructor // (returns instances of HiddenSymbol) module.exports = SymbolPolyfill = function Symbol(description) { var symbol; if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor'); symbol = create(HiddenSymbol.prototype); description = (description === undefined ? '' : String(description)); return defineProperties(symbol, { __description__: d('', description), __name__: d('', generateName(description)) }); }; defineProperties(SymbolPolyfill, { for: d(function (key) { if (globalSymbols[key]) return globalSymbols[key]; return (globalSymbols[key] = SymbolPolyfill(String(key))); }), keyFor: d(function (s) { var key; validateSymbol(s); for (key in globalSymbols) if (globalSymbols[key] === s) return key; }), // If there's native implementation of given symbol, let's fallback to it // to ensure proper interoperability with other native functions e.g. Array.from hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')), isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) || SymbolPolyfill('isConcatSpreadable')), iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')), match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')), replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')), search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')), species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')), split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')), toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')), toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')), unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables')) }); // Internal tweaks for real symbol producer defineProperties(HiddenSymbol.prototype, { constructor: d(SymbolPolyfill), toString: d('', function () { return this.__name__; }) }); // Proper implementation of methods exposed on Symbol.prototype // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype defineProperties(SymbolPolyfill.prototype, { toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), valueOf: d(function () { return validateSymbol(this); }) }); defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () { return validateSymbol(this); })); defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol')); // Proper implementaton of toPrimitive and toStringTag for returned symbol instances defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])); // Note: It's important to define `toPrimitive` as last one, as some implementations // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) // And that may invoke error in definition flow: // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])); },{"./validate-symbol":44,"d":16}],44:[function(require,module,exports){ 'use strict'; var isSymbol = require('./is-symbol'); module.exports = function (value) { if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); return value; }; },{"./is-symbol":42}],45:[function(require,module,exports){ 'use strict'; var sign = require('../math/sign') , abs = Math.abs, floor = Math.floor; module.exports = function (value) { if (isNaN(value)) return 0; value = Number(value); if ((value === 0) || !isFinite(value)) return value; return sign(value) * floor(abs(value)); }; },{"../math/sign":34}],46:[function(require,module,exports){ 'use strict'; var toInteger = require('./to-integer') , max = Math.max; module.exports = function (value) { return max(0, toInteger(value)); }; },{"./to-integer":45}],47:[function(require,module,exports){ // Internal method, used by iteration functions. // Calls a function for each key-value pair found in object // Optionally takes compareFn to iterate object in specific order 'use strict'; var callable = require('./valid-callable') , value = require('./valid-value') , bind = Function.prototype.bind, call = Function.prototype.call, keys = Object.keys , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (method, defVal) { return function (obj, cb/*, thisArg, compareFn*/) { var list, thisArg = arguments[2], compareFn = arguments[3]; obj = Object(value(obj)); callable(cb); list = keys(obj); if (compareFn) { list.sort((typeof compareFn === 'function') ? bind.call(compareFn, obj) : undefined); } if (typeof method !== 'function') method = list[method]; return call.call(method, list, function (key, index) { if (!propertyIsEnumerable.call(obj, key)) return defVal; return call.call(cb, thisArg, obj[key], key, obj, index); }); }; }; },{"./valid-callable":68,"./valid-value":70}],48:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.assign : require('./shim'); },{"./is-implemented":49,"./shim":50}],49:[function(require,module,exports){ 'use strict'; module.exports = function () { var assign = Object.assign, obj; if (typeof assign !== 'function') return false; obj = { foo: 'raz' }; assign(obj, { bar: 'dwa' }, { trzy: 'trzy' }); return (obj.foo + obj.bar + obj.trzy) === 'razdwatrzy'; }; },{}],50:[function(require,module,exports){ 'use strict'; var keys = require('../keys') , value = require('../valid-value') , max = Math.max; module.exports = function (dest, src/*, …srcn*/) { var error, i, l = max(arguments.length, 2), assign; dest = Object(value(dest)); assign = function (key) { try { dest[key] = src[key]; } catch (e) { if (!error) error = e; } }; for (i = 1; i < l; ++i) { src = arguments[i]; keys(src).forEach(assign); } if (error !== undefined) throw error; return dest; }; },{"../keys":58,"../valid-value":70}],51:[function(require,module,exports){ 'use strict'; var assign = require('./assign') , value = require('./valid-value'); module.exports = function (obj) { var copy = Object(value(obj)); if (copy !== obj) return copy; return assign({}, obj); }; },{"./assign":48,"./valid-value":70}],52:[function(require,module,exports){ // Workaround for http://code.google.com/p/v8/issues/detail?id=2804 'use strict'; var create = Object.create, shim; if (!require('./set-prototype-of/is-implemented')()) { shim = require('./set-prototype-of/shim'); } module.exports = (function () { var nullObject, props, desc; if (!shim) return create; if (shim.level !== 1) return create; nullObject = {}; props = {}; desc = { configurable: false, enumerable: false, writable: true, value: undefined }; Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { if (name === '__proto__') { props[name] = { configurable: true, enumerable: false, writable: true, value: undefined }; return; } props[name] = desc; }); Object.defineProperties(nullObject, props); Object.defineProperty(shim, 'nullPolyfill', { configurable: false, enumerable: false, writable: false, value: nullObject }); return function (prototype, props) { return create((prototype === null) ? nullObject : prototype, props); }; }()); },{"./set-prototype-of/is-implemented":66,"./set-prototype-of/shim":67}],53:[function(require,module,exports){ 'use strict'; var value = require('./valid-value') , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (obj) { var i; value(obj); for (i in obj) { if (propertyIsEnumerable.call(obj, i)) return i; } return null; }; },{"./valid-value":70}],54:[function(require,module,exports){ 'use strict'; module.exports = require('./_iterate')('forEach'); },{"./_iterate":47}],55:[function(require,module,exports){ 'use strict'; var isFunction = require('../function/is-function') , isObject = require('./is-object'); module.exports = function (x) { return ((x != null) && (typeof x.length === 'number') && // Just checking ((typeof x === 'object') && (typeof x !== 'function')) // won't work right for some cases, e.g.: // type of instance of NodeList in Safari is a 'function' ((isObject(x) && !isFunction(x)) || (typeof x === "string"))) || false; }; },{"../function/is-function":30,"./is-object":57}],56:[function(require,module,exports){ // Deprecated 'use strict'; module.exports = function (obj) { return typeof obj === 'function'; }; },{}],57:[function(require,module,exports){ 'use strict'; var map = { function: true, object: true }; module.exports = function (x) { return ((x != null) && map[typeof x]) || false; }; },{}],58:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.keys : require('./shim'); },{"./is-implemented":59,"./shim":60}],59:[function(require,module,exports){ 'use strict'; module.exports = function () { try { Object.keys('primitive'); return true; } catch (e) { return false; } }; },{}],60:[function(require,module,exports){ 'use strict'; var keys = Object.keys; module.exports = function (object) { return keys(object == null ? object : Object(object)); }; },{}],61:[function(require,module,exports){ 'use strict'; var callable = require('./valid-callable') , forEach = require('./for-each') , call = Function.prototype.call; module.exports = function (obj, cb/*, thisArg*/) { var o = {}, thisArg = arguments[2]; callable(cb); forEach(obj, function (value, key, obj, index) { o[key] = call.call(cb, thisArg, value, key, obj, index); }); return o; }; },{"./for-each":54,"./valid-callable":68}],62:[function(require,module,exports){ 'use strict'; var value = require('./valid-value') , defineProperty = Object.defineProperty , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor , getOwnPropertyNames = Object.getOwnPropertyNames; module.exports = function (target, source) { var error; target = Object(value(target)); getOwnPropertyNames(Object(value(source))).forEach(function (name) { try { defineProperty(target, name, getOwnPropertyDescriptor(source, name)); } catch (e) { error = e; } }); if (error !== undefined) throw error; return target; }; },{"./valid-value":70}],63:[function(require,module,exports){ 'use strict'; var forEach = Array.prototype.forEach, create = Object.create; var process = function (src, obj) { var key; for (key in src) obj[key] = src[key]; }; module.exports = function (options/*, …options*/) { var result = create(null); forEach.call(arguments, function (options) { if (options == null) return; process(Object(options), result); }); return result; }; },{}],64:[function(require,module,exports){ 'use strict'; var forEach = Array.prototype.forEach, create = Object.create; module.exports = function (arg/*, …args*/) { var set = create(null); forEach.call(arguments, function (name) { set[name] = true; }); return set; }; },{}],65:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.setPrototypeOf : require('./shim'); },{"./is-implemented":66,"./shim":67}],66:[function(require,module,exports){ 'use strict'; var create = Object.create, getPrototypeOf = Object.getPrototypeOf , x = {}; module.exports = function (/*customCreate*/) { var setPrototypeOf = Object.setPrototypeOf , customCreate = arguments[0] || create; if (typeof setPrototypeOf !== 'function') return false; return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x; }; },{}],67:[function(require,module,exports){ // Big thanks to @WebReflection for sorting this out // https://gist.github.com/WebReflection/5593554 'use strict'; var isObject = require('../is-object') , value = require('../valid-value') , isPrototypeOf = Object.prototype.isPrototypeOf , defineProperty = Object.defineProperty , nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined } , validate; validate = function (obj, prototype) { value(obj); if ((prototype === null) || isObject(prototype)) return obj; throw new TypeError('Prototype must be null or an object'); }; module.exports = (function (status) { var fn, set; if (!status) return null; if (status.level === 2) { if (status.set) { set = status.set; fn = function (obj, prototype) { set.call(validate(obj, prototype), prototype); return obj; }; } else { fn = function (obj, prototype) { validate(obj, prototype).__proto__ = prototype; return obj; }; } } else { fn = function self(obj, prototype) { var isNullBase; validate(obj, prototype); isNullBase = isPrototypeOf.call(self.nullPolyfill, obj); if (isNullBase) delete self.nullPolyfill.__proto__; if (prototype === null) prototype = self.nullPolyfill; obj.__proto__ = prototype; if (isNullBase) defineProperty(self.nullPolyfill, '__proto__', nullDesc); return obj; }; } return Object.defineProperty(fn, 'level', { configurable: false, enumerable: false, writable: false, value: status.level }); }((function () { var x = Object.create(null), y = {}, set , desc = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'); if (desc) { try { set = desc.set; // Opera crashes at this point set.call(x, y); } catch (ignore) { } if (Object.getPrototypeOf(x) === y) return { set: set, level: 2 }; } x.__proto__ = y; if (Object.getPrototypeOf(x) === y) return { level: 2 }; x = {}; x.__proto__ = y; if (Object.getPrototypeOf(x) === y) return { level: 1 }; return false; }()))); require('../create'); },{"../create":52,"../is-object":57,"../valid-value":70}],68:[function(require,module,exports){ 'use strict'; module.exports = function (fn) { if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); return fn; }; },{}],69:[function(require,module,exports){ 'use strict'; var isObject = require('./is-object'); module.exports = function (value) { if (!isObject(value)) throw new TypeError(value + " is not an Object"); return value; }; },{"./is-object":57}],70:[function(require,module,exports){ 'use strict'; module.exports = function (value) { if (value == null) throw new TypeError("Cannot use null or undefined"); return value; }; },{}],71:[function(require,module,exports){ 'use strict'; var value = require('./valid-value') , stringifiable = require('./validate-stringifiable'); module.exports = function (x) { return stringifiable(value(x)); }; },{"./valid-value":70,"./validate-stringifiable":72}],72:[function(require,module,exports){ 'use strict'; module.exports = function (stringifiable) { try { return String(stringifiable); } catch (e) { throw new TypeError("Passed argument cannot be stringifed"); } }; },{}],73:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? String.prototype.contains : require('./shim'); },{"./is-implemented":74,"./shim":75}],74:[function(require,module,exports){ 'use strict'; var str = 'razdwatrzy'; module.exports = function () { if (typeof str.contains !== 'function') return false; return ((str.contains('dwa') === true) && (str.contains('foo') === false)); }; },{}],75:[function(require,module,exports){ 'use strict'; var indexOf = String.prototype.indexOf; module.exports = function (searchString/*, position*/) { return indexOf.call(this, searchString, arguments[1]) > -1; }; },{}],76:[function(require,module,exports){ 'use strict'; var toInteger = require('../../number/to-integer') , value = require('../../object/valid-value') , repeat = require('./repeat') , abs = Math.abs, max = Math.max; module.exports = function (fill/*, length*/) { var self = String(value(this)) , sLength = self.length , length = arguments[1]; length = isNaN(length) ? 1 : toInteger(length); fill = repeat.call(String(fill), abs(length)); if (length >= 0) return fill.slice(0, max(0, length - sLength)) + self; return self + (((sLength + length) >= 0) ? '' : fill.slice(length + sLength)); }; },{"../../number/to-integer":45,"../../object/valid-value":70,"./repeat":77}],77:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? String.prototype.repeat : require('./shim'); },{"./is-implemented":78,"./shim":79}],78:[function(require,module,exports){ 'use strict'; var str = 'foo'; module.exports = function () { if (typeof str.repeat !== 'function') return false; return (str.repeat(2) === 'foofoo'); }; },{}],79:[function(require,module,exports){ // Thanks: http://www.2ality.com/2014/01/efficient-string-repeat.html 'use strict'; var value = require('../../../object/valid-value') , toInteger = require('../../../number/to-integer'); module.exports = function (count) { var str = String(value(this)), result; count = toInteger(count); if (count < 0) throw new RangeError("Count must be >= 0"); if (!isFinite(count)) throw new RangeError("Count must be < ∞"); result = ''; if (!count) return result; while (true) { if (count & 1) result += str; count >>>= 1; if (count <= 0) break; str += str; } return result; }; },{"../../../number/to-integer":45,"../../../object/valid-value":70}],80:[function(require,module,exports){ 'use strict'; var toString = Object.prototype.toString , id = toString.call(''); module.exports = function (x) { return (typeof x === 'string') || (x && (typeof x === 'object') && ((x instanceof String) || (toString.call(x) === id))) || false; }; },{}],81:[function(require,module,exports){ 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , contains = require('es5-ext/string/#/contains') , d = require('d') , Iterator = require('./') , defineProperty = Object.defineProperty , ArrayIterator; ArrayIterator = module.exports = function (arr, kind) { if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); Iterator.call(this, arr); if (!kind) kind = 'value'; else if (contains.call(kind, 'key+value')) kind = 'key+value'; else if (contains.call(kind, 'key')) kind = 'key'; else kind = 'value'; defineProperty(this, '__kind__', d('', kind)); }; if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); ArrayIterator.prototype = Object.create(Iterator.prototype, { constructor: d(ArrayIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__list__[i]; if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; return i; }), toString: d(function () { return '[object Array Iterator]'; }) }); },{"./":84,"d":16,"es5-ext/object/set-prototype-of":65,"es5-ext/string/#/contains":73}],82:[function(require,module,exports){ 'use strict'; var isArguments = require('es5-ext/function/is-arguments') , callable = require('es5-ext/object/valid-callable') , isString = require('es5-ext/string/is-string') , get = require('./get') , isArray = Array.isArray, call = Function.prototype.call , some = Array.prototype.some; module.exports = function (iterable, cb/*, thisArg*/) { var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code; if (isArray(iterable) || isArguments(iterable)) mode = 'array'; else if (isString(iterable)) mode = 'string'; else iterable = get(iterable); callable(cb); doBreak = function () { broken = true; }; if (mode === 'array') { some.call(iterable, function (value) { call.call(cb, thisArg, value, doBreak); if (broken) return true; }); return; } if (mode === 'string') { l = iterable.length; for (i = 0; i < l; ++i) { char = iterable[i]; if ((i + 1) < l) { code = char.charCodeAt(0); if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i]; } call.call(cb, thisArg, char, doBreak); if (broken) break; } return; } result = iterable.next(); while (!result.done) { call.call(cb, thisArg, result.value, doBreak); if (broken) return; result = iterable.next(); } }; },{"./get":83,"es5-ext/function/is-arguments":29,"es5-ext/object/valid-callable":68,"es5-ext/string/is-string":80}],83:[function(require,module,exports){ 'use strict'; var isArguments = require('es5-ext/function/is-arguments') , isString = require('es5-ext/string/is-string') , ArrayIterator = require('./array') , StringIterator = require('./string') , iterable = require('./valid-iterable') , iteratorSymbol = require('es6-symbol').iterator; module.exports = function (obj) { if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); if (isArguments(obj)) return new ArrayIterator(obj); if (isString(obj)) return new StringIterator(obj); return new ArrayIterator(obj); }; },{"./array":81,"./string":91,"./valid-iterable":92,"es5-ext/function/is-arguments":29,"es5-ext/string/is-string":80,"es6-symbol":86}],84:[function(require,module,exports){ 'use strict'; var clear = require('es5-ext/array/#/clear') , assign = require('es5-ext/object/assign') , callable = require('es5-ext/object/valid-callable') , value = require('es5-ext/object/valid-value') , d = require('d') , autoBind = require('d/auto-bind') , Symbol = require('es6-symbol') , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , Iterator; module.exports = Iterator = function (list, context) { if (!(this instanceof Iterator)) return new Iterator(list, context); defineProperties(this, { __list__: d('w', value(list)), __context__: d('w', context), __nextIndex__: d('w', 0) }); if (!context) return; callable(context.on); context.on('_add', this._onAdd); context.on('_delete', this._onDelete); context.on('_clear', this._onClear); }; defineProperties(Iterator.prototype, assign({ constructor: d(Iterator), _next: d(function () { var i; if (!this.__list__) return; if (this.__redo__) { i = this.__redo__.shift(); if (i !== undefined) return i; } if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; this._unBind(); }), next: d(function () { return this._createResult(this._next()); }), _createResult: d(function (i) { if (i === undefined) return { done: true, value: undefined }; return { done: false, value: this._resolve(i) }; }), _resolve: d(function (i) { return this.__list__[i]; }), _unBind: d(function () { this.__list__ = null; delete this.__redo__; if (!this.__context__) return; this.__context__.off('_add', this._onAdd); this.__context__.off('_delete', this._onDelete); this.__context__.off('_clear', this._onClear); this.__context__ = null; }), toString: d(function () { return '[object Iterator]'; }) }, autoBind({ _onAdd: d(function (index) { if (index >= this.__nextIndex__) return; ++this.__nextIndex__; if (!this.__redo__) { defineProperty(this, '__redo__', d('c', [index])); return; } this.__redo__.forEach(function (redo, i) { if (redo >= index) this.__redo__[i] = ++redo; }, this); this.__redo__.push(index); }), _onDelete: d(function (index) { var i; if (index >= this.__nextIndex__) return; --this.__nextIndex__; if (!this.__redo__) return; i = this.__redo__.indexOf(index); if (i !== -1) this.__redo__.splice(i, 1); this.__redo__.forEach(function (redo, i) { if (redo > index) this.__redo__[i] = --redo; }, this); }), _onClear: d(function () { if (this.__redo__) clear.call(this.__redo__); this.__nextIndex__ = 0; }) }))); defineProperty(Iterator.prototype, Symbol.iterator, d(function () { return this; })); defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); },{"d":16,"d/auto-bind":15,"es5-ext/array/#/clear":18,"es5-ext/object/assign":48,"es5-ext/object/valid-callable":68,"es5-ext/object/valid-value":70,"es6-symbol":86}],85:[function(require,module,exports){ 'use strict'; var isArguments = require('es5-ext/function/is-arguments') , isString = require('es5-ext/string/is-string') , iteratorSymbol = require('es6-symbol').iterator , isArray = Array.isArray; module.exports = function (value) { if (value == null) return false; if (isArray(value)) return true; if (isString(value)) return true; if (isArguments(value)) return true; return (typeof value[iteratorSymbol] === 'function'); }; },{"es5-ext/function/is-arguments":29,"es5-ext/string/is-string":80,"es6-symbol":86}],86:[function(require,module,exports){ arguments[4][40][0].apply(exports,arguments) },{"./is-implemented":87,"./polyfill":89,"dup":40}],87:[function(require,module,exports){ arguments[4][41][0].apply(exports,arguments) },{"dup":41}],88:[function(require,module,exports){ arguments[4][42][0].apply(exports,arguments) },{"dup":42}],89:[function(require,module,exports){ arguments[4][43][0].apply(exports,arguments) },{"./validate-symbol":90,"d":16,"dup":43}],90:[function(require,module,exports){ arguments[4][44][0].apply(exports,arguments) },{"./is-symbol":88,"dup":44}],91:[function(require,module,exports){ // Thanks @mathiasbynens // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , Iterator = require('./') , defineProperty = Object.defineProperty , StringIterator; StringIterator = module.exports = function (str) { if (!(this instanceof StringIterator)) return new StringIterator(str); str = String(str); Iterator.call(this, str); defineProperty(this, '__length__', d('', str.length)); }; if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); StringIterator.prototype = Object.create(Iterator.prototype, { constructor: d(StringIterator), _next: d(function () { if (!this.__list__) return; if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; this._unBind(); }), _resolve: d(function (i) { var char = this.__list__[i], code; if (this.__nextIndex__ === this.__length__) return char; code = char.charCodeAt(0); if ((code >= 0xD800) && (code <= 0xDBFF)) return char + this.__list__[this.__nextIndex__++]; return char; }), toString: d(function () { return '[object String Iterator]'; }) }); },{"./":84,"d":16,"es5-ext/object/set-prototype-of":65}],92:[function(require,module,exports){ 'use strict'; var isIterable = require('./is-iterable'); module.exports = function (value) { if (!isIterable(value)) throw new TypeError(value + " is not iterable"); return value; }; },{"./is-iterable":85}],93:[function(require,module,exports){ // Support for asynchronous functions 'use strict'; var aFrom = require('es5-ext/array/from') , mixin = require('es5-ext/object/mixin') , defineLength = require('es5-ext/function/_define-length') , nextTick = require('next-tick') , slice = Array.prototype.slice , apply = Function.prototype.apply, create = Object.create , hasOwnProperty = Object.prototype.hasOwnProperty; require('../lib/registered-extensions').async = function (tbi, conf) { var waiting = create(null), cache = create(null) , base = conf.memoized, original = conf.original , currentCallback, currentContext, currentArgs; // Initial conf.memoized = defineLength(function (arg) { var args = arguments, last = args[args.length - 1]; if (typeof last === 'function') { currentCallback = last; args = slice.call(args, 0, -1); } return base.apply(currentContext = this, currentArgs = args); }, base); try { mixin(conf.memoized, base); } catch (ignore) {} // From cache (sync) conf.on('get', function (id) { var cb, context, args; if (!currentCallback) return; // Unresolved if (waiting[id]) { if (typeof waiting[id] === 'function') waiting[id] = [waiting[id], currentCallback]; else waiting[id].push(currentCallback); currentCallback = null; return; } // Resolved, assure next tick invocation cb = currentCallback; context = currentContext; args = currentArgs; currentCallback = currentContext = currentArgs = null; nextTick(function () { var data; if (hasOwnProperty.call(cache, id)) { data = cache[id]; conf.emit('getasync', id, args, context); apply.call(cb, data.context, data.args); } else { // Purged in a meantime, we shouldn't rely on cached value, recall currentCallback = cb; currentContext = context; currentArgs = args; base.apply(context, args); } }); }); // Not from cache conf.original = function () { var args, cb, origCb, result; if (!currentCallback) return apply.call(original, this, arguments); args = aFrom(arguments); cb = function self(err) { var cb, args, id = self.id; if (id == null) { // Shouldn't happen, means async callback was called sync way nextTick(apply.bind(self, this, arguments)); return; } delete self.id; cb = waiting[id]; delete waiting[id]; if (!cb) { // Already processed, // outcome of race condition: asyncFn(1, cb), asyncFn.clear(), asyncFn(1, cb) return; } args = aFrom(arguments); if (conf.has(id)) { if (err) { conf.delete(id); } else { cache[id] = { context: this, args: args }; conf.emit('setasync', id, (typeof cb === 'function') ? 1 : cb.length); } } if (typeof cb === 'function') { result = apply.call(cb, this, args); } else { cb.forEach(function (cb) { result = apply.call(cb, this, args); }, this); } return result; }; origCb = currentCallback; currentCallback = currentContext = currentArgs = null; args.push(cb); result = apply.call(original, this, args); cb.cb = origCb; currentCallback = cb; return result; }; // After not from cache call conf.on('set', function (id) { if (!currentCallback) { conf.delete(id); return; } if (waiting[id]) { // Race condition: asyncFn(1, cb), asyncFn.clear(), asyncFn(1, cb) if (typeof waiting[id] === 'function') waiting[id] = [waiting[id], currentCallback.cb]; else waiting[id].push(currentCallback.cb); } else { waiting[id] = currentCallback.cb; } delete currentCallback.cb; currentCallback.id = id; currentCallback = null; }); // On delete conf.on('delete', function (id) { var result; // If false, we don't have value yet, so we assume that intention is not // to memoize this call. After value is obtained we don't cache it but // gracefully pass to callback if (hasOwnProperty.call(waiting, id)) return; if (!cache[id]) return; result = cache[id]; delete cache[id]; conf.emit('deleteasync', id, result); }); // On clear conf.on('clear', function () { var oldCache = cache; cache = create(null); conf.emit('clearasync', oldCache); }); }; },{"../lib/registered-extensions":101,"es5-ext/array/from":22,"es5-ext/function/_define-length":28,"es5-ext/object/mixin":62,"next-tick":108}],94:[function(require,module,exports){ // Call dispose callback on each cache purge 'use strict'; var callable = require('es5-ext/object/valid-callable') , forEach = require('es5-ext/object/for-each') , extensions = require('../lib/registered-extensions') , slice = Array.prototype.slice, apply = Function.prototype.apply; extensions.dispose = function (dispose, conf, options) { var del; callable(dispose); if (options.async && extensions.async) { conf.on('deleteasync', del = function (id, result) { apply.call(dispose, null, slice.call(result.args, 1)); }); conf.on('clearasync', function (cache) { forEach(cache, function (result, id) { del(id, result); }); }); return; } conf.on('delete', del = function (id, result) { dispose(result); }); conf.on('clear', function (cache) { forEach(cache, function (result, id) { del(id, result); }); }); }; },{"../lib/registered-extensions":101,"es5-ext/object/for-each":54,"es5-ext/object/valid-callable":68}],95:[function(require,module,exports){ // Timeout cached values 'use strict'; var aFrom = require('es5-ext/array/from') , noop = require('es5-ext/function/noop') , forEach = require('es5-ext/object/for-each') , timeout = require('timers-ext/valid-timeout') , extensions = require('../lib/registered-extensions') , max = Math.max, min = Math.min, create = Object.create; extensions.maxAge = function (maxAge, conf, options) { var timeouts, postfix, preFetchAge, preFetchTimeouts; maxAge = timeout(maxAge); if (!maxAge) return; timeouts = create(null); postfix = (options.async && extensions.async) ? 'async' : ''; conf.on('set' + postfix, function (id) { timeouts[id] = setTimeout(function () { conf.delete(id); }, maxAge); if (!preFetchTimeouts) return; if (preFetchTimeouts[id]) clearTimeout(preFetchTimeouts[id]); preFetchTimeouts[id] = setTimeout(function () { delete preFetchTimeouts[id]; }, preFetchAge); }); conf.on('delete' + postfix, function (id) { clearTimeout(timeouts[id]); delete timeouts[id]; if (!preFetchTimeouts) return; clearTimeout(preFetchTimeouts[id]); delete preFetchTimeouts[id]; }); if (options.preFetch) { if ((options.preFetch === true) || isNaN(options.preFetch)) { preFetchAge = 0.333; } else { preFetchAge = max(min(Number(options.preFetch), 1), 0); } if (preFetchAge) { preFetchTimeouts = {}; preFetchAge = (1 - preFetchAge) * maxAge; conf.on('get' + postfix, function (id, args, context) { if (!preFetchTimeouts[id]) { preFetchTimeouts[id] = setTimeout(function () { delete preFetchTimeouts[id]; conf.delete(id); if (options.async) { args = aFrom(args); args.push(noop); } conf.memoized.apply(context, args); }, 0); } }); } } conf.on('clear' + postfix, function () { forEach(timeouts, function (id) { clearTimeout(id); }); timeouts = {}; if (preFetchTimeouts) { forEach(preFetchTimeouts, function (id) { clearTimeout(id); }); preFetchTimeouts = {}; } }); }; },{"../lib/registered-extensions":101,"es5-ext/array/from":22,"es5-ext/function/noop":31,"es5-ext/object/for-each":54,"timers-ext/valid-timeout":116}],96:[function(require,module,exports){ // Limit cache size, LRU (least recently used) algorithm. 'use strict'; var toPosInteger = require('es5-ext/number/to-pos-integer') , lruQueue = require('lru-queue') , extensions = require('../lib/registered-extensions'); extensions.max = function (max, conf, options) { var postfix, queue, hit; max = toPosInteger(max); if (!max) return; queue = lruQueue(max); postfix = (options.async && extensions.async) ? 'async' : ''; conf.on('set' + postfix, hit = function (id) { id = queue.hit(id); if (id === undefined) return; conf.delete(id); }); conf.on('get' + postfix, hit); conf.on('delete' + postfix, queue.delete); conf.on('clear' + postfix, queue.clear); }; },{"../lib/registered-extensions":101,"es5-ext/number/to-pos-integer":46,"lru-queue":107}],97:[function(require,module,exports){ // Reference counter, useful for garbage collector like functionality 'use strict'; var d = require('d') , extensions = require('../lib/registered-extensions') , create = Object.create, defineProperties = Object.defineProperties; extensions.refCounter = function (ignore, conf, options) { var cache, postfix; cache = create(null); postfix = (options.async && extensions.async) ? 'async' : ''; conf.on('set' + postfix, function (id, length) { cache[id] = length || 1; }); conf.on('get' + postfix, function (id) { ++cache[id]; }); conf.on('delete' + postfix, function (id) { delete cache[id]; }); conf.on('clear' + postfix, function () { cache = {}; }); defineProperties(conf.memoized, { deleteRef: d(function () { var id = conf.get(arguments); if (id === null) return null; if (!cache[id]) return null; if (!--cache[id]) { conf.delete(id); return true; } return false; }), getRefCount: d(function () { var id = conf.get(arguments); if (id === null) return 0; if (!cache[id]) return 0; return cache[id]; }) }); }; },{"../lib/registered-extensions":101,"d":16}],98:[function(require,module,exports){ 'use strict'; var normalizeOpts = require('es5-ext/object/normalize-options') , resolveLength = require('./lib/resolve-length') , plain = require('./plain'); module.exports = function (fn/*, options*/) { var options = normalizeOpts(arguments[1]), length; if (!options.normalizer) { length = options.length = resolveLength(options.length, fn.length, options.async); if (length !== 0) { if (options.primitive) { if (length === false) { options.normalizer = require('./normalizers/primitive'); } else if (length > 1) { options.normalizer = require('./normalizers/get-primitive-fixed')(length); } } else { if (length === false) options.normalizer = require('./normalizers/get')(); else if (length === 1) options.normalizer = require('./normalizers/get-1')(); else options.normalizer = require('./normalizers/get-fixed')(length); } } } // Assure extensions if (options.async) require('./ext/async'); if (options.dispose) require('./ext/dispose'); if (options.maxAge) require('./ext/max-age'); if (options.max) require('./ext/max'); if (options.refCounter) require('./ext/ref-counter'); return plain(fn, options); }; },{"./ext/async":93,"./ext/dispose":94,"./ext/max":96,"./ext/max-age":95,"./ext/ref-counter":97,"./lib/resolve-length":102,"./normalizers/get":112,"./normalizers/get-1":109,"./normalizers/get-fixed":110,"./normalizers/get-primitive-fixed":111,"./normalizers/primitive":113,"./plain":114,"es5-ext/object/normalize-options":63}],99:[function(require,module,exports){ 'use strict'; var customError = require('es5-ext/error/custom') , defineLength = require('es5-ext/function/_define-length') , d = require('d') , ee = require('event-emitter').methods , resolveResolve = require('./resolve-resolve') , resolveNormalize = require('./resolve-normalize') , apply = Function.prototype.apply, call = Function.prototype.call , create = Object.create, hasOwnProperty = Object.prototype.hasOwnProperty , defineProperties = Object.defineProperties , on = ee.on, emit = ee.emit; module.exports = function (original, length, options) { var cache = create(null), conf, memLength, get, set, del, clear, extDel, normalizer , getListeners, setListeners, deleteListeners, memoized, resolve; if (length !== false) memLength = length; else if (isNaN(original.length)) memLength = 1; else memLength = original.length; if (options.normalizer) { normalizer = resolveNormalize(options.normalizer); get = normalizer.get; set = normalizer.set; del = normalizer.delete; clear = normalizer.clear; } if (options.resolvers != null) resolve = resolveResolve(options.resolvers); if (get) { memoized = defineLength(function (arg) { var id, result, args = arguments; if (resolve) args = resolve(args); id = get(args); if (id !== null) { if (hasOwnProperty.call(cache, id)) { if (getListeners) conf.emit('get', id, args, this); return cache[id]; } } if (args.length === 1) result = call.call(original, this, arg); else result = apply.call(original, this, args); if (id === null) { id = get(args); if (id !== null) throw customError("Circular invocation", 'CIRCULAR_INVOCATION'); id = set(args); } else if (hasOwnProperty.call(cache, id)) { throw customError("Circular invocation", 'CIRCULAR_INVOCATION'); } cache[id] = result; if (setListeners) conf.emit('set', id); return result; }, memLength); } else if (length === 0) { memoized = function () { var result; if (hasOwnProperty.call(cache, 'data')) { if (getListeners) conf.emit('get', 'data', arguments, this); return cache.data; } if (!arguments.length) result = call.call(original, this); else result = apply.call(original, this, arguments); if (hasOwnProperty.call(cache, 'data')) { throw customError("Circular invocation", 'CIRCULAR_INVOCATION'); } cache.data = result; if (setListeners) conf.emit('set', 'data'); return result; }; } else { memoized = function (arg) { var result, args = arguments, id; if (resolve) args = resolve(arguments); id = String(args[0]); if (hasOwnProperty.call(cache, id)) { if (getListeners) conf.emit('get', id, args, this); return cache[id]; } if (args.length === 1) result = call.call(original, this, args[0]); else result = apply.call(original, this, args); if (hasOwnProperty.call(cache, id)) { throw customError("Circular invocation", 'CIRCULAR_INVOCATION'); } cache[id] = result; if (setListeners) conf.emit('set', id); return result; }; } conf = { original: original, memoized: memoized, get: function (args) { if (resolve) args = resolve(args); if (get) return get(args); return String(args[0]); }, has: function (id) { return hasOwnProperty.call(cache, id); }, delete: function (id) { var result; if (!hasOwnProperty.call(cache, id)) return; if (del) del(id); result = cache[id]; delete cache[id]; if (deleteListeners) conf.emit('delete', id, result); }, clear: function () { var oldCache = cache; if (clear) clear(); cache = create(null); conf.emit('clear', oldCache); }, on: function (type, listener) { if (type === 'get') getListeners = true; else if (type === 'set') setListeners = true; else if (type === 'delete') deleteListeners = true; return on.call(this, type, listener); }, emit: emit, updateEnv: function () { original = conf.original; } }; if (get) { extDel = defineLength(function (arg) { var id, args = arguments; if (resolve) args = resolve(args); id = get(args); if (id === null) return; conf.delete(id); }, memLength); } else if (length === 0) { extDel = function () { return conf.delete('data'); }; } else { extDel = function (arg) { if (resolve) arg = resolve(arguments)[0]; return conf.delete(arg); }; } defineProperties(memoized, { __memoized__: d(true), delete: d(extDel), clear: d(conf.clear) }); return conf; }; },{"./resolve-normalize":103,"./resolve-resolve":104,"d":16,"es5-ext/error/custom":26,"es5-ext/function/_define-length":28,"event-emitter":106}],100:[function(require,module,exports){ 'use strict'; var forEach = require('es5-ext/object/for-each') , normalizeOpts = require('es5-ext/object/normalize-options') , callable = require('es5-ext/object/valid-callable') , lazy = require('d/lazy') , resolveLength = require('./resolve-length') , extensions = require('./registered-extensions'); module.exports = function (memoize) { return function (props) { forEach(props, function (desc, name) { var fn = callable(desc.value), length; desc.value = function (options) { if (options.getNormalizer) { options = normalizeOpts(options); if (length === undefined) { length = resolveLength(options.length, fn.length, options.async && extensions.async); } options.normalizer = options.getNormalizer(length); delete options.getNormalizer; } return memoize(fn.bind(this), options); }; }); return lazy(props); }; }; },{"./registered-extensions":101,"./resolve-length":102,"d/lazy":17,"es5-ext/object/for-each":54,"es5-ext/object/normalize-options":63,"es5-ext/object/valid-callable":68}],101:[function(require,module,exports){ 'use strict'; },{}],102:[function(require,module,exports){ 'use strict'; var toPosInt = require('es5-ext/number/to-pos-integer'); module.exports = function (optsLength, fnLength, isAsync) { var length; if (isNaN(optsLength)) { length = fnLength; if (!(length >= 0)) return 1; if (isAsync && length) return length - 1; return length; } if (optsLength === false) return false; return toPosInt(optsLength); }; },{"es5-ext/number/to-pos-integer":46}],103:[function(require,module,exports){ 'use strict'; var callable = require('es5-ext/object/valid-callable'); module.exports = function (userNormalizer) { var normalizer; if (typeof userNormalizer === 'function') return { set: userNormalizer, get: userNormalizer }; normalizer = { get: callable(userNormalizer.get) }; if (userNormalizer.set !== undefined) { normalizer.set = callable(userNormalizer.set); normalizer.delete = callable(userNormalizer.delete); normalizer.clear = callable(userNormalizer.clear); return normalizer; } normalizer.set = normalizer.get; return normalizer; }; },{"es5-ext/object/valid-callable":68}],104:[function(require,module,exports){ 'use strict'; var toArray = require('es5-ext/array/to-array') , callable = require('es5-ext/object/valid-callable') , slice = Array.prototype.slice , resolveArgs; resolveArgs = function (args) { return this.map(function (r, i) { return r ? r(args[i]) : args[i]; }).concat(slice.call(args, this.length)); }; module.exports = function (resolvers) { resolvers = toArray(resolvers); resolvers.forEach(function (r) { if (r != null) callable(r); }); return resolveArgs.bind(resolvers); }; },{"es5-ext/array/to-array":25,"es5-ext/object/valid-callable":68}],105:[function(require,module,exports){ 'use strict'; module.exports = require('./lib/methods')(require('./')); },{"./":98,"./lib/methods":100}],106:[function(require,module,exports){ 'use strict'; var d = require('d') , callable = require('es5-ext/object/valid-callable') , apply = Function.prototype.apply, call = Function.prototype.call , create = Object.create, defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , hasOwnProperty = Object.prototype.hasOwnProperty , descriptor = { configurable: true, enumerable: false, writable: true } , on, once, off, emit, methods, descriptors, base; on = function (type, listener) { var data; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) { data = descriptor.value = create(null); defineProperty(this, '__ee__', descriptor); descriptor.value = null; } else { data = this.__ee__; } if (!data[type]) data[type] = listener; else if (typeof data[type] === 'object') data[type].push(listener); else data[type] = [data[type], listener]; return this; }; once = function (type, listener) { var once, self; callable(listener); self = this; on.call(this, type, once = function () { off.call(self, type, once); apply.call(listener, this, arguments); }); once.__eeOnceListener__ = listener; return this; }; off = function (type, listener) { var data, listeners, candidate, i; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) return this; data = this.__ee__; if (!data[type]) return this; listeners = data[type]; if (typeof listeners === 'object') { for (i = 0; (candidate = listeners[i]); ++i) { if ((candidate === listener) || (candidate.__eeOnceListener__ === listener)) { if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; else listeners.splice(i, 1); } } } else { if ((listeners === listener) || (listeners.__eeOnceListener__ === listener)) { delete data[type]; } } return this; }; emit = function (type) { var i, l, listener, listeners, args; if (!hasOwnProperty.call(this, '__ee__')) return; listeners = this.__ee__[type]; if (!listeners) return; if (typeof listeners === 'object') { l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; listeners = listeners.slice(); for (i = 0; (listener = listeners[i]); ++i) { apply.call(listener, this, args); } } else { switch (arguments.length) { case 1: call.call(listeners, this); break; case 2: call.call(listeners, this, arguments[1]); break; case 3: call.call(listeners, this, arguments[1], arguments[2]); break; default: l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) { args[i - 1] = arguments[i]; } apply.call(listeners, this, args); } } }; methods = { on: on, once: once, off: off, emit: emit }; descriptors = { on: d(on), once: d(once), off: d(off), emit: d(emit) }; base = defineProperties({}, descriptors); module.exports = exports = function (o) { return (o == null) ? create(base) : defineProperties(Object(o), descriptors); }; exports.methods = methods; },{"d":16,"es5-ext/object/valid-callable":68}],107:[function(require,module,exports){ 'use strict'; var toPosInt = require('es5-ext/number/to-pos-integer') , create = Object.create, hasOwnProperty = Object.prototype.hasOwnProperty; module.exports = function (limit) { var size = 0, base = 1, queue = create(null), map = create(null), index = 0, del; limit = toPosInt(limit); return { hit: function (id) { var oldIndex = map[id], nuIndex = ++index; queue[nuIndex] = id; map[id] = nuIndex; if (!oldIndex) { ++size; if (size <= limit) return; id = queue[base]; del(id); return id; } delete queue[oldIndex]; if (base !== oldIndex) return; while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip }, delete: del = function (id) { var oldIndex = map[id]; if (!oldIndex) return; delete queue[oldIndex]; delete map[id]; --size; if (base !== oldIndex) return; if (!size) { index = 0; base = 1; return; } while (!hasOwnProperty.call(queue, ++base)) continue; //jslint: skip }, clear: function () { size = 0; base = 1; queue = create(null); map = create(null); index = 0; } }; }; },{"es5-ext/number/to-pos-integer":46}],108:[function(require,module,exports){ (function (process){ 'use strict'; var callable, byObserver; callable = function (fn) { if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); return fn; }; byObserver = function (Observer) { var node = document.createTextNode(''), queue, i = 0; new Observer(function () { var data; if (!queue) return; data = queue; queue = null; if (typeof data === 'function') { data(); return; } data.forEach(function (fn) { fn(); }); }).observe(node, { characterData: true }); return function (fn) { callable(fn); if (queue) { if (typeof queue === 'function') queue = [queue, fn]; else queue.push(fn); return; } queue = fn; node.data = (i = ++i % 2); }; }; module.exports = (function () { // Node.js if ((typeof process !== 'undefined') && process && (typeof process.nextTick === 'function')) { return process.nextTick; } // MutationObserver= if ((typeof document === 'object') && document) { if (typeof MutationObserver === 'function') { return byObserver(MutationObserver); } if (typeof WebKitMutationObserver === 'function') { return byObserver(WebKitMutationObserver); } } // W3C Draft // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html if (typeof setImmediate === 'function') { return function (cb) { setImmediate(callable(cb)); }; } // Wide available standard if (typeof setTimeout === 'function') { return function (cb) { setTimeout(callable(cb), 0); }; } return null; }()); }).call(this,require('_process')) },{"_process":149}],109:[function(require,module,exports){ 'use strict'; var indexOf = require('es5-ext/array/#/e-index-of'); module.exports = function () { var lastId = 0, argsMap = [], cache = []; return { get: function (args) { var index = indexOf.call(argsMap, args[0]); return (index === -1) ? null : cache[index]; }, set: function (args) { argsMap.push(args[0]); cache.push(++lastId); return lastId; }, delete: function (id) { var index = indexOf.call(cache, id); if (index !== -1) { argsMap.splice(index, 1); cache.splice(index, 1); } }, clear: function () { argsMap = []; cache = []; } }; }; },{"es5-ext/array/#/e-index-of":19}],110:[function(require,module,exports){ 'use strict'; var indexOf = require('es5-ext/array/#/e-index-of') , create = Object.create; module.exports = function (length) { var lastId = 0, map = [[], []], cache = create(null); return { get: function (args) { var index = 0, set = map, i; while (index < (length - 1)) { i = indexOf.call(set[0], args[index]); if (i === -1) return null; set = set[1][i]; ++index; } i = indexOf.call(set[0], args[index]); if (i === -1) return null; return set[1][i] || null; }, set: function (args) { var index = 0, set = map, i; while (index < (length - 1)) { i = indexOf.call(set[0], args[index]); if (i === -1) { i = set[0].push(args[index]) - 1; set[1].push([[], []]); } set = set[1][i]; ++index; } i = indexOf.call(set[0], args[index]); if (i === -1) { i = set[0].push(args[index]) - 1; } set[1][i] = ++lastId; cache[lastId] = args; return lastId; }, delete: function (id) { var index = 0, set = map, i, path = [], args = cache[id]; while (index < (length - 1)) { i = indexOf.call(set[0], args[index]); if (i === -1) { return; } path.push(set, i); set = set[1][i]; ++index; } i = indexOf.call(set[0], args[index]); if (i === -1) { return; } id = set[1][i]; set[0].splice(i, 1); set[1].splice(i, 1); while (!set[0].length && path.length) { i = path.pop(); set = path.pop(); set[0].splice(i, 1); set[1].splice(i, 1); } delete cache[id]; }, clear: function () { map = [[], []]; cache = create(null); } }; }; },{"es5-ext/array/#/e-index-of":19}],111:[function(require,module,exports){ 'use strict'; module.exports = function (length) { if (!length) { return function () { return ''; }; } return function (args) { var id = String(args[0]), i = 0, l = length; while (--l) { id += '\u0001' + args[++i]; } return id; }; }; },{}],112:[function(require,module,exports){ 'use strict'; var indexOf = require('es5-ext/array/#/e-index-of') , create = Object.create; module.exports = function () { var lastId = 0, map = [], cache = create(null); return { get: function (args) { var index = 0, set = map, i, length = args.length; if (length === 0) return set[length] || null; if ((set = set[length])) { while (index < (length - 1)) { i = indexOf.call(set[0], args[index]); if (i === -1) return null; set = set[1][i]; ++index; } i = indexOf.call(set[0], args[index]); if (i === -1) return null; return set[1][i] || null; } return null; }, set: function (args) { var index = 0, set = map, i, length = args.length; if (length === 0) { set[length] = ++lastId; } else { if (!set[length]) { set[length] = [[], []]; } set = set[length]; while (index < (length - 1)) { i = indexOf.call(set[0], args[index]); if (i === -1) { i = set[0].push(args[index]) - 1; set[1].push([[], []]); } set = set[1][i]; ++index; } i = indexOf.call(set[0], args[index]); if (i === -1) { i = set[0].push(args[index]) - 1; } set[1][i] = ++lastId; } cache[lastId] = args; return lastId; }, delete: function (id) { var index = 0, set = map, i, args = cache[id], length = args.length , path = []; if (length === 0) { delete set[length]; } else if ((set = set[length])) { while (index < (length - 1)) { i = indexOf.call(set[0], args[index]); if (i === -1) { return; } path.push(set, i); set = set[1][i]; ++index; } i = indexOf.call(set[0], args[index]); if (i === -1) { return; } id = set[1][i]; set[0].splice(i, 1); set[1].splice(i, 1); while (!set[0].length && path.length) { i = path.pop(); set = path.pop(); set[0].splice(i, 1); set[1].splice(i, 1); } } delete cache[id]; }, clear: function () { map = []; cache = create(null); } }; }; },{"es5-ext/array/#/e-index-of":19}],113:[function(require,module,exports){ 'use strict'; module.exports = function (args) { var id, i, length = args.length; if (!length) return '\u0002'; id = String(args[i = 0]); while (--length) id += '\u0001' + args[++i]; return id; }; },{}],114:[function(require,module,exports){ 'use strict'; var callable = require('es5-ext/object/valid-callable') , forEach = require('es5-ext/object/for-each') , extensions = require('./lib/registered-extensions') , configure = require('./lib/configure-map') , resolveLength = require('./lib/resolve-length') , hasOwnProperty = Object.prototype.hasOwnProperty; module.exports = function self(fn/*, options */) { var options, length, conf; callable(fn); options = Object(arguments[1]); // Do not memoize already memoized function if (hasOwnProperty.call(fn, '__memoized__') && !options.force) return fn; // Resolve length; length = resolveLength(options.length, fn.length, options.async && extensions.async); // Configure cache map conf = configure(fn, length, options); // Bind eventual extensions forEach(extensions, function (fn, name) { if (options[name]) fn(options[name], conf, options); }); if (self.__profiler__) self.__profiler__(conf); conf.updateEnv(); return conf.memoized; }; },{"./lib/configure-map":99,"./lib/registered-extensions":101,"./lib/resolve-length":102,"es5-ext/object/for-each":54,"es5-ext/object/valid-callable":68}],115:[function(require,module,exports){ 'use strict'; module.exports = 2147483647; },{}],116:[function(require,module,exports){ 'use strict'; var toPosInt = require('es5-ext/number/to-pos-integer') , maxTimeout = require('./max-timeout'); module.exports = function (value) { value = toPosInt(value); if (value > maxTimeout) throw new TypeError(value + " exceeds maximum possible timeout"); return value; }; },{"./max-timeout":115,"es5-ext/number/to-pos-integer":46}],117:[function(require,module,exports){ 'use strict'; module.exports = '\x1b[2J\x1b[0;0H'; },{}],118:[function(require,module,exports){ 'use strict'; var reAnsi = require('ansi-regex') , stringifiable = require('es5-ext/object/validate-stringifiable-value') , length = require('./get-stripped-length') , sgr = require('./lib/sgr') , max = Math.max; var Token = function Token(token) { this.token = token; }; var tokenize = function (str) { var match = reAnsi().exec(str); if (!match) { return [ str ]; } var index = match.index , head, prehead, tail; if (index === 0) { head = match[0]; tail = str.slice(head.length); return [ new Token(head) ].concat(tokenize(tail)); } prehead = str.slice(0, index); head = match[0]; tail = str.slice(index + head.length); return [ prehead, new Token(head) ].concat(tokenize(tail)); }; var isChunkInSlice = function (chunk, index, begin, end) { var endIndex = chunk.length + index; if (begin > endIndex) return false; if (end < index) return false; return true; }; var sliceSeq = function (seq, begin, end) { var sliced = seq.reduce(function (state, chunk) { var index = state.index; if (!(chunk instanceof Token)) { var nextChunk = ''; if (isChunkInSlice(chunk, index, begin, end)) { var relBegin = Math.max(begin - index, 0) , relEnd = Math.min(end - index, chunk.length); nextChunk = chunk.slice(relBegin, relEnd); } state.seq.push(nextChunk); state.index = index + chunk.length; } else { var code = sgr.extractCode(chunk.token); if (index <= begin) { if (code in sgr.openers) { sgr.openStyle(state.preOpeners, code); } if (code in sgr.closers) { sgr.closeStyle(state.preOpeners, code); } } else if (index < end) { if (code in sgr.openers) { sgr.openStyle(state.inOpeners, code); state.seq.push(chunk); } else if (code in sgr.closers) { state.inClosers.push(code); state.seq.push(chunk); } } } return state; }, { index: 0, seq: [], // preOpeners -> [ mod ] // preOpeners must be prepended to the slice if they wasn't closed til the end of it // preOpeners must be closed if they wasn't closed til the end of the slice preOpeners: [], // inOpeners -> [ mod ] // inOpeners already in the slice and must not be prepended to the slice // inOpeners must be closed if they wasn't closed til the end of the slice inOpeners: [], // opener CSI inside slice // inClosers -> [ code ] // closer CSIs for determining which pre/in-Openers must be closed inClosers: [] }); sliced.seq = [].concat( sgr.prepend(sliced.preOpeners), sliced.seq, sgr.complete([].concat(sliced.preOpeners, sliced.inOpeners), sliced.inClosers) ); return sliced.seq; }; module.exports = function (str/*, begin, end*/) { var seq, begin = Number(arguments[1]), end = Number(arguments[2]), len; str = stringifiable(str); len = length(str); if (isNaN(begin)) { begin = 0; } if (isNaN(end)) { end = len; } if (begin < 0) { begin = max(len + begin, 0); } if (end < 0) { end = max(len + end, 0); } seq = tokenize(str); seq = sliceSeq(seq, begin, end); return seq.map(function (chunk) { if (chunk instanceof Token) { return chunk.token; } return chunk; }).join(''); }; },{"./get-stripped-length":8,"./lib/sgr":10,"ansi-regex":14,"es5-ext/object/validate-stringifiable-value":71}],119:[function(require,module,exports){ // Strip ANSI formatting from string 'use strict'; var stringifiable = require('es5-ext/object/validate-stringifiable') , r = require('ansi-regex')(); module.exports = function (str) { return stringifiable(str).replace(r, ''); }; },{"ansi-regex":14,"es5-ext/object/validate-stringifiable":72}],120:[function(require,module,exports){ 'use strict'; var compose = require('es5-ext/function/#/compose') , callable = require('es5-ext/object/valid-callable') , d = require('d') , validTimeout = require('timers-ext/valid-timeout') , chars = '-\\|/', l = chars.length, ThrobberIterator; ThrobberIterator = function () {}; Object.defineProperties(ThrobberIterator.prototype, { index: d(-1), running: d(false), next: d(function () { var str = this.running ? '\u0008' : ''; if (!this.running) this.running = true; return str + chars[this.index = ((this.index + 1) % l)]; }), reset: d(function () { if (!this.running) return ''; this.index = -1; this.running = false; return '\u0008'; }) }); module.exports = exports = function (write, interval/*, format*/) { var format = arguments[2], token, iterator = new ThrobberIterator(); callable(write); interval = validTimeout(interval); if (format !== undefined) write = compose.call(write, callable(format)); return { start: function () { if (token) return; token = setInterval(function () { write(iterator.next()); }, interval); }, restart: function () { this.stop(); this.start(); }, stop: function () { if (!token) return; clearInterval(token); token = null; write(iterator.reset()); } }; }; Object.defineProperty(exports, 'Iterator', d(ThrobberIterator)); },{"d":16,"es5-ext/function/#/compose":27,"es5-ext/object/valid-callable":68,"timers-ext/valid-timeout":116}],121:[function(require,module,exports){ (function (process){ 'use strict'; var d = require('d'); Object.defineProperties(exports, { width: d.gs('ce', function () { return process.stdout.columns || 0; }), height: d.gs('ce', function () { return process.stdout.rows || 0; }) }); }).call(this,require('_process')) },{"_process":149,"d":16}],122:[function(require,module,exports){ module.exports = require('./src/table'); },{"./src/table":136}],123:[function(require,module,exports){ /* The MIT License (MIT) Original Library - Copyright (c) Marak Squires Additional functionality - Copyright (c) Sindre Sorhus (sindresorhus.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 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 colors = {}; module['exports'] = colors; colors.themes = {}; var ansiStyles = colors.styles = require('./styles'); var defineProps = Object.defineProperties; colors.supportsColor = require('./system/supports-colors'); if (typeof colors.enabled === "undefined") { colors.enabled = colors.supportsColor; } colors.stripColors = colors.strip = function(str){ return ("" + str).replace(/\x1B\[\d+m/g, ''); }; var stylize = colors.stylize = function stylize (str, style) { return ansiStyles[style].open + str + ansiStyles[style].close; } var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); } function build(_styles) { var builder = function builder() { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; // __proto__ is used because we must return a function, but there is // no way to create a function with a different prototype. builder.__proto__ = proto; return builder; } var styles = (function () { var ret = {}; ansiStyles.grey = ansiStyles.gray; Object.keys(ansiStyles).forEach(function (key) { ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); ret[key] = { get: function () { return build(this._styles.concat(key)); } }; }); return ret; })(); var proto = defineProps(function colors() {}, styles); function applyStyle() { var args = arguments; var argsLen = args.length; var str = argsLen !== 0 && String(arguments[0]); if (argsLen > 1) { for (var a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!colors.enabled || !str) { return str; } var nestedStyles = this._styles; var i = nestedStyles.length; while (i--) { var code = ansiStyles[nestedStyles[i]]; str = code.open + str.replace(code.closeRe, code.open) + code.close; } return str; } function applyTheme (theme) { for (var style in theme) { (function(style){ colors[style] = function(str){ return colors[theme[style]](str); }; })(style) } } colors.setTheme = function (theme) { if (typeof theme === 'string') { try { colors.themes[theme] = require(theme); applyTheme(colors.themes[theme]); return colors.themes[theme]; } catch (err) { console.log(err); return err; } } else { applyTheme(theme); } }; function init() { var ret = {}; Object.keys(styles).forEach(function (name) { ret[name] = { get: function () { return build([name]); } }; }); return ret; } var sequencer = function sequencer (map, str) { var exploded = str.split(""), i = 0; exploded = exploded.map(map); return exploded.join(""); }; // custom formatter methods colors.trap = require('./custom/trap'); colors.zalgo = require('./custom/zalgo'); // maps colors.maps = {}; colors.maps.america = require('./maps/america'); colors.maps.zebra = require('./maps/zebra'); colors.maps.rainbow = require('./maps/rainbow'); colors.maps.random = require('./maps/random') for (var map in colors.maps) { (function(map){ colors[map] = function (str) { return sequencer(colors.maps[map], str); } })(map) } defineProps(colors, init()); },{"./custom/trap":124,"./custom/zalgo":125,"./maps/america":126,"./maps/rainbow":127,"./maps/random":128,"./maps/zebra":129,"./styles":130,"./system/supports-colors":131}],124:[function(require,module,exports){ module['exports'] = function runTheTrap (text, options) { var result = ""; text = text || "Run the trap, drop the bass"; text = text.split(''); var trap = { a: ["\u0040", "\u0104", "\u023a", "\u0245", "\u0394", "\u039b", "\u0414"], b: ["\u00df", "\u0181", "\u0243", "\u026e", "\u03b2", "\u0e3f"], c: ["\u00a9", "\u023b", "\u03fe"], d: ["\u00d0", "\u018a", "\u0500" , "\u0501" ,"\u0502", "\u0503"], e: ["\u00cb", "\u0115", "\u018e", "\u0258", "\u03a3", "\u03be", "\u04bc", "\u0a6c"], f: ["\u04fa"], g: ["\u0262"], h: ["\u0126", "\u0195", "\u04a2", "\u04ba", "\u04c7", "\u050a"], i: ["\u0f0f"], j: ["\u0134"], k: ["\u0138", "\u04a0", "\u04c3", "\u051e"], l: ["\u0139"], m: ["\u028d", "\u04cd", "\u04ce", "\u0520", "\u0521", "\u0d69"], n: ["\u00d1", "\u014b", "\u019d", "\u0376", "\u03a0", "\u048a"], o: ["\u00d8", "\u00f5", "\u00f8", "\u01fe", "\u0298", "\u047a", "\u05dd", "\u06dd", "\u0e4f"], p: ["\u01f7", "\u048e"], q: ["\u09cd"], r: ["\u00ae", "\u01a6", "\u0210", "\u024c", "\u0280", "\u042f"], s: ["\u00a7", "\u03de", "\u03df", "\u03e8"], t: ["\u0141", "\u0166", "\u0373"], u: ["\u01b1", "\u054d"], v: ["\u05d8"], w: ["\u0428", "\u0460", "\u047c", "\u0d70"], x: ["\u04b2", "\u04fe", "\u04fc", "\u04fd"], y: ["\u00a5", "\u04b0", "\u04cb"], z: ["\u01b5", "\u0240"] } text.forEach(function(c){ c = c.toLowerCase(); var chars = trap[c] || [" "]; var rand = Math.floor(Math.random() * chars.length); if (typeof trap[c] !== "undefined") { result += trap[c][rand]; } else { result += c; } }); return result; } },{}],125:[function(require,module,exports){ // please no module['exports'] = function zalgo(text, options) { text = text || " he is here "; var soul = { "up" : [ '̍', '̎', '̄', '̅', '̿', '̑', '̆', '̐', '͒', '͗', '͑', '̇', '̈', '̊', '͂', '̓', '̈', '͊', '͋', '͌', '̃', '̂', '̌', '͐', '̀', '́', '̋', '̏', '̒', '̓', '̔', '̽', '̉', 'ͣ', 'ͤ', 'ͥ', 'ͦ', 'ͧ', 'ͨ', 'ͩ', 'ͪ', 'ͫ', 'ͬ', 'ͭ', 'ͮ', 'ͯ', '̾', '͛', '͆', '̚' ], "down" : [ '̖', '̗', '̘', '̙', '̜', '̝', '̞', '̟', '̠', '̤', '̥', '̦', '̩', '̪', '̫', '̬', '̭', '̮', '̯', '̰', '̱', '̲', '̳', '̹', '̺', '̻', '̼', 'ͅ', '͇', '͈', '͉', '͍', '͎', '͓', '͔', '͕', '͖', '͙', '͚', '̣' ], "mid" : [ '̕', '̛', '̀', '́', '͘', '̡', '̢', '̧', '̨', '̴', '̵', '̶', '͜', '͝', '͞', '͟', '͠', '͢', '̸', '̷', '͡', ' ҉' ] }, all = [].concat(soul.up, soul.down, soul.mid), zalgo = {}; function randomNumber(range) { var r = Math.floor(Math.random() * range); return r; } function is_char(character) { var bool = false; all.filter(function (i) { bool = (i === character); }); return bool; } function heComes(text, options) { var result = '', counts, l; options = options || {}; options["up"] = options["up"] || true; options["mid"] = options["mid"] || true; options["down"] = options["down"] || true; options["size"] = options["size"] || "maxi"; text = text.split(''); for (l in text) { if (is_char(l)) { continue; } result = result + text[l]; counts = {"up" : 0, "down" : 0, "mid" : 0}; switch (options.size) { case 'mini': counts.up = randomNumber(8); counts.min = randomNumber(2); counts.down = randomNumber(8); break; case 'maxi': counts.up = randomNumber(16) + 3; counts.min = randomNumber(4) + 1; counts.down = randomNumber(64) + 3; break; default: counts.up = randomNumber(8) + 1; counts.mid = randomNumber(6) / 2; counts.down = randomNumber(8) + 1; break; } var arr = ["up", "mid", "down"]; for (var d in arr) { var index = arr[d]; for (var i = 0 ; i <= counts[index]; i++) { if (options[index]) { result = result + soul[index][randomNumber(soul[index].length)]; } } } } return result; } // don't summon him return heComes(text); } },{}],126:[function(require,module,exports){ var colors = require('../colors'); module['exports'] = (function() { return function (letter, i, exploded) { if(letter === " ") return letter; switch(i%3) { case 0: return colors.red(letter); case 1: return colors.white(letter) case 2: return colors.blue(letter) } } })(); },{"../colors":123}],127:[function(require,module,exports){ var colors = require('../colors'); module['exports'] = (function () { var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV return function (letter, i, exploded) { if (letter === " ") { return letter; } else { return colors[rainbowColors[i++ % rainbowColors.length]](letter); } }; })(); },{"../colors":123}],128:[function(require,module,exports){ var colors = require('../colors'); module['exports'] = (function () { var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta']; return function(letter, i, exploded) { return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter); }; })(); },{"../colors":123}],129:[function(require,module,exports){ var colors = require('../colors'); module['exports'] = function (letter, i, exploded) { return i % 2 === 0 ? letter : colors.inverse(letter); }; },{"../colors":123}],130:[function(require,module,exports){ /* The MIT License (MIT) Copyright (c) Sindre Sorhus (sindresorhus.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 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 styles = {}; module['exports'] = styles; var codes = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // legacy styles for colors pre v1.0.0 blackBG: [40, 49], redBG: [41, 49], greenBG: [42, 49], yellowBG: [43, 49], blueBG: [44, 49], magentaBG: [45, 49], cyanBG: [46, 49], whiteBG: [47, 49] }; Object.keys(codes).forEach(function (key) { var val = codes[key]; var style = styles[key] = []; style.open = '\u001b[' + val[0] + 'm'; style.close = '\u001b[' + val[1] + 'm'; }); },{}],131:[function(require,module,exports){ (function (process){ /* The MIT License (MIT) Copyright (c) Sindre Sorhus (sindresorhus.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 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 argv = process.argv; module.exports = (function () { if (argv.indexOf('--no-color') !== -1 || argv.indexOf('--color=false') !== -1) { return false; } if (argv.indexOf('--color') !== -1 || argv.indexOf('--color=true') !== -1 || argv.indexOf('--color=always') !== -1) { return true; } if (process.stdout && !process.stdout.isTTY) { return false; } if (process.platform === 'win32') { return true; } if ('COLORTERM' in process.env) { return true; } if (process.env.TERM === 'dumb') { return false; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { return true; } return false; })(); }).call(this,require('_process')) },{"_process":149}],132:[function(require,module,exports){ // // Remark: Requiring this file will use the "safe" colors API which will not touch String.prototype // // var colors = require('colors/safe); // colors.red("foo") // // var colors = require('./lib/colors'); module['exports'] = colors; },{"./lib/colors":123}],133:[function(require,module,exports){ (function (global){ /** * @license * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modern -o ./dist/lodash.js` * Copyright 2012-2013 The Dojo Foundation * Based on Underscore.js 1.5.2 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license */ ;(function() { /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; /** Used to pool arrays and objects used internally */ var arrayPool = [], objectPool = []; /** Used to generate unique IDs */ var idCounter = 0; /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ var keyPrefix = +new Date + ''; /** Used as the size when optimizations are enabled for large arrays */ var largeArraySize = 75; /** Used as the max size of the `arrayPool` and `objectPool` */ var maxPoolSize = 40; /** Used to detect and test whitespace */ var whitespace = ( // whitespace ' \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 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 ES6 template delimiters * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match regexp flags from their coerced string values */ var reFlags = /\w*$/; /** Used to detected named functions */ var reFuncName = /^\s*function[ \n\r\t]+\w/; /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match leading whitespace and zeros to be removed */ var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); /** Used to ensure capturing order of template delimiters */ var reNoMatch = /($^)/; /** Used to detect functions containing a `this` reference */ var reThis = /\bthis\b/; /** Used to match unescaped characters in compiled string literals */ var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; /** Used to assign default `context` object properties */ var contextProps = [ 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify */ var templateCounter = 0; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; /** Used to identify object classifications that `_.clone` supports */ var cloneableClasses = {}; cloneableClasses[funcClass] = false; cloneableClasses[argsClass] = cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] = cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; /** Used as an internal `_.debounce` options object */ var debounceOptions = { 'leading': false, 'maxWait': 0, 'trailing': false }; /** Used as the property descriptor for `__bindData__` */ var descriptor = { 'configurable': false, 'enumerable': false, 'value': null, 'writable': false }; /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** Used to escape characters for inclusion in compiled string literals */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Used as a reference to the global object */ var root = (objectTypes[typeof window] && window) || this; /** 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 the popular CommonJS extension `module.exports` */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.indexOf` without support for binary searches * or `fromIndex` constraints. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. */ function baseIndexOf(array, value, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * An implementation of `_.contains` for cache objects that mimics the return * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. * * @private * @param {Object} cache The cache object to inspect. * @param {*} value The value to search for. * @returns {number} Returns `0` if `value` is found, else `-1`. */ function cacheIndexOf(cache, value) { var type = typeof value; cache = cache.cache; if (type == 'boolean' || value == null) { return cache[value] ? 0 : -1; } if (type != 'number' && type != 'string') { type = 'object'; } var key = type == 'number' ? value : keyPrefix + value; cache = (cache = cache[type]) && cache[key]; return type == 'object' ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) : (cache ? 0 : -1); } /** * Adds a given value to the corresponding cache object. * * @private * @param {*} value The value to add to the cache. */ function cachePush(value) { var cache = this.cache, type = typeof value; if (type == 'boolean' || value == null) { cache[value] = true; } else { if (type != 'number' && type != 'string') { type = 'object'; } var key = type == 'number' ? value : keyPrefix + value, typeCache = cache[type] || (cache[type] = {}); if (type == 'object') { (typeCache[key] || (typeCache[key] = [])).push(value); } else { typeCache[key] = true; } } } /** * Used by `_.max` and `_.min` as the default callback when a given * collection is a string value. * * @private * @param {string} value The character to inspect. * @returns {number} Returns the code unit of given character. */ function charAtCallback(value) { return value.charCodeAt(0); } /** * Used by `sortBy` to compare transformed `collection` elements, stable sorting * them in ascending order. * * @private * @param {Object} a The object to compare to `b`. * @param {Object} b The object to compare to `a`. * @returns {number} Returns the sort order indicator of `1` or `-1`. */ function compareAscending(a, b) { var ac = a.criteria, bc = b.criteria, index = -1, length = ac.length; while (++index < length) { var value = ac[index], other = bc[index]; if (value !== other) { if (value > other || typeof value == 'undefined') { return 1; } if (value < other || typeof other == 'undefined') { return -1; } } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to return the same value for // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 // // This also ensures a stable sort in V8 and other engines. // See http://code.google.com/p/v8/issues/detail?id=90 return a.index - b.index; } /** * Creates a cache object to optimize linear searches of large arrays. * * @private * @param {Array} [array=[]] The array to search. * @returns {null|Object} Returns the cache object or `null` if caching should not be used. */ function createCache(array) { var index = -1, length = array.length, first = array[0], mid = array[(length / 2) | 0], last = array[length - 1]; if (first && typeof first == 'object' && mid && typeof mid == 'object' && last && typeof last == 'object') { return false; } var cache = getObject(); cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; var result = getObject(); result.array = array; result.cache = cache; result.push = cachePush; while (++index < length) { result.push(array[index]); } return result; } /** * Used by `template` to escape characters for inclusion in compiled * string literals. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(match) { return '\\' + stringEscapes[match]; } /** * Gets an array from the array pool or creates a new one if the pool is empty. * * @private * @returns {Array} The array from the pool. */ function getArray() { return arrayPool.pop() || []; } /** * Gets an object from the object pool or creates a new one if the pool is empty. * * @private * @returns {Object} The object from the pool. */ function getObject() { return objectPool.pop() || { 'array': null, 'cache': null, 'criteria': null, 'false': false, 'index': 0, 'null': false, 'number': null, 'object': null, 'push': null, 'string': null, 'true': false, 'undefined': false, 'value': null }; } /** * Releases the given array back to the array pool. * * @private * @param {Array} [array] The array to release. */ function releaseArray(array) { array.length = 0; if (arrayPool.length < maxPoolSize) { arrayPool.push(array); } } /** * Releases the given object back to the object pool. * * @private * @param {Object} [object] The object to release. */ function releaseObject(object) { var cache = object.cache; if (cache) { releaseObject(cache); } object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; if (objectPool.length < maxPoolSize) { objectPool.push(object); } } /** * Slices the `collection` from the `start` index up to, but not including, * the `end` index. * * Note: This function is used instead of `Array#slice` to support node lists * in IE < 9 and to ensure dense arrays are returned. * * @private * @param {Array|Object|string} collection The collection to slice. * @param {number} start The start index. * @param {number} end The end index. * @returns {Array} Returns the new array. */ function slice(array, start, end) { start || (start = 0); if (typeof end == 'undefined') { end = array ? array.length : 0; } var index = -1, length = end - start || 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = array[start + index]; } return result; } /*--------------------------------------------------------------------------*/ /** * Create a new `lodash` function using the given context object. * * @static * @memberOf _ * @category Utilities * @param {Object} [context=root] The context object. * @returns {Function} Returns the `lodash` function. */ 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 http://es5.github.io/#x11.1.5. context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; /** Native constructor references */ var Array = context.Array, Boolean = context.Boolean, Date = context.Date, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Used for native method references */ var objectProto = Object.prototype; /** Used to restore the original `_` reference in `noConflict` */ var oldDash = context._; /** Used to resolve the internal [[Class]] of values */ var toString = objectProto.toString; /** Used to detect if a method is native */ var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); /** Native method shortcuts */ var ceil = Math.ceil, clearTimeout = context.clearTimeout, floor = Math.floor, fnToString = Function.prototype.toString, getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, hasOwnProperty = objectProto.hasOwnProperty, push = arrayRef.push, setTimeout = context.setTimeout, splice = arrayRef.splice, unshift = arrayRef.unshift; /** Used to set meta data on functions */ var defineProperty = (function() { // IE 8 only accepts DOM elements try { var o = {}, func = isNative(func = Object.defineProperty) && func, result = func(o, o, o) && func; } catch(e) { } return result; }()); /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, nativeIsFinite = context.isFinite, nativeIsNaN = context.isNaN, nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min, nativeParseInt = context.parseInt, nativeRandom = Math.random; /** Used to lookup a built-in constructor by [[Class]] */ var ctorByClass = {}; ctorByClass[arrayClass] = Array; ctorByClass[boolClass] = Boolean; ctorByClass[dateClass] = Date; ctorByClass[funcClass] = Function; ctorByClass[objectClass] = Object; ctorByClass[numberClass] = Number; ctorByClass[regexpClass] = RegExp; ctorByClass[stringClass] = String; /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps the given value to enable intuitive * method chaining. * * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, * and `unshift` * * Chaining is supported in custom builds as long as the `value` method is * implicitly or explicitly included in the build. * * The chainable wrapper functions are: * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, * and `zip` * * The non-chainable wrapper functions are: * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, * `template`, `unescape`, `uniqueId`, and `value` * * The wrapper functions `first` and `last` return wrapped values when `n` is * provided, otherwise they return unwrapped values. * * Explicit chaining can be enabled by using the `_.chain` method. * * @name _ * @constructor * @category Chaining * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(sum, num) { * return sum + num; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(num) { * return num * num; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) ? value : new lodashWrapper(value); } /** * A fast path for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap in a `lodash` instance. * @param {boolean} chainAll A flag to enable chaining for all methods * @returns {Object} Returns a `lodash` instance. */ function lodashWrapper(value, chainAll) { this.__chain__ = !!chainAll; this.__wrapped__ = value; } // ensure `new lodashWrapper` is an instance of `lodash` lodashWrapper.prototype = lodash.prototype; /** * An object used to flag environments features. * * @static * @memberOf _ * @type Object */ var support = lodash.support = {}; /** * Detect if functions can be decompiled by `Function#toString` * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). * * @memberOf _.support * @type boolean */ support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); /** * Detect if `Function#name` is supported (all but IE). * * @memberOf _.support * @type boolean */ support.funcNames = typeof Function.name == 'string'; /** * By default, the template delimiters used by Lo-Dash are similar to 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': /<%-([\s\S]+?)%>/g, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': /<%([\s\S]+?)%>/g, /** * 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 } }; /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.bind` that creates the bound function and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new bound function. */ function baseBind(bindData) { var func = bindData[0], partialArgs = bindData[2], thisArg = bindData[4]; function bound() { // `Function#bind` spec // http://es5.github.io/#x15.3.4.5 if (partialArgs) { // avoid `arguments` object deoptimizations by using `slice` instead // of `Array.prototype.slice.call` and not assigning `arguments` to a // variable as a ternary expression var args = slice(partialArgs); push.apply(args, arguments); } // mimic the constructor's `return` behavior // http://es5.github.io/#x13.2.2 if (this instanceof bound) { // ensure `new bound` is an instance of `func` var thisBinding = baseCreate(func.prototype), result = func.apply(thisBinding, args || arguments); return isObject(result) ? result : thisBinding; } return func.apply(thisArg, args || arguments); } setBindData(bound, bindData); return bound; } /** * The base implementation of `_.clone` without argument juggling or support * for `thisArg` binding. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates clones with source counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, callback, stackA, stackB) { if (callback) { var result = callback(value); if (typeof result != 'undefined') { return result; } } // inspect [[Class]] var isObj = isObject(value); if (isObj) { var className = toString.call(value); if (!cloneableClasses[className]) { return value; } var ctor = ctorByClass[className]; switch (className) { case boolClass: case dateClass: return new ctor(+value); case numberClass: case stringClass: return new ctor(value); case regexpClass: result = ctor(value.source, reFlags.exec(value)); result.lastIndex = value.lastIndex; return result; } } else { return value; } var isArr = isArray(value); if (isDeep) { // check for circular references and return corresponding clone var initedStack = !stackA; stackA || (stackA = getArray()); stackB || (stackB = getArray()); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } result = isArr ? ctor(value.length) : {}; } else { result = isArr ? slice(value) : assign({}, value); } // add array properties assigned by `RegExp#exec` if (isArr) { if (hasOwnProperty.call(value, 'index')) { result.index = value.index; } if (hasOwnProperty.call(value, 'input')) { result.input = value.input; } } // exit for shallow clone if (!isDeep) { return result; } // 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 ? forEach : forOwn)(value, function(objValue, key) { result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); }); if (initedStack) { releaseArray(stackA); releaseArray(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. */ function baseCreate(prototype, properties) { return isObject(prototype) ? nativeCreate(prototype) : {}; } // fallback for browsers without `Object.create` if (!nativeCreate) { 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 `_.createCallback` without support for creating * "_.pluck" or "_.where" style callbacks. * * @private * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. */ function baseCreateCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } // exit early for no `thisArg` or already bound by `Function#bind` if (typeof thisArg == 'undefined' || !('prototype' in func)) { return func; } var bindData = func.__bindData__; if (typeof bindData == 'undefined') { if (support.funcNames) { bindData = !func.name; } bindData = bindData || !support.funcDecomp; if (!bindData) { var source = fnToString.call(func); if (!support.funcNames) { bindData = !reFuncName.test(source); } if (!bindData) { // checks if `func` references the `this` keyword and stores the result bindData = reThis.test(source); setBindData(func, bindData); } } } // exit early if there are no `this` references or `func` is bound if (bindData === false || (bindData !== true && bindData[1] & 1)) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 2: return function(a, b) { return func.call(thisArg, a, b); }; 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); }; } return bind(func, thisArg); } /** * The base implementation of `createWrapper` that creates the wrapper and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new function. */ function baseCreateWrapper(bindData) { var func = bindData[0], bitmask = bindData[1], partialArgs = bindData[2], partialRightArgs = bindData[3], thisArg = bindData[4], arity = bindData[5]; var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, key = func; function bound() { var thisBinding = isBind ? thisArg : this; if (partialArgs) { var args = slice(partialArgs); push.apply(args, arguments); } if (partialRightArgs || isCurry) { args || (args = slice(arguments)); if (partialRightArgs) { push.apply(args, partialRightArgs); } if (isCurry && args.length < arity) { bitmask |= 16 & ~32; return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); } } args || (args = arguments); if (isBindKey) { func = thisBinding[key]; } if (this instanceof bound) { thisBinding = baseCreate(func.prototype); var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } setBindData(bound, bindData); return bound; } /** * The base implementation of `_.difference` that accepts a single array * of values to exclude. * * @private * @param {Array} array The array to process. * @param {Array} [values] The array of values to exclude. * @returns {Array} Returns a new array of filtered values. */ function baseDifference(array, values) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, isLarge = length >= largeArraySize && indexOf === baseIndexOf, result = []; if (isLarge) { var cache = createCache(values); if (cache) { indexOf = cacheIndexOf; values = cache; } else { isLarge = false; } } while (++index < length) { var value = array[index]; if (indexOf(values, value) < 0) { result.push(value); } } if (isLarge) { releaseObject(values); } return result; } /** * The base implementation of `_.flatten` without support for callback * shorthands or `thisArg` binding. * * @private * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. * @param {number} [fromIndex=0] The index to start from. * @returns {Array} Returns a new flattened array. */ function baseFlatten(array, isShallow, isStrict, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value && typeof value == 'object' && typeof value.length == 'number' && (isArray(value) || isArguments(value))) { // recursively flatten arrays (susceptible to call stack limits) if (!isShallow) { value = baseFlatten(value, isShallow, isStrict); } var valIndex = -1, valLength = value.length, resIndex = result.length; result.length += valLength; while (++valIndex < valLength) { result[resIndex++] = value[valIndex]; } } else if (!isStrict) { result.push(value); } } return result; } /** * The base implementation of `_.isEqual`, without support for `thisArg` binding, * that allows partial "_.where" style comparisons. * * @private * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `a` objects. * @param {Array} [stackB=[]] Tracks traversed `b` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { // used to indicate that when comparing objects, `a` has at least the properties of `b` if (callback) { var result = callback(a, b); if (typeof result != 'undefined') { return !!result; } } // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && !(a && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } // exit early for `null` and `undefined` avoiding ES3's Function#call behavior // http://es5.github.io/#x15.3.4.4 if (a == null || b == null) { return a === b; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // 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 +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `+0` vs. `-0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // unwrap any `lodash` wrapped values var aWrapped = hasOwnProperty.call(a, '__wrapped__'), bWrapped = hasOwnProperty.call(b, '__wrapped__'); if (aWrapped || bWrapped) { return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); } // exit for functions and DOM nodes if (className != objectClass) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = a.constructor, ctorB = b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = getArray()); stackB || (stackB = getArray()); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result || isWhere) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (isWhere) { while (index--) { if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { break; } } } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly forIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); } }); if (result && !isWhere) { // ensure both objects have the same number of properties forIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); if (initedStack) { releaseArray(stackA); releaseArray(stackB); } return result; } /** * The base implementation of `_.merge` without argument juggling or support * for `thisArg` binding. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [callback] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. */ function baseMerge(object, source, callback, stackA, stackB) { (isArray(source) ? forEach : forOwn)(source, function(source, key) { var found, isArr, result = source, value = object[key]; if (source && ((isArr = isArray(source)) || isPlainObject(source))) { // avoid merging previously merged cyclic sources var stackLength = stackA.length; while (stackLength--) { if ((found = stackA[stackLength] == source)) { value = stackB[stackLength]; break; } } if (!found) { var isShallow; if (callback) { result = callback(value, source); if ((isShallow = typeof result != 'undefined')) { value = result; } } if (!isShallow) { value = isArr ? (isArray(value) ? value : []) : (isPlainObject(value) ? value : {}); } // add `source` and associated `value` to the stack of traversed objects stackA.push(source); stackB.push(value); // recursively merge objects and arrays (susceptible to call stack limits) if (!isShallow) { baseMerge(value, source, callback, stackA, stackB); } } } else { if (callback) { result = callback(value, source); if (typeof result == 'undefined') { result = source; } } if (typeof result != 'undefined') { value = result; } } object[key] = value; }); } /** * The base implementation of `_.random` without argument juggling or support * for returning floating-point numbers. * * @private * @param {number} min The minimum possible value. * @param {number} max The maximum possible value. * @returns {number} Returns a random number. */ function baseRandom(min, max) { return min + floor(nativeRandom() * (max - min + 1)); } /** * The base implementation of `_.uniq` without support for callback shorthands * or `thisArg` binding. * * @private * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function} [callback] The function called per iteration. * @returns {Array} Returns a duplicate-value-free array. */ function baseUniq(array, isSorted, callback) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, result = []; var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, seen = (callback || isLarge) ? getArray() : result; if (isLarge) { var cache = createCache(seen); indexOf = cacheIndexOf; seen = cache; } while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; if (isSorted ? !index || seen[seen.length - 1] !== computed : indexOf(seen, computed) < 0 ) { if (callback || isLarge) { seen.push(computed); } result.push(value); } } if (isLarge) { releaseArray(seen.array); releaseObject(seen); } else if (callback) { releaseArray(seen); } return result; } /** * Creates a function that aggregates a collection, creating an object composed * of keys generated from the results of running each element of the collection * through a callback. The given `setter` function sets the keys and values * of the composed object. * * @private * @param {Function} setter The setter function. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter) { return function(collection, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; setter(result, value, callback(value, index, collection), collection); } } else { forOwn(collection, function(value, key, collection) { setter(result, value, callback(value, key, collection), collection); }); } return result; }; } /** * Creates a function that, when called, either curries or invokes `func` * with an 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 method flags to compose. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` * 8 - `_.curry` (bound) * 16 - `_.partial` * 32 - `_.partialRight` * @param {Array} [partialArgs] An array of arguments to prepend to those * provided to the new function. * @param {Array} [partialRightArgs] An array of arguments to append to those * provided to the new function. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new function. */ function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, isPartial = bitmask & 16, isPartialRight = bitmask & 32; if (!isBindKey && !isFunction(func)) { throw new TypeError; } if (isPartial && !partialArgs.length) { bitmask &= ~16; isPartial = partialArgs = false; } if (isPartialRight && !partialRightArgs.length) { bitmask &= ~32; isPartialRight = partialRightArgs = false; } var bindData = func && func.__bindData__; if (bindData && bindData !== true) { // clone `bindData` bindData = slice(bindData); if (bindData[2]) { bindData[2] = slice(bindData[2]); } if (bindData[3]) { bindData[3] = slice(bindData[3]); } // set `thisBinding` is not previously bound if (isBind && !(bindData[1] & 1)) { bindData[4] = thisArg; } // set if previously bound but not currently (subsequent curried functions) if (!isBind && bindData[1] & 1) { bitmask |= 8; } // set curried arity if not yet set if (isCurry && !(bindData[1] & 4)) { bindData[5] = arity; } // append partial left arguments if (isPartial) { push.apply(bindData[2] || (bindData[2] = []), partialArgs); } // append partial right arguments if (isPartialRight) { unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); } // merge flags bindData[1] |= bitmask; return createWrapper.apply(null, bindData); } // fast path for `_.bind` var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); } /** * Used by `escape` to convert characters to HTML entities. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(match) { return htmlEscapes[match]; } /** * Gets the appropriate "indexOf" function. If the `_.indexOf` method is * customized, this method returns the custom method, otherwise it returns * the `baseIndexOf` function. * * @private * @returns {Function} Returns the "indexOf" function. */ function getIndexOf() { var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; return result; } /** * Checks if `value` is a native function. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. */ function isNative(value) { return typeof value == 'function' && reNative.test(value); } /** * Sets `this` binding data on a given function. * * @private * @param {Function} func The function to set data on. * @param {Array} value The data array to set. */ var setBindData = !defineProperty ? noop : function(func, value) { descriptor.value = value; defineProperty(func, '__bindData__', descriptor); }; /** * A fallback implementation of `isPlainObject` which checks if a given value * is an object created by the `Object` constructor, assuming objects created * by the `Object` constructor have no inherited enumerable properties and that * there are no `Object.prototype` extensions. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { var ctor, result; // avoid non Object objects, `arguments` objects, and DOM elements if (!(value && toString.call(value) == objectClass) || (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) { return false; } // 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. forIn(value, function(value, key) { result = key; }); return typeof result == 'undefined' || hasOwnProperty.call(value, result); } /** * Used by `unescape` to convert HTML entities to characters. * * @private * @param {string} match The matched character to unescape. * @returns {string} Returns the unescaped character. */ function unescapeHtmlChar(match) { return htmlUnescapes[match]; } /*--------------------------------------------------------------------------*/ /** * Checks if `value` is an `arguments` object. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. * @example * * (function() { return _.isArguments(arguments); })(1, 2, 3); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == argsClass || false; } /** * Checks if `value` is an array. * * @static * @memberOf _ * @type Function * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an array, else `false`. * @example * * (function() { return _.isArray(arguments); })(); * // => false * * _.isArray([1, 2, 3]); * // => true */ var isArray = nativeIsArray || function(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == arrayClass || false; }; /** * A fallback implementation of `Object.keys` which produces an array of the * given object's own enumerable property names. * * @private * @type Function * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. */ var shimKeys = function(object) { var index, iterable = object, result = []; if (!iterable) return result; if (!(objectTypes[typeof object])) return result; for (index in iterable) { if (hasOwnProperty.call(iterable, index)) { result.push(index); } } return result }; /** * Creates an array composed of the own enumerable property names of an object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. * @example * * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) */ var keys = !nativeKeys ? shimKeys : function(object) { if (!isObject(object)) { return []; } return nativeKeys(object); }; /** * Used to convert characters to HTML entities: * * 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 an unquoted attribute value. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; /** Used to convert HTML entities to characters */ var htmlUnescapes = invert(htmlEscapes); /** Used to match HTML entities and HTML characters */ var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); /*--------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources will overwrite property assignments of previous * sources. If a callback is provided it will be executed to produce the * assigned values. The callback is bound to `thisArg` and invoked with two * arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @type Function * @alias extend * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param {Function} [callback] The function to customize assigning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); * // => { 'name': 'fred', 'employer': 'slate' } * * var defaults = _.partialRight(_.assign, function(a, b) { * return typeof a == 'undefined' ? b : a; * }); * * var object = { 'name': 'barney' }; * defaults(object, { 'name': 'fred', 'employer': 'slate' }); * // => { 'name': 'barney', 'employer': 'slate' } */ var assign = function(object, source, guard) { var index, iterable = object, result = iterable; if (!iterable) return result; var args = arguments, argsIndex = 0, argsLength = typeof guard == 'number' ? 2 : args.length; if (argsLength > 3 && typeof args[argsLength - 2] == 'function') { var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2); } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') { callback = args[--argsLength]; } while (++argsIndex < argsLength) { iterable = args[argsIndex]; if (iterable && objectTypes[typeof iterable]) { var ownIndex = -1, ownProps = objectTypes[typeof iterable] && keys(iterable), length = ownProps ? ownProps.length : 0; while (++ownIndex < length) { index = ownProps[ownIndex]; result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]; } } } return result }; /** * Creates a clone of `value`. If `isDeep` is `true` nested objects will also * be cloned, otherwise they will be assigned by reference. If a callback * is provided it will be executed to produce the cloned values. If the * callback returns `undefined` cloning will be handled by the method instead. * The callback is bound to `thisArg` and invoked with one argument; (value). * * @static * @memberOf _ * @category Objects * @param {*} value The value to clone. * @param {boolean} [isDeep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the cloned value. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * var shallow = _.clone(characters); * shallow[0] === characters[0]; * // => true * * var deep = _.clone(characters, true); * deep[0] === characters[0]; * // => false * * _.mixin({ * 'clone': _.partialRight(_.clone, function(value) { * return _.isElement(value) ? value.cloneNode(false) : undefined; * }) * }); * * var clone = _.clone(document.body); * clone.childNodes.length; * // => 0 */ function clone(value, isDeep, callback, thisArg) { // allows working with "Collections" methods without using their `index` // and `collection` arguments for `isDeep` and `callback` if (typeof isDeep != 'boolean' && isDeep != null) { thisArg = callback; callback = isDeep; isDeep = false; } return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); } /** * Creates a deep clone of `value`. If a callback is provided it will be * executed to produce the cloned values. If the callback returns `undefined` * cloning will be handled by the method instead. The callback is bound to * `thisArg` and invoked with one argument; (value). * * Note: This method is loosely based on the structured clone algorithm. Functions * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and * objects created by constructors other than `Object` are cloned to plain `Object` objects. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. * * @static * @memberOf _ * @category Objects * @param {*} value The value to deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the deep cloned value. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * var deep = _.cloneDeep(characters); * deep[0] === characters[0]; * // => false * * var view = { * 'label': 'docs', * 'node': element * }; * * var clone = _.cloneDeep(view, function(value) { * return _.isElement(value) ? value.cloneNode(true) : undefined; * }); * * clone.node == view.node; * // => false */ function cloneDeep(value, callback, thisArg) { return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); } /** * 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 Objects * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @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) { var result = baseCreate(prototype); return properties ? assign(result, 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 defaults of the same property will be ignored. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param- {Object} [guard] Allows working with `_.reduce` without using its * `key` and `object` arguments as sources. * @returns {Object} Returns the destination object. * @example * * var object = { 'name': 'barney' }; * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); * // => { 'name': 'barney', 'employer': 'slate' } */ var defaults = function(object, source, guard) { var index, iterable = object, result = iterable; if (!iterable) return result; var args = arguments, argsIndex = 0, argsLength = typeof guard == 'number' ? 2 : args.length; while (++argsIndex < argsLength) { iterable = args[argsIndex]; if (iterable && objectTypes[typeof iterable]) { var ownIndex = -1, ownProps = objectTypes[typeof iterable] && keys(iterable), length = ownProps ? ownProps.length : 0; while (++ownIndex < length) { index = ownProps[ownIndex]; if (typeof result[index] == 'undefined') result[index] = iterable[index]; } } } return result }; /** * This method is like `_.findIndex` except that it returns the key of the * first element that passes the callback check, instead of the element itself. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|string} [callback=identity] The function called per * iteration. If a property name or object is provided it will be used to * create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {string|undefined} Returns the key of the found element, else `undefined`. * @example * * var characters = { * 'barney': { 'age': 36, 'blocked': false }, * 'fred': { 'age': 40, 'blocked': true }, * 'pebbles': { 'age': 1, 'blocked': false } * }; * * _.findKey(characters, function(chr) { * return chr.age < 40; * }); * // => 'barney' (property order is not guaranteed across environments) * * // using "_.where" callback shorthand * _.findKey(characters, { 'age': 1 }); * // => 'pebbles' * * // using "_.pluck" callback shorthand * _.findKey(characters, 'blocked'); * // => 'fred' */ function findKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forOwn(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * 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 `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|string} [callback=identity] The function called per * iteration. If a property name or object is provided it will be used to * create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {string|undefined} Returns the key of the found element, else `undefined`. * @example * * var characters = { * 'barney': { 'age': 36, 'blocked': true }, * 'fred': { 'age': 40, 'blocked': false }, * 'pebbles': { 'age': 1, 'blocked': true } * }; * * _.findLastKey(characters, function(chr) { * return chr.age < 40; * }); * // => returns `pebbles`, assuming `_.findKey` returns `barney` * * // using "_.where" callback shorthand * _.findLastKey(characters, { 'age': 40 }); * // => 'fred' * * // using "_.pluck" callback shorthand * _.findLastKey(characters, 'blocked'); * // => 'pebbles' */ function findLastKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forOwnRight(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * Iterates over own and inherited enumerable properties of an object, * executing the callback for each property. The callback is bound to `thisArg` * and invoked with three arguments; (value, key, object). Callbacks may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * Shape.prototype.move = function(x, y) { * this.x += x; * this.y += y; * }; * * _.forIn(new Shape, function(value, key) { * console.log(key); * }); * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) */ var forIn = function(collection, callback, thisArg) { var index, iterable = collection, result = iterable; if (!iterable) return result; if (!objectTypes[typeof iterable]) return result; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); for (index in iterable) { if (callback(iterable[index], index, collection) === false) return result; } return result }; /** * This method is like `_.forIn` except that it iterates over elements * of a `collection` in the opposite order. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * Shape.prototype.move = function(x, y) { * this.x += x; * this.y += y; * }; * * _.forInRight(new Shape, function(value, key) { * console.log(key); * }); * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' */ function forInRight(object, callback, thisArg) { var pairs = []; forIn(object, function(value, key) { pairs.push(key, value); }); var length = pairs.length; callback = baseCreateCallback(callback, thisArg, 3); while (length--) { if (callback(pairs[length--], pairs[length], object) === false) { break; } } return object; } /** * Iterates over own enumerable properties of an object, executing the callback * for each property. The callback is bound to `thisArg` and invoked with three * arguments; (value, key, object). Callbacks may exit iteration early by * explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) */ var forOwn = function(collection, callback, thisArg) { var index, iterable = collection, result = iterable; if (!iterable) return result; if (!objectTypes[typeof iterable]) return result; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); var ownIndex = -1, ownProps = objectTypes[typeof iterable] && keys(iterable), length = ownProps ? ownProps.length : 0; while (++ownIndex < length) { index = ownProps[ownIndex]; if (callback(iterable[index], index, collection) === false) return result; } return result }; /** * This method is like `_.forOwn` except that it iterates over elements * of a `collection` in the opposite order. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' */ function forOwnRight(object, callback, thisArg) { var props = keys(object), length = props.length; callback = baseCreateCallback(callback, thisArg, 3); while (length--) { var key = props[length]; if (callback(object[key], key, object) === false) { break; } } return object; } /** * Creates a sorted array of property names of all enumerable properties, * own and inherited, of `object` that have function values. * * @static * @memberOf _ * @alias methods * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names that have function values. * @example * * _.functions(_); * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] */ function functions(object) { var result = []; forIn(object, function(value, key) { if (isFunction(value)) { result.push(key); } }); return result.sort(); } /** * Checks if the specified property name exists as a direct property of `object`, * instead of an inherited property. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @param {string} key The name of the property to check. * @returns {boolean} Returns `true` if key is a direct property, else `false`. * @example * * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); * // => true */ function has(object, key) { return object ? hasOwnProperty.call(object, key) : false; } /** * Creates an object composed of the inverted keys and values of the given object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to invert. * @returns {Object} Returns the created inverted object. * @example * * _.invert({ 'first': 'fred', 'second': 'barney' }); * // => { 'fred': 'first', 'barney': 'second' } */ function invert(object) { var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index]; result[object[key]] = key; } return result; } /** * Checks if `value` is a boolean value. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. * @example * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || value && typeof value == 'object' && toString.call(value) == boolClass || false; } /** * Checks if `value` is a date. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a date, else `false`. * @example * * _.isDate(new Date); * // => true */ function isDate(value) { return value && typeof value == 'object' && toString.call(value) == dateClass || false; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true */ function isElement(value) { return value && value.nodeType === 1 || false; } /** * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a * length of `0` and objects with no own enumerable properties are considered * "empty". * * @static * @memberOf _ * @category Objects * @param {Array|Object|string} value The value to inspect. * @returns {boolean} Returns `true` if the `value` is empty, else `false`. * @example * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({}); * // => true * * _.isEmpty(''); * // => true */ function isEmpty(value) { var result = true; if (!value) { return result; } var className = toString.call(value), length = value.length; if ((className == arrayClass || className == stringClass || className == argsClass ) || (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { return !length; } forOwn(value, function() { return (result = false); }); return result; } /** * Performs a deep comparison between two values to determine if they are * equivalent to each other. If a callback is provided it will be executed * to compare values. If the callback returns `undefined` comparisons will * be handled by the method instead. The callback is bound to `thisArg` and * invoked with two arguments; (a, b). * * @static * @memberOf _ * @category Objects * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'name': 'fred' }; * var copy = { 'name': 'fred' }; * * object == copy; * // => false * * _.isEqual(object, copy); * // => true * * var words = ['hello', 'goodbye']; * var otherWords = ['hi', 'goodbye']; * * _.isEqual(words, otherWords, function(a, b) { * var reGreet = /^(?:hello|hi)$/i, * aGreet = _.isString(a) && reGreet.test(a), * bGreet = _.isString(b) && reGreet.test(b); * * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; * }); * // => true */ function isEqual(a, b, callback, thisArg) { return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); } /** * Checks if `value` is, or can be coerced to, a finite number. * * Note: This is not the same as native `isFinite` which will return true for * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is finite, else `false`. * @example * * _.isFinite(-101); * // => true * * _.isFinite('10'); * // => true * * _.isFinite(true); * // => false * * _.isFinite(''); * // => false * * _.isFinite(Infinity); * // => false */ function isFinite(value) { return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); } /** * Checks if `value` is a function. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true */ function isFunction(value) { return typeof value == 'function'; } /** * Checks if `value` is the language type of Object. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 return !!(value && objectTypes[typeof value]); } /** * Checks if `value` is `NaN`. * * Note: This is not the same as native `isNaN` which will return `true` for * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // `NaN` as a primitive is the only value that is not equal to itself // (perform the [[Class]] check first to avoid errors with some host objects in IE) return isNumber(value) && value != +value; } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(undefined); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is a number. * * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a number, else `false`. * @example * * _.isNumber(8.4 * 5); * // => true */ function isNumber(value) { return typeof value == 'number' || value && typeof value == 'object' && toString.call(value) == numberClass || false; } /** * Checks if `value` is an object created by the `Object` constructor. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * _.isPlainObject(new Shape); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && toString.call(value) == objectClass)) { 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 a regular expression. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. * @example * * _.isRegExp(/fred/); * // => true */ function isRegExp(value) { return value && typeof value == 'object' && toString.call(value) == regexpClass || false; } /** * Checks if `value` is a string. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a string, else `false`. * @example * * _.isString('fred'); * // => true */ function isString(value) { return typeof value == 'string' || value && typeof value == 'object' && toString.call(value) == stringClass || false; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true */ function isUndefined(value) { return typeof value == 'undefined'; } /** * Creates an object with the same keys as `object` and values generated by * running each own enumerable property of `object` through the callback. * The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new object with values of the results of each `callback` execution. * @example * * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); * // => { 'a': 3, 'b': 6, 'c': 9 } * * var characters = { * 'fred': { 'name': 'fred', 'age': 40 }, * 'pebbles': { 'name': 'pebbles', 'age': 1 } * }; * * // using "_.pluck" callback shorthand * _.mapValues(characters, 'age'); * // => { 'fred': 40, 'pebbles': 1 } */ function mapValues(object, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg, 3); forOwn(object, function(value, key, object) { result[key] = callback(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 * will overwrite property assignments of previous sources. If a callback is * provided it will be executed to produce the merged values of the destination * and source properties. If the callback returns `undefined` merging will * be handled by the method instead. The callback is bound to `thisArg` and * invoked with two arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param {Function} [callback] The function to customize merging properties. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * var names = { * 'characters': [ * { 'name': 'barney' }, * { 'name': 'fred' } * ] * }; * * var ages = { * 'characters': [ * { 'age': 36 }, * { 'age': 40 } * ] * }; * * _.merge(names, ages); * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } * * var food = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var otherFood = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(food, otherFood, function(a, b) { * return _.isArray(a) ? a.concat(b) : undefined; * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } */ function merge(object) { var args = arguments, length = 2; if (!isObject(object)) { return object; } // allows working with `_.reduce` and `_.reduceRight` without using // their `index` and `collection` arguments if (typeof args[2] != 'number') { length = args.length; } if (length > 3 && typeof args[length - 2] == 'function') { var callback = baseCreateCallback(args[--length - 1], args[length--], 2); } else if (length > 2 && typeof args[length - 1] == 'function') { callback = args[--length]; } var sources = slice(arguments, 1, length), index = -1, stackA = getArray(), stackB = getArray(); while (++index < length) { baseMerge(object, sources[index], callback, stackA, stackB); } releaseArray(stackA); releaseArray(stackB); return object; } /** * Creates a shallow clone of `object` excluding the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` omitting the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The properties to omit or the * function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object without the omitted properties. * @example * * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); * // => { 'name': 'fred' } * * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { * return typeof value == 'number'; * }); * // => { 'name': 'fred' } */ function omit(object, callback, thisArg) { var result = {}; if (typeof callback != 'function') { var props = []; forIn(object, function(value, key) { props.push(key); }); props = baseDifference(props, baseFlatten(arguments, true, false, 1)); var index = -1, length = props.length; while (++index < length) { var key = props[index]; result[key] = object[key]; } } else { callback = lodash.createCallback(callback, thisArg, 3); forIn(object, function(value, key, object) { if (!callback(value, key, object)) { result[key] = value; } }); } return result; } /** * Creates a two dimensional array of an object's key-value pairs, * i.e. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) */ 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 a shallow clone of `object` composed of the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` picking the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The function called per * iteration or property names to pick, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object composed of the picked properties. * @example * * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); * // => { 'name': 'fred' } * * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { * return key.charAt(0) != '_'; * }); * // => { 'name': 'fred' } */ function pick(object, callback, thisArg) { var result = {}; if (typeof callback != 'function') { var index = -1, props = baseFlatten(arguments, true, false, 1), length = isObject(object) ? props.length : 0; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } } else { callback = lodash.createCallback(callback, thisArg, 3); forIn(object, function(value, key, object) { if (callback(value, key, object)) { result[key] = value; } }); } return result; } /** * 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 a callback, with each callback execution * potentially mutating the `accumulator` object. The callback is bound to * `thisArg` and invoked with four arguments; (accumulator, value, key, object). * Callbacks may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Objects * @param {Array|Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] The custom accumulator value. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { * num *= num; * if (num % 2) { * return result.push(num) < 3; * } * }); * // => [1, 9, 25] * * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * }); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function transform(object, callback, accumulator, thisArg) { var isArr = isArray(object); if (accumulator == null) { if (isArr) { accumulator = []; } else { var ctor = object && object.constructor, proto = ctor && ctor.prototype; accumulator = baseCreate(proto); } } if (callback) { callback = lodash.createCallback(callback, thisArg, 4); (isArr ? forEach : forOwn)(object, function(value, index, object) { return callback(accumulator, value, index, object); }); } return accumulator; } /** * Creates an array composed of the own enumerable property values of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property values. * @example * * _.values({ 'one': 1, 'two': 2, 'three': 3 }); * // => [1, 2, 3] (property order is not guaranteed across environments) */ function values(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /*--------------------------------------------------------------------------*/ /** * Creates an array of elements from the specified indexes, or keys, of the * `collection`. Indexes may be specified as individual arguments or as arrays * of indexes. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` * to retrieve, specified as individual indexes or arrays of indexes. * @returns {Array} Returns a new array of elements corresponding to the * provided indexes. * @example * * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); * // => ['a', 'c', 'e'] * * _.at(['fred', 'barney', 'pebbles'], 0, 2); * // => ['fred', 'pebbles'] */ function at(collection) { var args = arguments, index = -1, props = baseFlatten(args, true, false, 1), length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, result = Array(length); while(++index < length) { result[index] = collection[props[index]]; } return result; } /** * Checks if a given value is present in a collection using strict equality * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the * offset from the end of the collection. * * @static * @memberOf _ * @alias include * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {*} target The value to check for. * @param {number} [fromIndex=0] The index to search from. * @returns {boolean} Returns `true` if the `target` element is found, else `false`. * @example * * _.contains([1, 2, 3], 1); * // => true * * _.contains([1, 2, 3], 1, 2); * // => false * * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); * // => true * * _.contains('pebbles', 'eb'); * // => true */ function contains(collection, target, fromIndex) { var index = -1, indexOf = getIndexOf(), length = collection ? collection.length : 0, result = false; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; if (isArray(collection)) { result = indexOf(collection, target, fromIndex) > -1; } else if (typeof length == 'number') { result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; } else { forOwn(collection, function(value) { if (++index >= fromIndex) { return !(result = value === target); } }); } return result; } /** * Creates an object composed of keys generated from the results of running * each element of `collection` through the callback. The corresponding value * of each key is the number of times the key was returned by the callback. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, 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 the given callback returns truey value for **all** elements of * a collection. The callback is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias all * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if all elements passed the callback check, * else `false`. * @example * * _.every([true, 1, null, 'yes']); * // => false * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // using "_.pluck" callback shorthand * _.every(characters, 'age'); * // => true * * // using "_.where" callback shorthand * _.every(characters, { 'age': 36 }); * // => false */ function every(collection, callback, thisArg) { var result = true; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { if (!(result = !!callback(collection[index], index, collection))) { break; } } } else { forOwn(collection, function(value, index, collection) { return (result = !!callback(value, index, collection)); }); } return result; } /** * Iterates over elements of a collection, returning an array of all elements * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias select * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that passed the callback check. * @example * * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [2, 4, 6] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.filter(characters, 'blocked'); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] * * // using "_.where" callback shorthand * _.filter(characters, { 'age': 36 }); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] */ function filter(collection, callback, thisArg) { var result = []; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { result.push(value); } } } else { forOwn(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } }); } return result; } /** * Iterates over elements of a collection, returning the first element that * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias detect, findWhere * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the found element, else `undefined`. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true }, * { 'name': 'pebbles', 'age': 1, 'blocked': false } * ]; * * _.find(characters, function(chr) { * return chr.age < 40; * }); * // => { 'name': 'barney', 'age': 36, 'blocked': false } * * // using "_.where" callback shorthand * _.find(characters, { 'age': 1 }); * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } * * // using "_.pluck" callback shorthand * _.find(characters, 'blocked'); * // => { 'name': 'fred', 'age': 40, 'blocked': true } */ function find(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { return value; } } } else { var result; forOwn(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } } /** * This method is like `_.find` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the found element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(num) { * return num % 2 == 1; * }); * // => 3 */ function findLast(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forEachRight(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } /** * Iterates over elements of a collection, executing the callback for each * element. The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). Callbacks 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 Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); * // => logs each number and returns '1,2,3' * * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); * // => logs each number and returns the object (property order is not guaranteed across environments) */ function forEach(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); if (typeof length == 'number') { while (++index < length) { if (callback(collection[index], index, collection) === false) { break; } } } else { forOwn(collection, callback); } return collection; } /** * This method is like `_.forEach` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias eachRight * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); * // => logs each number from right to left and returns '3,2,1' */ function forEachRight(collection, callback, thisArg) { var length = collection ? collection.length : 0; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); if (typeof length == 'number') { while (length--) { if (callback(collection[length], length, collection) === false) { break; } } } else { var props = keys(collection); length = props.length; forOwn(collection, function(value, key, collection) { key = props ? props[--length] : --length; return callback(collection[key], key, collection); }); } return collection; } /** * Creates an object composed of keys generated from the results of running * each element of a collection through the callback. The corresponding value * of each key is an array of the elements responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false` * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using "_.pluck" callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); }); /** * Creates an object composed of keys generated from the results of running * each element of the collection through the given callback. The corresponding * value of each key is the last element responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * var keys = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.indexBy(keys, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.indexBy(characters, function(key) { this.fromCharCode(key.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 the `collection` * returning an array of the results of each invoked method. Additional arguments * will be provided to each invoked method. If `methodName` is a function it * will be invoked for, and `this` bound to, each element in the `collection`. * * @static * @memberOf _ * @category Collections * @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 {...*} [arg] Arguments to invoke the method with. * @returns {Array} Returns a new array of the results of each invoked method. * @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']] */ function invoke(collection, methodName) { var args = slice(arguments, 2), index = -1, isFunc = typeof methodName == 'function', length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); }); return result; } /** * Creates an array of values by running each element in the collection * through the callback. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias collect * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * _.map([1, 2, 3], function(num) { return num * 3; }); * // => [3, 6, 9] * * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); * // => [3, 6, 9] (property order is not guaranteed across environments) * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // using "_.pluck" callback shorthand * _.map(characters, 'name'); * // => ['barney', 'fred'] */ function map(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0; callback = lodash.createCallback(callback, thisArg, 3); if (typeof length == 'number') { var result = Array(length); while (++index < length) { result[index] = callback(collection[index], index, collection); } } else { result = []; forOwn(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } return result; } /** * Retrieves the maximum value of a collection. If the collection is empty or * falsey `-Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.max(characters, function(chr) { return chr.age; }); * // => { 'name': 'fred', 'age': 40 }; * * // using "_.pluck" callback shorthand * _.max(characters, 'age'); * // => { 'name': 'fred', 'age': 40 }; */ function max(collection, callback, thisArg) { var computed = -Infinity, result = computed; // allows working with functions like `_.map` without using // their `index` argument as a callback if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { callback = null; } if (callback == null && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value > result) { result = value; } } } else { callback = (callback == null && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg, 3); forEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current > computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the minimum value of a collection. If the collection is empty or * falsey `Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.min(characters, function(chr) { return chr.age; }); * // => { 'name': 'barney', 'age': 36 }; * * // using "_.pluck" callback shorthand * _.min(characters, 'age'); * // => { 'name': 'barney', 'age': 36 }; */ function min(collection, callback, thisArg) { var computed = Infinity, result = computed; // allows working with functions like `_.map` without using // their `index` argument as a callback if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { callback = null; } if (callback == null && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value < result) { result = value; } } } else { callback = (callback == null && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg, 3); forEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current < computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the value of a specified property from all elements in the collection. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {string} property The name of the property to pluck. * @returns {Array} Returns a new array of property values. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.pluck(characters, 'name'); * // => ['barney', 'fred'] */ var pluck = map; /** * Reduces a collection to a value which is the accumulated result of running * each element in the collection through the callback, where each successive * callback execution consumes the return value of the previous execution. If * `accumulator` is not provided the first element of the collection will be * used as the initial `accumulator` value. The callback is bound to `thisArg` * and invoked with four arguments; (accumulator, value, index|key, collection). * * @static * @memberOf _ * @alias foldl, inject * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var sum = _.reduce([1, 2, 3], function(sum, num) { * return sum + num; * }); * // => 6 * * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function reduce(collection, callback, accumulator, thisArg) { if (!collection) return accumulator; var noaccum = arguments.length < 3; callback = lodash.createCallback(callback, thisArg, 4); var index = -1, length = collection.length; if (typeof length == 'number') { if (noaccum) { accumulator = collection[++index]; } while (++index < length) { accumulator = callback(accumulator, collection[index], index, collection); } } else { forOwn(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection) }); } return accumulator; } /** * This method is like `_.reduce` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var list = [[0, 1], [2, 3], [4, 5]]; * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = lodash.createCallback(callback, thisArg, 4); forEachRight(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection); }); return accumulator; } /** * The opposite of `_.filter` this method returns the elements of a * collection that the callback does **not** return truey for. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that failed the callback check. * @example * * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [1, 3, 5] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.reject(characters, 'blocked'); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] * * // using "_.where" callback shorthand * _.reject(characters, { 'age': 36 }); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] */ function reject(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg, 3); return filter(collection, function(value, index, collection) { return !callback(value, index, collection); }); } /** * Retrieves a random element or `n` random elements from a collection. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to sample. * @param {number} [n] The number of elements to sample. * @param- {Object} [guard] Allows working with functions like `_.map` * without using their `index` arguments as `n`. * @returns {Array} Returns the random sample(s) of `collection`. * @example * * _.sample([1, 2, 3, 4]); * // => 2 * * _.sample([1, 2, 3, 4], 2); * // => [3, 1] */ function sample(collection, n, guard) { if (collection && typeof collection.length != 'number') { collection = values(collection); } if (n == null || guard) { return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; } var result = shuffle(collection); result.length = nativeMin(nativeMax(0, n), result.length); return result; } /** * Creates an array of shuffled values, using a version of the Fisher-Yates * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to shuffle. * @returns {Array} Returns a new shuffled collection. * @example * * _.shuffle([1, 2, 3, 4, 5, 6]); * // => [4, 1, 6, 3, 5, 2] */ function shuffle(collection) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { var rand = baseRandom(0, ++index); result[index] = result[rand]; result[rand] = value; }); return result; } /** * Gets the size of the `collection` by returning `collection.length` for arrays * and array-like objects or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns `collection.length` or number of own enumerable properties. * @example * * _.size([1, 2]); * // => 2 * * _.size({ 'one': 1, 'two': 2, 'three': 3 }); * // => 3 * * _.size('pebbles'); * // => 7 */ function size(collection) { var length = collection ? collection.length : 0; return typeof length == 'number' ? length : keys(collection).length; } /** * Checks if the callback returns a truey value for **any** element of a * collection. The function returns as soon as it finds a passing value and * does not iterate over the entire collection. The callback is bound to * `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias any * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if any element passed the callback check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.some(characters, 'blocked'); * // => true * * // using "_.where" callback shorthand * _.some(characters, { 'age': 1 }); * // => false */ function some(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { if ((result = callback(collection[index], index, collection))) { break; } } } else { forOwn(collection, function(value, index, collection) { return !(result = callback(value, index, collection)); }); } return !!result; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through the callback. This method * performs a stable sort, that is, it will preserve the original sort order * of equal elements. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an array of property names is provided for `callback` the collection * will be sorted by each property value. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of sorted elements. * @example * * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); * // => [3, 1, 2] * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 }, * { 'name': 'barney', 'age': 26 }, * { 'name': 'fred', 'age': 30 } * ]; * * // using "_.pluck" callback shorthand * _.map(_.sortBy(characters, 'age'), _.values); * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] * * // sorting by multiple properties * _.map(_.sortBy(characters, ['name', 'age']), _.values); * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] */ function sortBy(collection, callback, thisArg) { var index = -1, isArr = isArray(callback), length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); if (!isArr) { callback = lodash.createCallback(callback, thisArg, 3); } forEach(collection, function(value, key, collection) { var object = result[++index] = getObject(); if (isArr) { object.criteria = map(callback, function(key) { return value[key]; }); } else { (object.criteria = getArray())[0] = callback(value, key, collection); } object.index = index; object.value = value; }); length = result.length; result.sort(compareAscending); while (length--) { var object = result[length]; result[length] = object.value; if (!isArr) { releaseArray(object.criteria); } releaseObject(object); } return result; } /** * Converts the `collection` to an array. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to convert. * @returns {Array} Returns the new converted array. * @example * * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); * // => [2, 3, 4] */ function toArray(collection) { if (collection && typeof collection.length == 'number') { return slice(collection); } return values(collection); } /** * Performs a deep comparison of each element in a `collection` to the given * `properties` object, returning an array of all elements that have equivalent * property values. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Object} props The object of property values to filter by. * @returns {Array} Returns a new array of elements that have the given properties. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } * ]; * * _.where(characters, { 'age': 36 }); * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] * * _.where(characters, { 'pets': ['dino'] }); * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] */ var where = filter; /*--------------------------------------------------------------------------*/ /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are all falsey. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. * @returns {Array} Returns a 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, result = []; while (++index < length) { var value = array[index]; if (value) { result.push(value); } } return result; } /** * Creates an array excluding all values of the provided arrays using strict * equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @param {...Array} [values] The arrays of values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); * // => [1, 3, 4] */ function difference(array) { return baseDifference(array, baseFlatten(arguments, true, true, 1)); } /** * This method is like `_.find` except that it returns the index of the first * element that passes the callback check, instead of the element itself. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true }, * { 'name': 'pebbles', 'age': 1, 'blocked': false } * ]; * * _.findIndex(characters, function(chr) { * return chr.age < 20; * }); * // => 2 * * // using "_.where" callback shorthand * _.findIndex(characters, { 'age': 36 }); * // => 0 * * // using "_.pluck" callback shorthand * _.findIndex(characters, 'blocked'); * // => 1 */ function findIndex(array, callback, thisArg) { var index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length) { if (callback(array[index], index, array)) { return index; } } return -1; } /** * This method is like `_.findIndex` except that it iterates over elements * of a `collection` from right to left. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': true }, * { 'name': 'fred', 'age': 40, 'blocked': false }, * { 'name': 'pebbles', 'age': 1, 'blocked': true } * ]; * * _.findLastIndex(characters, function(chr) { * return chr.age > 30; * }); * // => 1 * * // using "_.where" callback shorthand * _.findLastIndex(characters, { 'age': 36 }); * // => 0 * * // using "_.pluck" callback shorthand * _.findLastIndex(characters, 'blocked'); * // => 2 */ function findLastIndex(array, callback, thisArg) { var length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (length--) { if (callback(array[length], length, array)) { return length; } } return -1; } /** * Gets the first element or first `n` elements of an array. If a callback * is provided elements at the beginning of the array are returned as long * as the callback returns truey. The callback is bound to `thisArg` and * invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias head, take * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the first element(s) of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([1, 2, 3], 2); * // => [1, 2] * * _.first([1, 2, 3], function(num) { * return num < 3; * }); * // => [1, 2] * * var characters = [ * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.first(characters, 'blocked'); * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] * * // using "_.where" callback shorthand * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); * // => ['barney', 'fred'] */ function first(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = -1; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[0] : undefined; } } return slice(array, 0, nativeMin(nativeMax(0, n), length)); } /** * Flattens a nested array (the nesting can be to any depth). If `isShallow` * is truey, the array will only be flattened a single level. If a callback * is provided each element of the array is passed through the callback before * flattening. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * * _.flatten([1, [2], [3, [[4]]]]); * // => [1, 2, 3, 4]; * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; * * var characters = [ * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } * ]; * * // using "_.pluck" callback shorthand * _.flatten(characters, 'pets'); * // => ['hoppy', 'baby puss', 'dino'] */ function flatten(array, isShallow, callback, thisArg) { // juggle arguments if (typeof isShallow != 'boolean' && isShallow != null) { thisArg = callback; callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; isShallow = false; } if (callback != null) { array = map(array, callback, thisArg); } return baseFlatten(array, isShallow); } /** * Gets the index at which the first occurrence of `value` is found using * strict equality for comparisons, i.e. `===`. If the array is already sorted * providing `true` for `fromIndex` will run a faster binary search. * * @static * @memberOf _ * @category Arrays * @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 or `-1`. * @example * * _.indexOf([1, 2, 3, 1, 2, 3], 2); * // => 1 * * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 4 * * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { if (typeof fromIndex == 'number') { var length = array ? array.length : 0; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); } else if (fromIndex) { var index = sortedIndex(array, value); return array[index] === value ? index : -1; } return baseIndexOf(array, value, fromIndex); } /** * Gets all but the last element or last `n` elements of an array. If a * callback is provided elements at the end of the array are excluded from * the result as long as the callback returns truey. The callback is bound * to `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] * * _.initial([1, 2, 3], 2); * // => [1] * * _.initial([1, 2, 3], function(num) { * return num > 1; * }); * // => [1] * * var characters = [ * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.initial(characters, 'blocked'); * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] * * // using "_.where" callback shorthand * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); * // => ['barney', 'fred'] */ function initial(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : callback || n; } return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); } /** * Creates an array of unique values present in all provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of shared values. * @example * * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); * // => [1, 2] */ function intersection() { var args = [], argsIndex = -1, argsLength = arguments.length, caches = getArray(), indexOf = getIndexOf(), trustIndexOf = indexOf === baseIndexOf, seen = getArray(); while (++argsIndex < argsLength) { var value = arguments[argsIndex]; if (isArray(value) || isArguments(value)) { args.push(value); caches.push(trustIndexOf && value.length >= largeArraySize && createCache(argsIndex ? args[argsIndex] : seen)); } } var array = args[0], index = -1, length = array ? array.length : 0, result = []; outer: while (++index < length) { var cache = caches[0]; value = array[index]; if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { argsIndex = argsLength; (cache || seen).push(value); while (--argsIndex) { cache = caches[argsIndex]; if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { continue outer; } } result.push(value); } } while (argsLength--) { cache = caches[argsLength]; if (cache) { releaseObject(cache); } } releaseArray(caches); releaseArray(seen); return result; } /** * Gets the last element or last `n` elements of an array. If a callback is * provided elements at the end of the array are returned as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the last element(s) of `array`. * @example * * _.last([1, 2, 3]); * // => 3 * * _.last([1, 2, 3], 2); * // => [2, 3] * * _.last([1, 2, 3], function(num) { * return num > 1; * }); * // => [2, 3] * * var characters = [ * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.pluck(_.last(characters, 'blocked'), 'name'); * // => ['fred', 'pebbles'] * * // using "_.where" callback shorthand * _.last(characters, { 'employer': 'na' }); * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] */ function last(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[length - 1] : undefined; } } return slice(array, nativeMax(0, length - n)); } /** * Gets the index at which the last occurrence of `value` is found using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); * // => 4 * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var index = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Removes all provided values from the given array using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to modify. * @param {...*} [value] 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(array) { var args = arguments, argsIndex = 0, argsLength = args.length, length = array ? array.length : 0; while (++argsIndex < argsLength) { var index = -1, value = args[argsIndex]; while (++index < length) { if (array[index] === value) { splice.call(array, index--, 1); length--; } } } return array; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to but not including `end`. If `start` is less than `stop` a * zero-length range is created unless a negative `step` is specified. * * @static * @memberOf _ * @category Arrays * @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 a new range array. * @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) { start = +start || 0; step = typeof step == 'number' ? step : (+step || 1); if (end == null) { end = start; start = 0; } // use `Array(length)` so engines like Chakra and V8 avoid slower modes // http://youtu.be/XAqIpGU8ZZk#t=17m25s var index = -1, length = nativeMax(0, ceil((end - start) / (step || 1))), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * Removes all elements from an array that the callback returns truey for * and returns an array of removed elements. The callback is bound to `thisArg` * and invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to modify. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of removed elements. * @example * * var array = [1, 2, 3, 4, 5, 6]; * var evens = _.remove(array, function(num) { return num % 2 == 0; }); * * console.log(array); * // => [1, 3, 5] * * console.log(evens); * // => [2, 4, 6] */ function remove(array, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length) { var value = array[index]; if (callback(value, index, array)) { result.push(value); splice.call(array, index--, 1); length--; } } return result; } /** * The opposite of `_.initial` this method gets all but the first element or * first `n` elements of an array. If a callback function is provided elements * at the beginning of the array are excluded from the result as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias drop, tail * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] * * _.rest([1, 2, 3], 2); * // => [3] * * _.rest([1, 2, 3], function(num) { * return num < 3; * }); * // => [3] * * var characters = [ * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.pluck(_.rest(characters, 'blocked'), 'name'); * // => ['fred', 'pebbles'] * * // using "_.where" callback shorthand * _.rest(characters, { 'employer': 'slate' }); * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] */ function rest(array, callback, thisArg) { if (typeof callback != 'number' && callback != null) { var n = 0, index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); } return slice(array, n); } /** * Uses a binary search to determine the smallest index at which a value * should be inserted into a given sorted array in order to maintain the sort * order of the array. If a callback is provided it will be executed for * `value` and each element of `array` to compute their sort ranking. The * callback is bound to `thisArg` and invoked with one argument; (value). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([20, 30, 50], 40); * // => 2 * * // using "_.pluck" callback shorthand * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 2 * * var dict = { * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } * }; * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return dict.wordToNumber[word]; * }); * // => 2 * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return this.wordToNumber[word]; * }, dict); * // => 2 */ function sortedIndex(array, value, callback, thisArg) { var low = 0, high = array ? array.length : low; // explicitly reference `identity` for better inlining in Firefox callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; value = callback(value); while (low < high) { var mid = (low + high) >>> 1; (callback(array[mid]) < value) ? low = mid + 1 : high = mid; } return low; } /** * Creates an array of unique values, in order, of the provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of combined values. * @example * * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); * // => [1, 2, 3, 5, 4] */ function union() { return baseUniq(baseFlatten(arguments, true, true)); } /** * Creates a duplicate-value-free version of an array using strict equality * for comparisons, i.e. `===`. If the array is sorted, providing * `true` for `isSorted` will use a faster algorithm. If a callback is provided * each element of `array` is passed through the callback before uniqueness * is computed. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias unique * @category Arrays * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a duplicate-value-free array. * @example * * _.uniq([1, 2, 1, 3, 1]); * // => [1, 2, 3] * * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); * // => ['A', 'b', 'C'] * * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); * // => [1, 2.5, 3] * * // using "_.pluck" callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, callback, thisArg) { // juggle arguments if (typeof isSorted != 'boolean' && isSorted != null) { thisArg = callback; callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; isSorted = false; } if (callback != null) { callback = lodash.createCallback(callback, thisArg, 3); } return baseUniq(array, isSorted, callback); } /** * Creates an array excluding all provided values using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to filter. * @param {...*} [value] The values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); * // => [2, 3, 4] */ function without(array) { return baseDifference(array, slice(arguments, 1)); } /** * Creates an array that is the symmetric difference of the provided arrays. * See http://en.wikipedia.org/wiki/Symmetric_difference. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of values. * @example * * _.xor([1, 2, 3], [5, 2, 1, 4]); * // => [3, 5, 4] * * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); * // => [1, 4, 5] */ function xor() { var index = -1, length = arguments.length; while (++index < length) { var array = arguments[index]; if (isArray(array) || isArguments(array)) { var result = result ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) : array; } } return 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 _ * @alias unzip * @category Arrays * @param {...Array} [array] Arrays to process. * @returns {Array} Returns a new array of grouped elements. * @example * * _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] */ function zip() { var array = arguments.length > 1 ? arguments : arguments[0], index = -1, length = array ? max(pluck(array, 'length')) : 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = pluck(array, index); } return result; } /** * Creates an object composed from arrays of `keys` and `values`. Provide * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` * or two arrays, one of `keys` and one of corresponding `values`. * * @static * @memberOf _ * @alias object * @category Arrays * @param {Array} keys The array of keys. * @param {Array} [values=[]] The array of values. * @returns {Object} Returns an object composed of the given keys and * corresponding values. * @example * * _.zipObject(['fred', 'barney'], [30, 40]); * // => { 'fred': 30, 'barney': 40 } */ function zipObject(keys, values) { var index = -1, length = keys ? keys.length : 0, result = {}; if (!values && length && !isArray(keys[0])) { values = []; } while (++index < length) { var key = keys[index]; if (values) { result[key] = values[index]; } else if (key) { result[key[0]] = key[1]; } } return result; } /*--------------------------------------------------------------------------*/ /** * Creates a function that executes `func`, with the `this` binding and * arguments of the created function, only after being called `n` times. * * @static * @memberOf _ * @category Functions * @param {number} n The number of times the function must be called before * `func` is executed. * @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 all saves have completed */ function after(n, func) { if (!isFunction(func)) { throw new TypeError; } return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that, when called, invokes `func` with the `this` * binding of `thisArg` and prepends any additional `bind` arguments to those * provided to the bound function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var func = function(greeting) { * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'fred' }, 'hi'); * func(); * // => 'hi fred' */ function bind(func, thisArg) { return arguments.length > 2 ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) : createWrapper(func, 1, null, null, thisArg); } /** * 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 the function properties * of `object` will be bound. * * @static * @memberOf _ * @category Functions * @param {Object} object The object to bind and assign the bound methods to. * @param {...string} [methodName] 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 button is clicked */ function bindAll(object) { var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = createWrapper(object[key], 1, null, null, object); } return object; } /** * Creates a function that, when called, 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 will be redefined or don't yet exist. * See http://michaux.ca/articles/lazy-function-definition-pattern. * * @static * @memberOf _ * @category Functions * @param {Object} object The object the method belongs to. * @param {string} key The key of the method. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'name': 'fred', * 'greet': function(greeting) { * return greeting + ' ' + this.name; * } * }; * * var func = _.bindKey(object, 'greet', 'hi'); * func(); * // => 'hi fred' * * object.greet = function(greeting) { * return greeting + 'ya ' + this.name + '!'; * }; * * func(); * // => 'hiya fred!' */ function bindKey(object, key) { return arguments.length > 2 ? createWrapper(key, 19, slice(arguments, 2), null, object) : createWrapper(key, 3, null, null, object); } /** * Creates a function that is the composition of the provided functions, * where each function consumes the return value of the function that follows. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. * Each function is executed with the `this` binding of the composed function. * * @static * @memberOf _ * @category Functions * @param {...Function} [func] Functions to compose. * @returns {Function} Returns the new composed function. * @example * * var realNameMap = { * 'pebbles': 'penelope' * }; * * var format = function(name) { * name = realNameMap[name.toLowerCase()] || name; * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); * }; * * var greet = function(formatted) { * return 'Hiya ' + formatted + '!'; * }; * * var welcome = _.compose(greet, format); * welcome('pebbles'); * // => 'Hiya Penelope!' */ function compose() { var funcs = arguments, length = funcs.length; while (length--) { if (!isFunction(funcs[length])) { throw new TypeError; } } return function() { var args = arguments, length = funcs.length; while (length--) { args = [funcs[length].apply(this, args)]; } return args[0]; }; } /** * Creates a function which accepts one or more arguments of `func` that when * invoked either executes `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` can be specified * if `func.length` is not sufficient. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @returns {Function} Returns the new curried function. * @example * * var curried = _.curry(function(a, b, c) { * console.log(a + b + c); * }); * * curried(1)(2)(3); * // => 6 * * curried(1, 2)(3); * // => 6 * * curried(1, 2, 3); * // => 6 */ function curry(func, arity) { arity = typeof arity == 'number' ? arity : (+arity || func.length); return createWrapper(func, 4, null, null, null, arity); } /** * Creates a function that will delay the execution of `func` until after * `wait` milliseconds have elapsed since the last time it was invoked. * 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 will return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to debounce. * @param {number} wait The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. * @param {boolean} [options.trailing=true] Specify execution 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 * var lazyLayout = _.debounce(calculateLayout, 150); * jQuery(window).on('resize', lazyLayout); * * // execute `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * }); * * // ensure `batchLog` is executed once after 1 second of debounced calls * var source = new EventSource('/stream'); * source.addEventListener('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * }, false); */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (!isFunction(func)) { throw new TypeError; } wait = nativeMax(0, wait) || 0; if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = options.leading; maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); trailing = 'trailing' in options ? options.trailing : trailing; } var delayed = function() { var remaining = wait - (now() - stamp); if (remaining <= 0) { 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); } }; var maxDelayed = function() { 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; } } }; return function() { 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; 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; }; } /** * Defers executing the `func` function until the current call stack has cleared. * Additional arguments will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to defer. * @param {...*} [arg] 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 */ function defer(func) { if (!isFunction(func)) { throw new TypeError; } var args = slice(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); } /** * Executes the `func` function after `wait` milliseconds. Additional arguments * will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay execution. * @param {...*} [arg] 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 */ function delay(func, wait) { if (!isFunction(func)) { throw new TypeError; } var args = slice(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided it will be used to determine 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 used as the cache key. * The `func` is executed with the `this` binding of the memoized function. * The result cache is exposed as the `cache` property on the memoized function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] A function used to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var fibonacci = _.memoize(function(n) { * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); * }); * * fibonacci(9) * // => 34 * * var data = { * 'fred': { 'name': 'fred', 'age': 40 }, * 'pebbles': { 'name': 'pebbles', 'age': 1 } * }; * * // modifying the result cache * var get = _.memoize(function(name) { return data[name]; }, _.identity); * get('pebbles'); * // => { 'name': 'pebbles', 'age': 1 } * * get.cache.pebbles.name = 'penelope'; * get('pebbles'); * // => { 'name': 'penelope', 'age': 1 } */ function memoize(func, resolver) { if (!isFunction(func)) { throw new TypeError; } var memoized = function() { var cache = memoized.cache, key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); } memoized.cache = {}; return memoized; } /** * Creates a function that is restricted to execute `func` once. Repeat calls to * the function will return the value of the first call. The `func` is executed * with the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` executes `createApplication` once */ function once(func) { var ran, result; if (!isFunction(func)) { throw new TypeError; } return function() { if (ran) { return result; } ran = true; result = func.apply(this, arguments); // clear the `func` variable so the function may be garbage collected func = null; return result; }; } /** * Creates a function that, when called, invokes `func` with any additional * `partial` arguments prepended to those provided to the new function. This * method is similar to `_.bind` except it does **not** alter the `this` binding. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { return greeting + ' ' + name; }; * var hi = _.partial(greet, 'hi'); * hi('fred'); * // => 'hi fred' */ function partial(func) { return createWrapper(func, 16, slice(arguments, 1)); } /** * This method is like `_.partial` except that `partial` arguments are * appended to those provided to the new function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var defaultsDeep = _.partialRight(_.merge, _.defaults); * * var options = { * 'variable': 'data', * 'imports': { 'jq': $ } * }; * * defaultsDeep(options, _.templateSettings); * * options.variable * // => 'data' * * options.imports * // => { '_': _, 'jq': $ } */ function partialRight(func) { return createWrapper(func, 32, null, slice(arguments, 1)); } /** * Creates a function that, when executed, will only call the `func` function * at most once per every `wait` milliseconds. 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 will * return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to throttle. * @param {number} wait The number of milliseconds to throttle executions to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * var throttled = _.throttle(updatePosition, 100); * jQuery(window).on('scroll', throttled); * * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (!isFunction(func)) { throw new TypeError; } 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. Additional arguments provided to the function are appended * to those provided to the wrapper function. The wrapper is executed with * the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @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 '

' + func(text) + '

'; * }); * * p('Fred, Wilma, & Pebbles'); * // => '

Fred, Wilma, & Pebbles

' */ function wrap(value, wrapper) { return createWrapper(wrapper, 16, [value]); } /*--------------------------------------------------------------------------*/ /** * Creates a function that returns `value`. * * @static * @memberOf _ * @category Utilities * @param {*} value The value to return from the new function. * @returns {Function} Returns the new function. * @example * * var object = { 'name': 'fred' }; * var getter = _.constant(object); * getter() === object; * // => true */ function constant(value) { return function() { return value; }; } /** * Produces a callback bound to an optional `thisArg`. If `func` is a property * name the created callback will return the property value for a given element. * If `func` is an object the created callback will return `true` for elements * that contain the equivalent object properties, otherwise it will return `false`. * * @static * @memberOf _ * @category Utilities * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // wrap to create custom callback shorthands * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); * return !match ? func(callback, thisArg) : function(object) { * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; * }; * }); * * _.filter(characters, 'age__gt38'); * // => [{ 'name': 'fred', 'age': 40 }] */ function createCallback(func, thisArg, argCount) { var type = typeof func; if (func == null || type == 'function') { return baseCreateCallback(func, thisArg, argCount); } // handle "_.pluck" style callback shorthands if (type != 'object') { return property(func); } var props = keys(func), key = props[0], a = func[key]; // handle "_.where" style callback shorthands if (props.length == 1 && a === a && !isObject(a)) { // fast path the common case of providing an object with a single // property containing a primitive value return function(object) { var b = object[key]; return a === b && (a !== 0 || (1 / a == 1 / b)); }; } return function(object) { var length = props.length, result = false; while (length--) { if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { break; } } return result; }; } /** * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their * corresponding HTML entities. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('Fred, Wilma, & Pebbles'); * // => 'Fred, Wilma, & Pebbles' */ function escape(string) { return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utilities * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'name': 'fred' }; * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Adds function properties of a source object to the destination object. * If `object` is a function methods will be added to its prototype as well. * * @static * @memberOf _ * @category Utilities * @param {Function|Object} [object=lodash] 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. * @example * * function capitalize(string) { * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); * } * * _.mixin({ 'capitalize': capitalize }); * _.capitalize('fred'); * // => 'Fred' * * _('fred').capitalize().value(); * // => 'Fred' * * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); * _('fred').capitalize(); * // => 'Fred' */ function mixin(object, source, options) { var chain = true, methodNames = source && functions(source); if (!source || (!options && !methodNames.length)) { if (options == null) { options = source; } ctor = lodashWrapper; source = object; object = lodash; methodNames = functions(source); } if (options === false) { chain = false; } else if (isObject(options) && 'chain' in options) { chain = options.chain; } var ctor = object, isFunc = isFunction(ctor); forEach(methodNames, function(methodName) { var func = object[methodName] = source[methodName]; if (isFunc) { ctor.prototype[methodName] = function() { var chainAll = this.__chain__, value = this.__wrapped__, args = [value]; push.apply(args, arguments); var result = func.apply(object, args); if (chain || chainAll) { if (value === result && isObject(result)) { return this; } result = new ctor(result); result.__chain__ = chainAll; } return result; }; } }); } /** * Reverts the '_' variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utilities * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { context._ = oldDash; return this; } /** * A no-operation function. * * @static * @memberOf _ * @category Utilities * @example * * var object = { 'name': 'fred' }; * _.noop(object) === undefined; * // => true */ function noop() { // no operation performed } /** * Gets the number of milliseconds that have elapsed since the Unix epoch * (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @category Utilities * @example * * var stamp = _.now(); * _.defer(function() { console.log(_.now() - stamp); }); * // => logs the number of milliseconds it took for the deferred function to be called */ var now = isNative(now = Date.now) && now || function() { return new Date().getTime(); }; /** * Converts the given value into an integer of the specified radix. * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the * `value` is a hexadecimal, in which case a `radix` of `16` is used. * * Note: This method avoids differences in native ES3 and ES5 `parseInt` * implementations. See http://es5.github.io/#E. * * @static * @memberOf _ * @category Utilities * @param {string} value The value to parse. * @param {number} [radix] The radix used to interpret the value to parse. * @returns {number} Returns the new integer value. * @example * * _.parseInt('08'); * // => 8 */ var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt` return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); }; /** * Creates a "_.pluck" style function, which returns the `key` value of a * given object. * * @static * @memberOf _ * @category Utilities * @param {string} key The name of the property to retrieve. * @returns {Function} Returns the new function. * @example * * var characters = [ * { 'name': 'fred', 'age': 40 }, * { 'name': 'barney', 'age': 36 } * ]; * * var getName = _.property('name'); * * _.map(characters, getName); * // => ['barney', 'fred'] * * _.sortBy(characters, getName); * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] */ function property(key) { return function(object) { return object[key]; }; } /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is provided a number between `0` and the given number will be * returned. If `floating` is truey or either `min` or `max` are floats a * floating-point number will be returned instead of an integer. * * @static * @memberOf _ * @category Utilities * @param {number} [min=0] The minimum possible value. * @param {number} [max=1] The maximum possible value. * @param {boolean} [floating=false] Specify returning a floating-point number. * @returns {number} Returns a 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) { var noMin = min == null, noMax = max == null; if (floating == null) { if (typeof min == 'boolean' && noMax) { floating = min; min = 1; } else if (!noMax && typeof max == 'boolean') { floating = max; noMax = true; } } if (noMin && noMax) { max = 1; } 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); } /** * Resolves the value of property `key` on `object`. If `key` is a function * it will be invoked with the `this` binding of `object` and its result returned, * else the property value is returned. If `object` is falsey then `undefined` * is returned. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object to inspect. * @param {string} key The name of the property to resolve. * @returns {*} Returns the resolved value. * @example * * var object = { * 'cheese': 'crumpets', * 'stuff': function() { * return 'nonsense'; * } * }; * * _.result(object, 'cheese'); * // => 'crumpets' * * _.result(object, 'stuff'); * // => 'nonsense' */ function result(object, key) { if (object) { var value = object[key]; return isFunction(value) ? object[key]() : value; } } /** * A micro-templating method that handles arbitrary delimiters, preserves * whitespace, and correctly escapes quotes within interpolated code. * * Note: In the development build, `_.template` utilizes sourceURLs for easier * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl * * For more information on precompiling templates see: * http://lodash.com/custom-builds * * For more information on Chrome extension sandboxes see: * http://developer.chrome.com/stable/extensions/sandboxingEval.html * * @static * @memberOf _ * @category Utilities * @param {string} text The template text. * @param {Object} data The data object used to populate the text. * @param {Object} [options] The options object. * @param {RegExp} [options.escape] The "escape" delimiter. * @param {RegExp} [options.evaluate] The "evaluate" delimiter. * @param {Object} [options.imports] An object to import into the template as local variables. * @param {RegExp} [options.interpolate] The "interpolate" delimiter. * @param {string} [sourceURL] The sourceURL of the template's compiled source. * @param {string} [variable] The data object variable name. * @returns {Function|string} Returns a compiled function when no `data` object * is given, else it returns the interpolated text. * @example * * // using the "interpolate" delimiter to create a compiled template * var compiled = _.template('hello <%= name %>'); * compiled({ 'name': 'fred' }); * // => 'hello fred' * * // using the "escape" delimiter to escape HTML in data property values * _.template('<%- value %>', { 'value': '