code
stringlengths
2
1.05M
// https://github.com/ghiculescu/jekyll-table-of-contents (function($){ $.fn.toc = function(options) { var defaults = { noBackToTopLinks: false, title: '<i>Jump to...</i>', listType: 'ol', // values: [ol|ul] showEffect: 'show', // values: [show|slideDown|fadeIn|none] showSpeed: 'slow' // set to 0 to deactivate effect }, settings = $.extend(defaults, options); var headers = $('h1, h2, h3, h4, h5, h6').filter(function() { // get all headers with an ID if (!this.id) { this.id = $(this).attr( "id", $(this).prev().attr( "name" ).replace(/\./g, "-") ); } return this.id; }), output = $(this); if (!headers.length || headers.length < 3 || !output.length) { return; } if (0 === settings.showSpeed) { settings.showEffect = 'none'; } var render = { show: function() { output.hide().html(html).show(settings.showSpeed); }, slideDown: function() { output.hide().html(html).slideDown(settings.showSpeed); }, fadeIn: function() { output.hide().html(html).fadeIn(settings.showSpeed); }, none: function() { output.html(html); } }; var get_level = function(ele) { return parseInt(ele.nodeName.replace("H", ""), 10); } var highest_level = headers.map(function(_, ele) { return get_level(ele); }).get().sort()[0]; var return_to_top = '<i class="icon-arrow-up back-to-top"> </i>'; var level = get_level(headers[0]), this_level, html = settings.title + " <"+settings.listType+">"; headers.on('click', function() { if (!settings.noBackToTopLinks) { window.location.hash = this.id; } }) .addClass('clickable-header') .each(function(_, header) { this_level = get_level(header); if (!settings.noBackToTopLinks && this_level === highest_level) { $(header).addClass('top-level-header').after(return_to_top); } if (this_level === level) // same level as before; same indenting html += "<li><a href='#" + header.id + "'>" + header.innerHTML + "</a>"; else if (this_level <= level){ // higher level than before; end parent ol for(i = this_level; i < level; i++) { html += "</li></"+settings.listType+">" } html += "<li><a href='#" + header.id + "'>" + header.innerHTML + "</a>"; } else if (this_level > level) { // lower level than before; expand the previous to contain a ol for(i = this_level; i > level; i--) { html += "<"+settings.listType+"><li>" } html += "<a href='#" + header.id + "'>" + header.innerHTML + "</a>"; } level = this_level; // update for the next one }); html += "</"+settings.listType+">"; if (!settings.noBackToTopLinks) { $(document).on('click', '.back-to-top', function() { $(window).scrollTop(0); window.location.hash = ''; }); } render[settings.showEffect](); }; })(jQuery);
var Command = {}; var settings, sessions; Command.dataElements = []; Command.matches = []; Command.lastInputValue = ''; Command.setup = function() { this.bar = document.createElement('div'); this.bar.id = 'cVim-command-bar'; this.bar.cVim = true; this.bar.style[(this.onBottom) ? 'bottom' : 'top'] = '0'; this.input = document.createElement('input'); this.input.type = 'text'; this.input.id = 'cVim-command-bar-input'; this.input.cVim = true; this.statusBar = document.createElement('div'); this.statusBar.id = 'cVim-status-bar'; this.statusBar.style[(this.onBottom) ? 'bottom' : 'top'] = '0'; this.modeIdentifier = document.createElement('span'); this.modeIdentifier.id = 'cVim-command-bar-mode'; this.modeIdentifier.cVim = true; this.bar.appendChild(this.modeIdentifier); this.bar.appendChild(this.input); this.bar.spellcheck = false; try { document.lastChild.appendChild(this.bar); document.lastChild.appendChild(this.statusBar); } catch(e) { document.body.appendChild(this.bar); document.body.appendChild(this.statusBar); } if (!this.data) { this.data = document.createElement('div'); this.data.id = 'cVim-command-bar-search-results'; this.data.cVim = true; try { document.lastChild.appendChild(this.data); } catch(e) { document.body.appendChild(this.data); } this.barHeight = parseInt(getComputedStyle(this.bar).height, 10); if (this.onBottom) { this.barPaddingTop = 0; this.barPaddingBottom = this.barHeight; this.data.style.bottom = this.barHeight + 'px'; } else { this.barPaddingBottom = 0; this.barPaddingTop = this.barHeight; this.data.style.top = this.barHeight + 'px'; } } }; Command.commandBarFocused = function() { return commandMode && this.active && document.activeElement && document.activeElement.id === 'cVim-command-bar-input'; }; Command.history = { index: {}, search: [], url: [], action: [], setInfo: function(type, index) { var fail = false; if (index < 0) { index = 0; fail = true; } if (index >= this[type].length) { index = this[type].length; fail = true; } this.index[type] = index; return !fail; }, cycle: function(type, reverse) { if (this[type].length === 0) { return false; } var len = this[type].length, index = this.index[type]; if (index === void 0) { index = len; } var lastIndex = index; index += reverse ? -1 : 1; if (Command.typed && Command.typed.trim()) { while (this.setInfo(type, index)) { if (this[type][index].substring(0, Command.typed.length) === Command.typed) { break; } index += reverse ? -1 : 1; } } if (reverse && !~index) { this.index[type] = lastIndex; return; } Command.hideData(); this.setInfo(type, index); if (this.index[type] !== this[type].length) { Command.input.value = this[type][this.index[type]]; } else { Command.input.value = Command.typed || ''; } } }; Command.completions = {}; Command.completionStyles = { topsites: [ 'Top Site', 'darkcyan' ], history: [ 'History', 'cyan' ], bookmarks: [ 'Bookmark', '#6d85fd' ] }; Command.completionOrder = { engines: 5, topsites: 4, bookmarks: 2, history: 3, getImportance: function(item) { if (!this.hasOwnProperty(item)) { return -1; } return this[item]; } }; Command.updateCompletions = function(useStyles) { this.completionResults = []; this.dataElements = []; this.data.innerHTML = ''; var key, i; var completionKeys = Object.keys(this.completions).sort(function(a, b) { return this.completionOrder.getImportance(b) - this.completionOrder.getImportance(a); }.bind(this)); for (i = 0; i < completionKeys.length; i++) { key = completionKeys[i]; for (var j = 0; j < this.completions[key].length; ++j) { this.completionResults.push([key].concat(this.completions[key][j])); } } for (i = 0; i < this.completionResults.length; ++i) { if (i > settings.searchlimit) { break; } var item = document.createElement('div'); item.className = 'cVim-completion-item'; var identifier; if (useStyles && this.completionStyles.hasOwnProperty(this.completionResults[i][0])) { var styles = this.completionStyles[this.completionResults[i][0]]; identifier = document.createElement('span'); identifier.style.color = styles[1]; identifier.textContent = styles[0] + ': '; } if (this.completionResults[i].length >= 3) { var left = document.createElement('span'); left.className = 'cVim-left'; left.textContent = decodeHTMLEntities(this.completionResults[i][1]); var right = document.createElement('span'); right.className = 'cVim-right'; right.textContent = decodeHTMLEntities(this.completionResults[i][2]); if (identifier) { left.insertBefore(identifier, left.firstChild); } item.appendChild(left); item.appendChild(right); } else { var full = document.createElement('span'); full.className = 'cVim-full'; full.textContent = decodeHTMLEntities(this.completionResults[i][1]); item.appendChild(full); } this.dataElements.push(item); this.data.appendChild(item); } if (!this.active || !commandMode) { this.hideData(); } else { this.data.style.display = 'block'; } }; Command.hideData = function() { this.completions = {}; Search.lastActive = null; this.dataElements.length = 0; if (this.data) { this.data.innerHTML = ''; Search.index = null; } }; Command.descriptions = [ ['open', 'Open a link in the current tab'], ['tabnew', 'Open a link in a new tab'], ['tabnext', 'Switch to the next open tab'], ['tabprevious', 'Switch to the previous open tab'], ['new', 'Open a link in a new window'], ['buffer', 'Select from a list of current tabs'], ['history', 'Search through your browser history'], ['bookmarks', 'Search through your bookmarks'], ['file', 'Browse local directories'], ['set', 'Configure Settings'], ['tabhistory', 'Open a tab from its history states'], ['execute', 'Execute a sequence of keys'], ['session', 'Open a saved session in a new window'], ['restore', 'Open a recently closed tab'], ['mksession', 'Create a saved session of current tabs'], ['delsession', 'Delete sessions'], ['map', 'Map a command'], ['unmap', 'Unmap a command'], ['tabattach', 'Move current tab to another window'], ['tabdetach', 'Move current tab to a new window'], ['chrome', 'Opens Chrome urls'], ['duplicate', 'Clone the current tab'], ['settings', 'Open the options page for this extension'], ['help', 'Shows the help page'], ['changelog', 'Shows the changelog page'], ['quit', 'Close the current tab'], ['qall', 'Close the current window'], ['stop', 'Stop the current page from loading'], ['stopall', 'Stop all pages in Chrome from loading'], ['undo', 'Reopen the last closed tab'], ['togglepin', 'Toggle the tab\'s pinned state'], ['nohlsearch', 'Clears the search highlight'], ['viewsource', 'View the source for the current document'], ['script', 'Run JavaScript on the current page'] ]; Command.deleteCompletions = function(completions) { completions = completions.split(','); for (var i = 0, l = completions.length; i < l; ++i) { this.completions[completions[i]] = []; } }; Command.expandCompletion = function(value) { var firstWord = value.match(/^[a-z]+(\b|$)/); var exactMatch = this.descriptions.some(function(e) { return e[0] === firstWord; }); if (firstWord && !exactMatch) { firstWord = firstWord[0]; var completedWord = (function() { for (var i = 0; i < this.descriptions.length; i++) if (this.descriptions[i][0].indexOf(firstWord) === 0) return this.descriptions[i][0]; }.bind(this))(); if (completedWord) return value.replace(firstWord, completedWord); } return value; }; Command.callCompletionFunction = (function() { var self = Command; var search; var searchCompletion = function(value) { self.deleteCompletions('engines,bookmarks,complete,chrome,search'); search = search.split(/ +/).compress(); if ((search.length < 2 || !~Complete.engines.indexOf(search[0])) && !Complete.hasAlias(search[0]) || (Complete.hasAlias(search[0]) && value.slice(-1) !== ' ' && search.length < 2)) { if (~Complete.engines.indexOf(search[0])) { self.hideData(); return; } self.completions.engines = []; for (var i = 0; i < Complete.engines.length; i++) { if (!search[0] || !Complete.engines[i].indexOf(search.join(' '))) { self.completions.engines.push([ Complete.engines[i], Complete.requestUrls[Complete.engines[i]] ]); } } self.updateCompletions(true); self.completions.topsites = Search.topSites.filter(function(e) { return ~(e[0] + ' ' + e[1]).toLowerCase() .indexOf(search.slice(0).join(' ').toLowerCase()); }).slice(0, 5).map(function(e) { return [e[0], e[1]]; }); self.updateCompletions(true); if (search.length) { Marks.match(search.join(' '), function(response) { self.completions.bookmarks = response; self.updateCompletions(true); }, 2); } self.historyMode = false; self.searchMode = true; PORT('searchHistory', { search: value.replace(/^\S+\s+/, ''), limit: settings.searchlimit }); return; } if (search[0] = (Complete.getAlias(search[0]) || search[0])) { if (search.length < 2) { self.hideData(); return; } } if (~Complete.engines.indexOf(search[0]) && Complete.hasOwnProperty(search[0])) { Complete[search[0]](search.slice(1).join(' '), function(response) { self.completions = { search: response }; self.updateCompletions(); }); } }; var tabHistoryCompletion = function(value) { RUNTIME('getHistoryStates', null, function(response) { self.completions = { tabhistory: searchArray(response.links, value.replace(/\S+\s+/, ''), settings.searchlimit, true) }; self.updateCompletions(); }); }; var restoreTabCompletion = function(value) { RUNTIME('getChromeSessions', null, function(sessions) { self.completions = { chromesessions: Object.keys(sessions).map(function(e) { return [sessions[e].id + ': ' + sessions[e].title, sessions[e].url, sessions[e].id]; }).filter(function(e) { return ~e.join('').toLowerCase() .indexOf(value.replace(/^\S+\s+/, '').toLowerCase()); }) }; self.updateCompletions(); }); }; var deleteSessionCompletion = function() { self.completions = { sessions: sessions.filter(function(e) { var regexp; var isValidRegex = true; try { regexp = new RegExp(search, 'i'); } catch (ex) { isValidRegex = false; } if (isValidRegex) { return regexp.test(e[0]); } return e[0].substring(0, search.length) === search; }) }; self.updateCompletions(); }; return function(value) { search = value.replace(/^(chrome:\/\/|\S+ +)/, ''); var baseCommand = (value.match(/^\S+/) || [null])[0]; switch (baseCommand) { case 'tabnew': case 'tabedit': case 'tabopen': case 'open': case 'new': searchCompletion(value); return true; case 'chrome': Search.chromeMatch(search, function(matches) { self.completions = { chrome: matches }; self.updateCompletions(); }); return true; case 'tabhistory': tabHistoryCompletion(value); return true; case 'tabattach': RUNTIME('getWindows'); self.completions = {}; return true; case 'buffer': PORT('getBuffers'); return true; case 'restore': restoreTabCompletion(value); return true; case 'delsession': deleteSessionCompletion(value); return true; case 'set': Search.settingsMatch(search, function(matches) { self.completions = {settings: matches}; self.updateCompletions(); }); return true; case 'history': if (search.trim() === '') { self.hideData(); return; } self.historyMode = true; PORT('searchHistory', {search: search, limit: settings.searchlimit}); return true; case 'file': Marks.parseFileCommand(search); return true; case 'bookmarks': self.completions = {}; if (search[0] === '/') { return Marks.matchPath(search); } Marks.match(search, function(response) { self.completions.bookmarks = response; self.updateCompletions(); }); return true; } return false; }; })(); Command.complete = function(value) { Search.index = null; this.typed = this.input.value; var originalValue = value; // prevent expandCompletion from // limiting command completions value = this.expandCompletion(value).replace(/(^[^\s&!*?=]+)[&!*?=]*/, '$1'); if (~value.indexOf(' ') && this.callCompletionFunction(value) === true) { return; } // Default completion for commands this.completions = { complete: this.descriptions.filter(function(element) { return originalValue === element[0].slice(0, originalValue.length); }) }; this.updateCompletions(); }; Command.execute = function(value, repeats) { value = this.expandCompletion(value); value = value.replace(/@@[a-zA-Z_$][a-zA-Z0-9_$]*/g, function(e) { return settings.hasOwnProperty(e) ? settings[e] : e; }); // Match commands like ':tabnew*&! search' before // commands like ':tabnew search&*!' // e.g. :tabnew& google asdf* => opens a new pinned tab // ! == whether to open in a new tab or not // & == whether the tab will be active // * == whether the tab will be pinned // = == force cVim to treat text as a URL // ? == force cVim to tread text as a search var tab = { active: true, isURL: false, isLink: false, pinned: false, tabbed: false }; (value.match(/^[^\s&!*=?]*([&!*=?]+)/) || []) .concat(value.match(/[&!*=?]*$/) || []) .join('').split('') .forEach(function(e) { switch (e) { case '&': tab.active = false; break; case '!': tab.tabbed = true; break; case '*': tab.pinned = true; break; case '?': tab.isLink = true; tab.isURL = false; break; case '=': tab.isLink = false; tab.isURL = true; break; } }); value = value.replace(/^([^\s&*!=?]*)[&*!=?]*\s/, '$1 '); value = value.replace(/[&*!=?]+$/, function(e) { return e.replace(/[^=?]/g, ''); }); if ( !~Complete.engines.indexOf(value.split(/\s+/g).compress()[1]) ) value = value.replace(/[=?]+$/, ''); this.history.index = {}; switch (value) { case 'nohlsearch': Find.clear(); HUD.hide(); return; case 'duplicate': RUNTIME('duplicateTab', {repeats: repeats}); return; case 'settings': tab.tabbed = true; RUNTIME('openLink', { tab: tab, url: chrome.extension.getURL('/pages/options.html'), repeats: repeats }); return; case 'changelog': tab.tabbed = true; RUNTIME('openLink', { tab: tab, url: chrome.extension.getURL('/pages/changelog.html'), repeats: repeats }); return; case 'help': tab.tabbed = true; RUNTIME('openLink', { tab: tab, url: chrome.extension.getURL('/pages/mappings.html') }); return; case 'stop': window.stop(); return; case 'stopall': RUNTIME('cancelAllWebRequests'); return; case 'viewsource': RUNTIME('openLink', { tab: tab, url: 'view-source:' + document.URL, noconvert: true }); return; case 'pintab': RUNTIME('pinTab', {pinned: true}); break; case 'unpintab': RUNTIME('pinTab', {pinned: false}); break; case 'togglepin': RUNTIME('pinTab'); return; case 'undo': RUNTIME('openLast'); return; case 'tabnext': case 'tabn': RUNTIME('nextTab'); return; case 'tabprevious': case 'tabp': case 'tabN': RUNTIME('previousTab'); return; case 'tabprevious': return; case 'q': case 'quit': case 'exit': RUNTIME('closeTab', {repeats: repeats}); return; case 'qa': case 'qall': RUNTIME('closeWindow'); return; } if (/^chrome +/.test(value)) { RUNTIME('openLink', { tab: tab, url: value.replace(' ', '://'), noconvert: true }); return; } if (/^bookmarks +/.test(value) && !/^\S+\s*$/.test(value)) { if (/^\S+\s+\//.test(value)) { RUNTIME('openBookmarkFolder', { path: value.replace(/\S+\s+/, ''), noconvert: true }); return; } if (this.completionResults.length && !this.completionResults.some(function(e) { return e[2] === value.replace(/^\S+\s*/, ''); })) { RUNTIME('openLink', { tab: tab, url: this.completionResults[0][2], noconvert: true }); return; } RUNTIME('openLink', { tab: tab, url: value.replace(/^\S+\s+/, ''), noconvert: true }); return; } if (/^history +/.test(value) && !/^\S+\s*$/.test(value)) { RUNTIME('openLink', { tab: tab, url: Complete.convertToLink(value), noconvert: true }); return; } if (/^taba(ttach)? +/.test(value) && !/^\S+\s*$/.test(value)) { var windowId; if (windowId = this.completionResults[parseInt( value.replace(/^\S+ */, ''), 10)]) { RUNTIME('moveTab', { windowId: windowId[3] }); return; } } if (/^tabd(etach)?/.test(value)) { RUNTIME('moveTab'); return; } if (/^file +/.test(value)) { RUNTIME('openLink', { tab: tab, url: 'file://' + value.replace(/\S+ +/, '') .replace(/^~/, settings.homedirectory), noconvert: true }); return; } if (/^(new|winopen|wo)$/.test(value.replace(/ .*/, '')) && !/^\S+\s*$/.test(value)) { RUNTIME('openLinkWindow', { tab: tab, url: Complete.convertToLink(value, tab.isURL, tab.isLink), repeats: repeats, noconvert: true }); return; } if (/^restore\s+/.test(value)) { RUNTIME('restoreChromeSession', { sessionId: value.replace(/\S+\s+/, '').trimAround() }); } if (/^(tabnew|tabedit|tabe|to|tabopen|tabhistory)$/ .test(value.replace(/ .*/, ''))) { tab.tabbed = true; RUNTIME('openLink', { tab: tab, url: Complete.convertToLink(value, tab.isURL, tab.isLink), repeats: repeats, noconvert: true }); return; } if (/^(o|open)$/.test(value.replace(/ .*/, '')) && !/^\S+\s*$/.test(value)) { RUNTIME('openLink', { tab: tab, url: Complete.convertToLink(value, tab.isURL, tab.isLink), noconvert: true }); return; } if (/^buffer +/.test(value)) { var index = +value.replace(/^\S+\s+/, '') - 1, selectedBuffer; if (Number.isNaN(index)) { selectedBuffer = Command.completionResults[0]; if (selectedBuffer === void 0) return; } else { selectedBuffer = Command.completionResults.filter(function(e) { return e[1].indexOf((index + 1).toString()) === 0; })[0]; } if (selectedBuffer !== void 0) RUNTIME('goToTab', {id: selectedBuffer[3]}); return; } if (/^execute +/.test(value)) { var command = value.replace(/^\S+/, '').trim(); realKeys = ''; repeats = ''; Command.hide(); Mappings.executeSequence(command); return; } if (/^delsession/.test(value)) { value = value.replace(/^\S+(\s+)?/, '').trimAround(); if (value === '') { Status.setMessage('argument required', 1, 'error'); return; } if (~sessions.indexOf(value)) { sessions.splice(sessions.indexOf(value), 1); } value.split(' ').forEach(function(v) { RUNTIME('deleteSession', {name: v}); }); PORT('getSessionNames'); return; } if (/^mksession/.test(value)) { value = value.replace(/^\S+(\s+)?/, '').trimAround(); if (value === '') { Status.setMessage('session name required', 1, 'error'); return; } if (/[^a-zA-Z0-9_-]/.test(value)) { Status.setMessage('only alphanumeric characters, dashes, ' + 'and underscores are allowed', 1, 'error'); return; } if (!~sessions.indexOf(value)) { sessions.push(value); } RUNTIME('createSession', {name: value}); return; } if (/^session/.test(value)) { value = value.replace(/^\S+(\s+)?/, '').trimAround(); if (value === '') { Status.setMessage('session name required', 1, 'error'); return; } RUNTIME('openSession', {name: value, sameWindow: !tab.active}, function() { Status.setMessage('session does not exist', 1, 'error'); }); return; } if (/^((i?(re)?map)|i?unmap(All)?)+/.test(value)) { Mappings.parseLine(value); return; } if (/^set +/.test(value) && value !== 'set') { value = value.replace(/^set +/, '').split(/[ =]+/); var isSet, swapVal, isQuery = /\?$/.test(value[0]); value[0] = value[0].replace(/\?$/, ''); if (!settings.hasOwnProperty(value[0].replace(/^no|!$/g, ''))) { Status.setMessage('unknown option: ' + value[0], 1, 'error'); return; } if (isQuery) { Status.setMessage(value + ': ' + settings[value[0]], 1); return; } isSet = !/^no/.test(value[0]); swapVal = tab.tabbed; value[0] = value[0].replace(/^no|\?$/g, ''); if (value.length === 1 && Boolean(settings[value]) === settings[value]) { if (value[0] === 'hud' && !isSet) { HUD.hide(true); } if (swapVal) { settings[value[0]] = !settings[value[0]]; } else { settings[value[0]] = isSet; } RUNTIME('syncSettings', {settings: settings}); } return; } if (/^script +/.test(value)) { RUNTIME('runScript', {code: value.slice(7)}); } }; Command.show = function(search, value) { if (!this.domElementsLoaded) { return; } this.type = ''; this.active = true; if (document.activeElement) { document.activeElement.blur(); } if (search) { this.type = 'search'; this.modeIdentifier.innerHTML = search; } else { this.type = 'action'; this.modeIdentifier.innerHTML = ':'; } if (value) { this.input.value = value; this.typed = value; } if (Status.active) { Status.hide(); } this.bar.style.display = 'inline-block'; setTimeout(function() { this.input.focus(); // Temp fix for Chromium issue in #97 if (this.commandBarFocused()) { document.activeElement.select(); document.getSelection().collapseToEnd(); } // End temp fix }.bind(this), 0); }; Command.hide = function(callback) { if (document.activeElement) { document.activeElement.blur(); } this.hideData(); if (this.bar) { this.bar.style.display = 'none'; } if (this.input) { this.input.value = ''; } if (this.data) { this.data.style.display = 'none'; } this.historyMode = false; this.active = false; commandMode = false; Search.index = null; this.history.index = {}; this.typed = ''; this.dataElements = []; if (callback) { callback(); } }; Command.insertCSS = function() { var css = settings.COMMANDBARCSS; if (!css) { return; } if (settings.linkanimations) { css += '.cVim-link-hint { transition: opacity 0.2s ease-out, ' + 'background 0.2s ease-out; }'; } RUNTIME('injectCSS', {css: css, runAt: 'document_start'}); var head = document.getElementsByTagName('head'); if (head.length) { this.css = document.createElement('style'); this.css.textContent = css; head[0].appendChild(this.css); } }; Command.onDOMLoad = function() { this.insertCSS(); this.onBottom = settings.barposition === 'bottom'; if (this.data !== void 0) { this.data.style[(!this.onBottom) ? 'bottom' : 'top'] = ''; this.data.style[(this.onBottom) ? 'bottom' : 'top'] = '20px'; } if (!settings.autofocus) { var manualFocus = false; var initialFocus = window.setInterval(function() { if (document.activeElement) { if (/input|textarea/i.test(document.activeElement.localName) && !manualFocus && !Command.commandBarFocused()) { document.activeElement.blur(); } } if (manualFocus || KeyHandler.hasPressedKey) { window.clearInterval(initialFocus); } }, 5); var initialMouseDown = window.addEventListener('mousedown', function() { manualFocus = true; window.removeEventListener('mousedown', initialMouseDown, true); }, true); } this.setup(); this.domElementsLoaded = true; }; Command.updateSettings = function(config) { var key; config.nextmatchpattern = new RegExp('^' + config.nextmatchpattern + '$', 'i'); config.previousmatchpattern = new RegExp('^' + config.previousmatchpattern + '$', 'i'); if (Array.isArray(config.completionengines) && config.completionengines.length) { Complete.engines = Complete.engines.filter(function(e) { return ~config.completionengines.indexOf(e); }); } if (config.searchengines && config.searchengines.constructor === Object) { for (key in config.searchengines) { if (!~Complete.engines.indexOf(key) && typeof config.searchengines[key] === 'string') { Complete.engines.push(key); Complete.requestUrls[key] = config.searchengines[key]; } } } if (config.searchaliases && config.searchaliases.constructor === Object) { for (key in config.searchaliases) { if (Complete.engines.indexOf(key)) { Complete.aliases[key] = config.searchaliases[key]; } } } if (config.locale) { Complete.setLocale(config.locale); } if (config.hintcharacters && config.hintcharacters.split('').unique().length > 1) { settings.hintcharacters = config.hintcharacters .split('').unique().join(''); } if (config !== settings) { for (key in config) { if (key.toUpperCase() !== key && settings.hasOwnProperty(key)) { settings[key] = config[key]; } } } }; Command.addSettingBlock = function(config) { for (var key in config) { if (key === 'MAPPINGS') { settings.MAPPINGS += '\n' + config[key]; Mappings.parseCustom(settings.MAPPINGS); } else if (config[key].constructor === Object) { settings[key] = Object.extend(settings[key], config[key]); } else { settings[key] = config[key]; } } }; Command.init = function(enabled) { var key; Mappings.defaults = Object.clone(Mappings.defaultsClone); Mappings.parseCustom(settings.MAPPINGS); if (enabled) { this.loaded = true; this.updateSettings(settings); for (key in settings.sites) { if (matchLocation(document.URL, key)) { Command.addSettingBlock(settings.sites[key]); } } waitForLoad(this.onDOMLoad, this); if (settings.autohidecursor) { waitForLoad(Cursor.init, Cursor); } } else { this.loaded = false; if (this.css && this.css.parentNode) { this.css.parentNode.removeChild(this.css); } var links = document.getElementById('cVim-link-container'); if (Cursor.overlay && Cursor.overlay.parentNode) { Cursor.overlay.parentNode.removeChild(Cursor.overlay); } if (this.bar && this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } if (links) { links.parentNode.removeChild(links); } removeListeners(); } }; Command.configureSettings = function(_settings) { settings = _settings; this.initialLoadStarted = true; var checkBlacklist = function() { var blacklists = settings.blacklists, blacklist; Command.blacklisted = false; for (var i = 0, l = blacklists.length; i < l; i++) { blacklist = blacklists[i].trimAround().split(/\s+/g); if (!blacklist.length) { continue; } if (matchLocation(document.URL, blacklist[0])) { return true; } } }; var loadMain = function() { Command.loaded = true; PORT('setIconEnabled'); Command.init(true); }; Search.settings = Object.keys(settings).filter(function(e) { return typeof settings[e] === 'boolean'; }); removeListeners(); settings.searchlimit = +settings.searchlimit; if (!checkBlacklist()) { RUNTIME('getActiveState', null, function(response) { if (response) { addListeners(); loadMain(); } else { Command.init(false); } }); } else { this.init(false); } };
/*global define*/ define([ 'jquery', 'underscore', 'postal', 'out', //no args 'postaldom' ], function ($, _, postal, out) { 'use strict'; var log = out('#output'); postal.subscribe({ channel: 'postal-dom-demo', topic: 'button.clicked', callback: function (data) { log.writeln(JSON.stringify(data)); } }); postal.dom.on('#demo-button', 'click', { channel: 'postal-dom-demo', topic: 'button.clicked' }); });
import { drawChessman as drawChessmanCanvas } from './canvas.js' function drawChessman(type, value) { if (type === 'canvas') { return drawChessmanCanvas(value) } else { return drawChessmanCanvas(value) } } export { drawChessman }
var request = require('xhr') var parseCSV = require('./parse-csv') var parseJSON = require('./parse-json') module.exports = function orgs (options, callback) { console.log(options) var requestOptions = { url: 'https://api.github.com/repos/' + options.owner + '/' + options.repo + '/contents/' + options.path, headers: { authorization: 'token ' + options.token }, json: true } var type = require('./accept-file')(options.path) if (typeof type === 'error') return callback(type) request(requestOptions, function (err, res, body) { if (err) return callback(err) if (body.message === 'Not Found') return callback(new Error(body.message)) var content = window.atob(body.content) if (type === 'csv') { parseCSV(content, end) } else if (type === 'json') { parseJSON(content, end) } function end (err, data, properties) { var save = { type: type, branch: options.branch, owner: options.owner, repo: options.repo, location: body, source: 'github' } callback(err, data, properties, save) } }) }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M11 12V6c0-1.66-1.34-3-3-3S5 4.34 5 6v6c-1.21.91-2 2.37-2 4 0 1.12.38 2.14 1 2.97V19h.02c.91 1.21 2.35 2 3.98 2s3.06-.79 3.98-2H12v-.03c.62-.83 1-1.85 1-2.97 0-1.63-.79-3.09-2-4zm-6 4c0-.94.45-1.84 1.2-2.4L7 13V6c0-.55.45-1 1-1s1 .45 1 1v7l.8.6c.75.57 1.2 1.46 1.2 2.4H5zM17.81 4c-.48 0-.92.3-1.09.75L14 12.02c-.18.47.17.98.67.98.31 0 .58-.19.68-.48L16 10.7h3.63l.64 1.82c.1.29.38.48.68.48.51 0 .86-.51.68-.98L18.9 4.75c-.17-.45-.6-.75-1.09-.75zm-1.34 5.39 1.31-3.72h.08l1.31 3.72h-2.7z" }), 'ThermostatAutoRounded');
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var abstract_1 = require("./abstract"); var StringLiteralType = (function (_super) { __extends(StringLiteralType, _super); function StringLiteralType(value) { _super.call(this); this.value = value; } StringLiteralType.prototype.clone = function () { var clone = new StringLiteralType(this.value); clone.isArray = this.isArray; return clone; }; StringLiteralType.prototype.equals = function (type) { return type instanceof StringLiteralType && type.isArray == this.isArray && type.value == this.value; }; StringLiteralType.prototype.toObject = function () { var result = _super.prototype.toObject.call(this); result.type = 'stringLiteral'; result.value = this.value; return result; }; StringLiteralType.prototype.toString = function () { return '"' + this.value + '"'; }; return StringLiteralType; }(abstract_1.Type)); exports.StringLiteralType = StringLiteralType;
var $getChatsMoreBtn = $('#chat-content-chats-more'); // 只在父框架中才能显示 if (!$(window.parent.document).find('#chat-wrapper').length) { window.location.href = 'http://closer-chat.coding.io/'; } var $editBoxEdit = $('#chat-content-editbox-edit'); var $editBoxSend = $('#chat-content-send').find('button'); var $editBoxMenuCover = $('#editBox-menu-cover'); var cId = Util.getArgValue('id'); if (cId === null) { window.location.href = 'http://closer-chat.coding.io/'; } // 用户进入房间到时候默认加载历史消息 从后往前 $getChatsMoreBtn.click(function() { getChats('chat', cId, parseInt($(this).attr('data-pn'), 10)); }); $getChatsMoreBtn.click(); // 编辑框初始化 editBoxPreHandle(); $editBoxSend.removeClass('disabled'); $editBoxEdit.text('').attr('contentEditable', 'true'); $editBoxMenuCover.hide();
'use strict'; //Tracks service used to communicate Tracks REST endpoints angular.module('tracks').factory('Tracks', ['$resource', function($resource) { return $resource('tracks/:trackId', { trackId: '@_id' }, { update: { method: 'PUT' } }); } ]);
$(document).ready(function(){ $('#btn_ok').click(function(){ window.location.href='oa-personal-proc-approval.html'; }); $('#btn_no').click(function(){ window.location.href='oa-personal-proc-approval.html'; }); });
'use strict'; /** * Module dependencies. */ var _ = require('underscore'), mongoose = require('mongoose'), User = mongoose.model('User'), Room = mongoose.model('Room'), School = mongoose.model('School'); var async = require('async'); /** * Create user for sign up */ exports.create = function(req, res, next) { var user = new User(req.body); var message = null; user.save(function(err) { if (err) { switch (err.code) { case 11000: case 11001: message = '用户名已存在'; break; default: message = 'Please fill all the required fields'; } return res.send(400, { message: message }); } else if ((req.user) && (req.user.roles.indexOf('root') >= 0)) { res.json(200, user); } else { //{username: xxx, hashed_password:xxx, have_profile} var response = { _id:user._id, username: user.username }; //TODO: modify the usernmae mechanism if (user.email) { response.email = user.email; } else if (user.phone) { response.phone = user.phone; } if (req.query && req.query.isTemp) { req.logout(); req.login(user, function(err) { if (err) return res.send(500, "temp user login new create user err"); return res.json(200, req.user); }) } else { res.json(200, response); } } }); }; exports.createStudentBatch = function(req, res) { var studentsList = req.body.studentsList; console.log(studentsList); var successList = []; async.reject(studentsList, function(student, callback) { var newStudent = new User(student); newStudent.created_at = Date.now(); newStudent.save(function(err) { if(err) { callback(false); }else { newStudent.salt = null; newStudent.password = null; successList.push(newStudent); callback(true); } }) }, function(failedStudents) { if(failedStudents.length) { res.status(406).send(failedStudents); }else { res.status(200).send(successList); } }); }; exports.autoCreateAddStudents = function(req, res) { var names = req.body.names; var schoolId = req.body.schoolId; var roomId = req.body.roomId; console.log(names) School.findById(schoolId, function(err, school) { if(err) { res.status(500).send({message: '服务器错误,未找到学校'}); } if(school) { Room.findById(roomId, function(err, room) { if(err) { res.status(500).send({message: '服务器错误,未找到该班级'}); } if(room) { var index = room.studentIndex || 0; var successList = []; async.rejectSeries(names, function(name, callback) { index = index + 1; var student = new User(); var studentNo = (index > 9) ? ''+index : '0' + index; student.name = name; student.username = school.code + room.code + studentNo; student.roles = ['student']; student.school = school._id; student.created_at = Date.now(); student.save(function(err) { if(err){ console.error(err); callback(false); }else { successList.push(student); callback(true); } }) }, function(failList) { if(failList.length) { console.log(failList); res.status(406).send(failList); }else { room.students = room.students.concat(successList); room.studentIndex = index; room.save(function(err) { if(err) { res.status(500).send({message: '学生添加到班级失败'}) }else { res.status(200).send(successList); } }); } }) }else { res.status(404).send({message: '不存在此班级'}); } }); }else { res.status(404).send({message: '不存在此学校'}); } }) }; exports.manualCreateAddStudents = function(req, res) { var students = req.body.students; var schoolId = req.body.schoolId; var roomId = req.body.roomId; var successList = []; async.reject(students, function(student, callback) { var user = new User(); user.name = student.name; user.username = student.username; user.school = schoolId; user.roles = ['student']; user.created_at = Date.now(); user.save(function(err) { if(err) { console.log(err); callback(false); }else { successList.push(user); callback(true); } }) }, function(failList) { if(failList.length) { res.status(406).send(failList); }else { Room.findById(roomId, function(err, room) { if(err) { res.status(500).send('服务器错误'); } if(room) { room.students = room.students.concat(successList); room.save(function(err) { if(err) { res.status(500).send({message: '学生添加到班级失败'}) }else { res.status(200).send(successList); } }); }else { res.status(404).send({message: '不存在此班级'}); } }) } }) };
"use strict"; var Client = require("./client"); var MESSAGE_PATH = "messages"; function Message() { //compabtibility fix if (arguments.length > 0) { this.from = arguments[0]; this.to = arguments[1]; this.text = arguments[2]; } } /** * Get information about a message that was sent or received * @param client Client instance * @param id id of Message * @param callback callback * @example * bandwidth.Message.get(client, "id", function(err, message){}); */ Message.get = function (client, id, callback) { if (arguments.length === 2) { callback = id; id = client; client = new Client(); } client.makeRequest("get", client.concatUserPath(MESSAGE_PATH) + "/" + id, function (err, item) { if (err) { return callback(err); } item.client = client; item.__proto__ = Message.prototype; callback(null, item); }); }; /** * Get a list of previous messages that were sent or received * @param client Client instance * @param query query parameters * @param callback callback function * @example * bandwidth.Message.list(client, function(err, list){}); */ Message.list = function (client, query, callback) { if (arguments.length === 2) { callback = query; if (client instanceof Client) { query = {}; } else { query = client; client = new Client(); } } else if (arguments.length === 1) { callback = client; client = new Client(); } client.makeRequest("get", client.concatUserPath(MESSAGE_PATH), query, function (err, items) { if (err) { return callback(err); } var itemsIsEmpty = items instanceof Object && Object.getOwnPropertyNames(items).length === 0; var result = itemsIsEmpty ? [] : items.map(function (item) { item.client = client; item.__proto__ = Message.prototype; return item; }); callback(null, result); }); }; /** * Send text messages * @param client Client instance * @param item message (or list of messages) to send * @param callback callback function * @example * bandwidth.Message.create(client, {from: "", to: "", text: ""}, function(err, message){}); * bandwidth.Message.create(client, [{from: "", to: "", text: ""}], function(err, statuses){}); */ Message.create = function (client, item, callback) { if (arguments.length === 2) { callback = item; item = client; client = new Client(); } var isList = Array.isArray(item); var request = client.createRequest("post", client.concatUserPath(MESSAGE_PATH)); request.type("json").send(item).end(function (res) { if (res.ok) { if (isList) { var statuses = ((Object.keys(res.body).length === 0 ? null : res.body) || []).map(function (i) { if (i.result === "error") { return { error : new Error(i.error.message) }; } var index = (i.location || "").lastIndexOf("/"); if (index < 0) { return { error : new Error("Missing id in response") }; } return { id : i.location.substr(index + 1) }; }); callback(null, statuses); } else { Client.getIdFromLocationHeader(res.headers.location || "", function (err, id) { if (err) { return callback(err); } Message.get(client, id, callback); }); } } else { client.checkResponse(res, callback); } }); }; module.exports = Message;
// Copyright (c) 2015 Uber Technologies, Inc. // // 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. 'use strict'; var tape = require('tape'); var path = require('path'); var fs = require('graceful-fs'); var series = require('run-series'); var parallel = require('run-parallel'); var exec = require('child_process').exec; var createFixtures = require('fixtures-fs/create-fixtures'); var rimraf = require('rimraf'); var mkdirp = require('mkdirp'); var wrapCluster = require('tape-cluster'); var extend = require('xtend'); var DebugLogtron = require('debug-logtron'); var TimeMock = require('time-mock'); var readDirFiles = require('read-dir-files').read; var IDLDaemon = require('../../bin/idl-daemon.js'); var IDL = require('../../bin/idl.js'); var defineFixture = require('./define-fixture'); var defaultRepos = ['A', 'B', 'C', 'D'].reduce(makeFixture, {}); function makeFixture(memo, letter) { memo[letter] = defineFixture({ name: letter }); return memo; } TestCluster.test = wrapCluster(tape, TestCluster); module.exports = TestCluster; function TestCluster(opts) { if (!(this instanceof TestCluster)) { return new TestCluster(opts); } opts = opts || {}; var self = this; self.remoteRepos = extend(defaultRepos, opts.remoteRepos || {}); self.repoFixtures = Object.keys(self.remoteRepos) .reduce(function getFiles(acc, name) { acc[name] = self.remoteRepos[name].files; return acc; }, {}); self.prepareOnly = opts.prepareOnly || false; self.fetchRemotes = opts.fetchRemotes === false ? false : true; self.fixturesDir = path.join(__dirname, '..', 'fixtures'); self.remotesDir = path.join(self.fixturesDir, 'remotes'); self.upstreamDir = path.join(self.fixturesDir, 'upstream'); self.repositoryDir = path.join(self.fixturesDir, 'repository'); self.configFile = path.join(self.fixturesDir, 'config.json'); self.cacheDir = path.join(self.fixturesDir, 'remote-cache'); self.getCacheDir = path.join(self.fixturesDir, 'upstream-cache'); self.localApp = path.join(self.fixturesDir, 'local-app'); self.config = extend({ upstream: 'file://' + self.upstreamDir, repositoryDirectory: self.repositoryDir, fileNameStrategy: 'lastSegment', cacheLocation: self.cacheDir, fetchInterval: opts.fetchInterval || 30 * 1000, remotes: Object.keys(self.remoteRepos) .map(function buildRepoObj(remoteName) { var repoInfo = self.remoteRepos[remoteName]; return { repository: 'file://' + path.join( self.remotesDir, remoteName ), branch: repoInfo.branch || 'master', localFileName: repoInfo.localFileName }; }) }, opts.config || {}); self.logger = DebugLogtron('idl'); self.timers = TimeMock(0); self.idlDaemon = null; } TestCluster.prototype.bootstrap = function bootstrap(cb) { var self = this; series([ rimraf.bind(null, self.fixturesDir), mkdirp.bind(null, self.remotesDir), createFixtures.bind(null, self.remotesDir, self.repoFixtures), createFixtures.bind(null, self.localApp, {}), self.gitifyRemotes.bind(self), self.setupUpstream.bind(self), self.writeConfigFile.bind(self), self.prepareOnly ? null : self.setupIDLDaemon.bind(self) ].filter(Boolean), cb); }; // git init // git a . // git commit -m 'initial' TestCluster.prototype.gitifyRemotes = function gitifyRemotes(cb) { var self = this; var keys = Object.keys(self.remoteRepos); var tasks = keys.map(function buildThunk(remoteKey) { var repoInfo = self.remoteRepos[remoteKey]; var cwd = path.join(self.remotesDir, remoteKey); return makeGitifyThunk(cwd, repoInfo); }); return parallel(tasks, cb); }; function makeGitifyThunk(cwd, repoInfo) { return function gitifyThunk(callback) { var gitOpts = { cwd: cwd }; series([ git('init', gitOpts), git('remote add origin ' + repoInfo.gitUrl, gitOpts), git('commit --allow-empty -am "initial"', gitOpts), repoInfo.branch !== 'master' ? git('checkout -b ' + repoInfo.branch, gitOpts) : null, git('add --all .', gitOpts), git('commit -am "second"', gitOpts) ].filter(Boolean), callback); }; } TestCluster.prototype.updateRemote = function updateRemote(name, files, callback) { var self = this; var remoteDir = path.join(self.remotesDir, name); series([ rimraf.bind(null, path.join(remoteDir, 'idl')), createFixtures.bind(null, remoteDir, files), git('add --all .', { cwd: remoteDir }), git('commit -am "update files"', { cwd: remoteDir }) ], callback); }; TestCluster.prototype.setupUpstream = function setupUpstream(cb) { var self = this; series([ mkdirp.bind(null, self.upstreamDir), git('init', { cwd: self.upstreamDir }), git('commit --allow-empty -am "initial"', { cwd: self.upstreamDir }), git('config --bool core.bare true', { cwd: self.upstreamDir }) ], cb); }; TestCluster.prototype.writeConfigFile = function writeConfigFile(cb) { var self = this; var data = JSON.stringify(self.config, null, ' ') + '\n'; fs.writeFile(self.configFile, data, 'utf8', cb); }; TestCluster.prototype.setupIDLDaemon = function setupIDLDaemon(cb) { var self = this; if (self.idlDaemon) { self.idlDaemon.destroy(); } self.idlDaemon = IDLDaemon({ configFile: self.configFile, logger: self.logger, timers: self.timers }); self.idlDaemon.bootstrap(self.fetchRemotes, cb); }; TestCluster.prototype.gitlog = function gitlog(cb) { var self = this; var command = 'git log --pretty="%s"'; exec(command, { cwd: self.upstreamDir }, cb); }; TestCluster.prototype.gitshow = function gitshow(file, cb) { var self = this; var command = 'git show HEAD:' + file; exec(command, { cwd: self.upstreamDir }, cb); }; TestCluster.prototype.gittag = function gittag(cb) { var self = this; var command = 'git tag --list'; exec(command, { cwd: self.upstreamDir }, cb); }; TestCluster.prototype.gitlsfiles = function gitlsfiles(cb) { var self = this; var command = 'git ls-tree --full-tree -r HEAD'; exec(command, { cwd: self.upstreamDir }, onlsfiles); function onlsfiles(err, stdout, stderr) { if (err) { return cb(err); } var files = stdout.trim().split('\n').map(parseFilepaths); cb(null, files); } function parseFilepaths(file) { return file.split(/\s/)[3]; } }; TestCluster.prototype.inspectUpstream = function inspectUpstream(callback) { var self = this; parallel({ gitlog: self.gitlog.bind(self), gittag: self.gittag.bind(self), gitlsfiles: self.gitlsfiles.bind(self), meta: function thunk(cb) { self.gitshow('meta.json', onFile); function onFile(err, file) { if (err) { return cb(err); } cb(null, JSON.parse(file)); } } }, readFiles); function readFiles(err, results) { if (err) { return callback(err); } var fileTasks = results.gitlsfiles.reduce(function b(acc, file) { acc[file] = self.gitshow.bind(self, file); return acc; }, {}); parallel(fileTasks, function onFiles(readFilesErr, files) { if (readFilesErr) { return callback(readFilesErr); } results.files = files; callback(null, results); }); } }; TestCluster.prototype.inspectLocalApp = function inspectLocalApp(callback) { var self = this; readDirFiles(self.localApp, 'utf8', callback); }; TestCluster.prototype.idlGet = function idlGet(text, cb) { var self = this; text = text + ' --repository=' + 'file://' + self.upstreamDir; text = text + ' --cacheDir=' + self.getCacheDir; text = text + ' --cwd=' + self.localApp; return IDL.exec(text, { preauth: 'true', logger: self.logger, timers: self.timers }, cb); }; TestCluster.prototype.idlFetch = function idlFetch(moduleName, cb) { var self = this; var text = 'fetch ' + moduleName; text = text + ' --repository=' + 'file://' + self.upstreamDir; text = text + ' --cacheDir=' + self.getCacheDir; text = text + ' --cwd=' + self.localApp; return IDL.exec(text, { preauth: 'true', logger: self.logger, timers: self.timers }, cb); }; TestCluster.prototype.idlPublish = function idlPublish(cwd, cb) { var self = this; var text = 'publish'; text = text + ' --repository=' + 'file://' + self.upstreamDir; text = text + ' --cacheDir=' + self.getCacheDir; text = text + ' --cwd=' + cwd; return IDL.exec(text, { preauth: 'true', logger: self.logger, timers: self.timers }, cb); }; TestCluster.prototype.idlUpdate = function idlUpdate(cb) { var self = this; var text = 'update'; text = text + ' --repository=' + 'file://' + self.upstreamDir; text = text + ' --cacheDir=' + self.getCacheDir; text = text + ' --cwd=' + self.localApp; return IDL.exec(text, { preauth: 'true', logger: self.logger, timers: self.timers }, cb); }; TestCluster.prototype.close = function close(cb) { var self = this; self.idlDaemon.destroy(); rimraf(self.fixturesDir, cb); }; function git(text, opts) { return exec.bind(null, 'git ' + text, opts); }
'use strict'; var debug = require('debug')('secc:routes:schedulerArchive'); var environment = require('../lib/environment.js'); var path = require('path'); module.exports = function(express, io, SECC, SCHEDULER) { var router = express.Router(); var am = SCHEDULER.am; router.get('/', function(req, res) { res.json(am.getArchiveList()); }); router.get('/:archiveId', function(req, res) { var archiveId = req.params.archiveId; if (!am.archiveExists(archiveId)) return res.status(400).send('archive not exists.'); return res.json(am.getArchiveInfo(archiveId)); }); router.get('/:archiveId/target', function(req, res) { var archiveId = req.params.archiveId; if (!am.archiveExists(archiveId)) return res.status(400).send('archive not exists.'); return res.json(am.getArchiveInfo(archiveId).targets); }); router.post('/:archiveId/target/:target', function(req, res) { var archiveId = req.params.archiveId; var target = req.params.target; if (!am.archiveExists(archiveId)) return res.status(400).send('archive not exists.'); am.addTarget(archiveId, target, function(err, archive) { if (err) { debug(err); return res.status(400).send('unable to add a target.'); } return res.json(archive.targets); }); }); router.delete('/:archiveId/target/:target', function(req, res) { var archiveId = req.params.archiveId; var target = req.params.target; if (!am.archiveExists(archiveId)) return res.status(400).send('archive not exists.'); am.removeTarget(archiveId, target, function(err, archive) { if (err) { debug(err); return res.status(400).send('unable to remove a target.'); } return res.json(archive.targets); }); }); router.get('/:archiveId/file/', function(req, res) { var archiveId = req.params.archiveId; if (!am.archiveExists(archiveId)) return res.status(400).send('archive not exists.'); var archive = am.getArchiveInfo(archiveId); res.attachment(archive.archiveFile); res.sendFile(path.join(SECC.archivePath, archive.archiveFile)); }); router.delete('/:archiveId', function(req, res) { var archiveId = req.params.archiveId; if (!am.archiveExists(archiveId)) return res.status(400).send('archive not exists.'); am.removeArchive(archiveId, function(err) { if (err) { debug(err); return res.status(400).send('unable to remove an archive.'); } io.emit('schedulerArchives', am.getArchiveList()); return res.send('archive deleted.'); }); }); router.post('/', function(req, res) { var archive = {}; try { archive = JSON.parse(req.body.archive); } catch (e) { debug('req.body.archive is not a json string. not serializable.'); } // check the input data. try { if ( archive.platform === undefined || archive.arch === undefined || archive.compiler === undefined || archive.version === undefined || archive.dumpmachine === undefined || archive.targets === undefined || archive.archiveLog === undefined || archive.archiveFile === undefined) throw new Error('invalid archive data'); // extract version(x.y.z) from '--version' string archive.compilerVersion = environment.getCompilerVersionFromString(archive.compiler, archive.version); if (archive.compilerversion === null) throw new Error('unable to extract the version'); // generate archiveId in server side archive.archiveId = environment.generatorArchiveId(archive); if (am.archiveExists(archive.archiveId)) throw new Error('archive already exists.'); } catch (e) { debug(e.message); debug(req.body); debug(req.file); return res.status(400).send(e.message); } // add new archive am.addArchive(archive, req.file, function(err) { if (err) { debug(err); return res.status(400).send('unable to add.'); } debug('an archive is uploaded'); debug(am.getArchiveInfo(archive.archiveId)); io.emit('schedulerArchives', am.getArchiveList()); return res.json(am.getArchiveInfo(archive.archiveId)); }); }); return router; };
// style for game font/menu var style; (function () { // the variables declared here will not be scoped anywhere and will only be accessible in this wrapped function var defaultColor = "white", highlightColor = "#FEFFD5"; style = { navitem: { base: { font: '30pt TheMinion', align: 'left', srokeThickness: 4 }, default: { fill: defaultColor, stroke: 'rgba(0,0,0,0)' }, hover: { fill: highlightColor, stroke: 'rgba(200,200,200,0.5)' } } }; Object.assign(style.navitem.hover, style.navitem.base); Object.assign(style.navitem.default, style.navitem.base); })();
/** * @name pc * @namespace * @description Root namespace for the PlayCanvas Engine. */ /** * @private * @function * @name _typeLookup * @description Create look up table for types. */ var _typeLookup = function () { var result = { }; var names = ["Array", "Object", "Function", "Date", "RegExp", "Float32Array"]; for (var i = 0; i < names.length; i++) result["[object " + names[i] + "]"] = names[i].toLowerCase(); return result; }(); var version = "__CURRENT_SDK_VERSION__"; var revision = "__REVISION__"; var config = { }; var common = { }; var apps = { }; // Storage for the applications using the PlayCanvas Engine var data = { }; // Storage for exported entity data /** * @private * @function * @name pc.type * @description Extended typeof() function, returns the type of the object. * @param {object} obj - The object to get the type of. * @returns {string} The type string: "null", "undefined", "number", "string", "boolean", "array", "object", "function", "date", "regexp" or "float32array". */ function type(obj) { if (obj === null) { return "null"; } var type = typeof obj; if (type === "undefined" || type === "number" || type === "string" || type === "boolean") { return type; } return _typeLookup[Object.prototype.toString.call(obj)]; } /** * @private * @function * @name pc.extend * @description Merge the contents of two objects into a single object. * @param {object} target - The target object of the merge. * @param {object} ex - The object that is merged with target. * @returns {object} The target object. * @example * var A = { * a: function () { * console.log(this.a); * } * }; * var B = { * b: function () { * console.log(this.b); * } * }; * * pc.extend(A, B); * A.a(); * // logs "a" * A.b(); * // logs "b" */ function extend(target, ex) { var prop, copy; for (prop in ex) { copy = ex[prop]; if (type(copy) == "object") { target[prop] = extend({}, copy); } else if (type(copy) == "array") { target[prop] = extend([], copy); } else { target[prop] = copy; } } return target; } /** * @private * @function * @name pc.isDefined * @description Return true if the Object is not undefined. * @param {object} o - The Object to test. * @returns {boolean} True if the Object is not undefined. */ function isDefined(o) { var a; return (o !== a); } export { apps, common, config, data, extend, isDefined, revision, type, version };
var constants = require('./index'); module.exports = constants(['FETCH_FAILED']);
import React from 'react' import Icon from 'react-icon-base' const FaNeuter = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m32.7 12.9q0 4.9-3.3 8.5t-8.1 4.2v13.7q0 0.3-0.2 0.5t-0.5 0.2h-1.5q-0.3 0-0.5-0.2t-0.2-0.5v-13.7q-4.8-0.5-8.1-4.2t-3.3-8.5q0-2.7 1-5t2.8-4.1 4.1-2.8 5-1 4.9 1 4.2 2.8 2.7 4.1 1 5z m-12.8 10q4.1 0 7-3t3-7-3-7.1-7-2.9-7.1 2.9-2.9 7.1 2.9 7 7.1 3z"/></g> </Icon> ) export default FaNeuter
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.11.1_A1; * @section: 11.11.1; * @assertion: White Space and Line Terminator between LogicalANDExpression and "&&" or between "&&" and BitwiseORExpression are allowed; * @description: Checking by using eval; */ //CHECK#1 if ((eval("true\u0009&&\u0009true")) !== true) { $ERROR('#1: (true\\u0009&&\\u0009true) === true'); } //CHECK#2 if ((eval("true\u000B&&\u000Btrue")) !== true) { $ERROR('#2: (true\\u000B&&\\u000Btrue) === true'); } //CHECK#3 if ((eval("true\u000C&&\u000Ctrue")) !== true) { $ERROR('#3: (true\\u000C&&\\u000Ctrue) === true'); } //CHECK#4 if ((eval("true\u0020&&\u0020true")) !== true) { $ERROR('#4: (true\\u0020&&\\u0020true) === true'); } //CHECK#5 if ((eval("true\u00A0&&\u00A0true")) !== true) { $ERROR('#5: (true\\u00A0&&\\u00A0true) === true'); } //CHECK#6 if ((eval("true\u000A&&\u000Atrue")) !== true) { $ERROR('#6: (true\\u000A&&\\u000Atrue) === true'); } //CHECK#7 if ((eval("true\u000D&&\u000Dtrue")) !== true) { $ERROR('#7: (true\\u000D&&\\u000Dtrue) === true'); } //CHECK#8 if ((eval("true\u2028&&\u2028true")) !== true) { $ERROR('#8: (true\\u2028&&\\u2028true) === true'); } //CHECK#9 if ((eval("true\u2029&&\u2029true")) !== true) { $ERROR('#9: (true\\u2029&&\\u2029true) === true'); } //CHECK#10 if ((eval("true\u0009\u000B\u000C\u0020\u00A0\u000A\u000D\u2028\u2029&&\u0009\u000B\u000C\u0020\u00A0\u000A\u000D\u2028\u2029true")) !== true) { $ERROR('#10: (true\\u0009\\u000B\\u000C\\u0020\\u00A0\\u000A\\u000D\\u2028\\u2029&&\\u0009\\u000B\\u000C\\u0020\\u00A0\\u000A\\u000D\\u2028\\u2029true) === true'); }
const { DefinePlugin } = require("webpack"); module.exports = { devtool: "source-map", mode: "production", entry: { index: [__dirname + "/src/index.ts"] }, output: { path: __dirname, library: "sift", libraryTarget: "umd", globalObject: "this", filename: `sift.${process.env.CSP_ENABLED ? "csp." : ""}min.js` }, resolve: { extensions: [".js", ".ts"] }, module: { rules: [ { test: /\.ts$/, exclude: /(node_modules|bower_components)/, use: ["ts-loader"] } ] }, plugins: [ new DefinePlugin({ "process.env.CSP_ENABLED": JSON.stringify( process.env.CSP_ENABLED || false ) }) ] };
/*eslint-env node, mocha */ 'use strict'; var lint = require('../../index.js'); var paths = ['tests/fixtures/warning']; var options = { formatter: 'stylish', alwaysWarn: true }; lint(paths, options);
var react = require('react') , isolator = require('./isolator'); var spec = { requestContext: react.PropTypes.object, rootIsolator: react.PropTypes.instanceOf(isolator), locales: react.PropTypes.oneOfType([ react.PropTypes.string, react.PropTypes.array ]) }; module.exports = { contextTypes : spec, childContextTypes: spec, getInitialState: function() { // create a local instrument with our isolatedConfig. This is like having our own constructor this.instrument = require('pellet').instrumentation.addIsolatedConfig(this.context.rootIsolator.isolatedConfig); return (this.props && this.props.__initState) || {}; }, event: function(name) { if(!this._$isolator) { console.verbose('add local isolator because event:', name); this._$isolator = this.context.rootIsolator.createChild(); } return this._$isolator.event(name); }, coordinator: function(name, type) { if(!this._$isolator) { console.verbose('add local isolator because isolator:', name, type); this._$isolator = this.context.rootIsolator.createChild(); } return this._$isolator.coordinator(name, type); }, getLocales: function() { return this.props.locales || this.context.locales; }, getRequestContext: function() { return this.context.requestContext; }, getIsolatedConfig: function() { if(this._$isolator) { return this._$isolator.isolatedConfig; } else { return this.context.rootIsolator.isolatedConfig; } }, componentWillUnmount: function() { // release everything if root element unmounting // else check if local isolator that we need to // release. if(!this._owner) { console.verbose('release rootIsolator'); this.context.rootIsolator.release(); } else if(this._$isolator) { console.verbose('release local isolator'); this._$isolator.release(); } }, getChildContext: function () { return { rootIsolator: this.context.rootIsolator, requestContext: this.context.requestContext, locales: this.getLocales() }; } };
'use strict' // Require and expose jQuery to window for Bootstrap window.$ = window.jQuery = require('jquery') // Don't require all of Bootstrap, just the parts we need // require('bootstrap') require('bootstrap/js/dist/util.js') // require('bootstrap/js/dist/alert.js') require('bootstrap/js/dist/button.js') require('bootstrap/js/dist/carousel.js') require('bootstrap/js/dist/collapse.js') require('bootstrap/js/dist/dropdown.js') // require('bootstrap/js/dist/modal.js') // require('bootstrap/js/dist/scrollspy.js') // require('bootstrap/js/dist/tab.js') // require('bootstrap/js/dist/tooltip.js') // require('bootstrap/js/dist/popover.js')
var searchData= [ ['controls',['Controls',['../namespace_generic_inliner_1_1_core_1_1_u_i_1_1_controls.html',1,'GenericInliner::Core::UI']]], ['core',['Core',['../namespace_generic_inliner_1_1_core.html',1,'GenericInliner']]], ['extensions',['Extensions',['../namespace_generic_inliner_1_1_core_1_1_extensions.html',1,'GenericInliner::Core']]], ['genericinliner',['GenericInliner',['../namespace_generic_inliner.html',1,'']]], ['properties',['Properties',['../namespace_generic_inliner_1_1_properties.html',1,'GenericInliner']]], ['providers',['Providers',['../namespace_generic_inliner_1_1_core_1_1_providers.html',1,'GenericInliner::Core']]], ['settings',['Settings',['../namespace_generic_inliner_1_1_core_1_1_settings.html',1,'GenericInliner::Core']]], ['ui',['UI',['../namespace_generic_inliner_1_1_core_1_1_u_i.html',1,'GenericInliner::Core']]] ];
$(document).ready(function() { $('.session_row').click(function(){ window.document.location = $(this).attr("href"); }); });
import _ from 'lodash'; import React, {Component} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import Subheader from './subheader'; import LoadingIndicator from '../../common/components/loading-indicator'; import loginServices from '../../common/utils/login-services'; import * as authActionCreators from '../../state/auth/action-creators'; function getLoginServiceImgUrl(serviceName) { return `/${serviceName.toLowerCase()}[email protected]`; } export class Account extends Component { render() { const {user, userMeta} = this.props; const {logins} = user; const linkedServices = _.chain(logins) .map((isLinked, serviceName) => ({isLinked, serviceName})) .filter(service => service.isLinked) .value(); const isSavingName = _.get(userMeta.updatingAttributes, 'name'); const isSavingEmail = _.get(userMeta.updatingAttributes, 'email'); return ( <div> <Subheader/> <div className="account container container-bottomSpaced"> <div className="account-form-row"> <div className="account-label-container"> <label htmlFor="user-name" className="account-label">Name</label> </div> <div className="account-field-container"> <input id="user-name" type="text" autoCapitalize="words" autoComplete="name" spellCheck={false} className="text-input account_textInput" value={this.state.name} onChange={(e) => this.setState({name: e.target.value})} onBlur={(e) => this.onBlurInput('name', e.target.value)} disabled={isSavingName}/> <div className="account_loadingIndicatorContainer"> {isSavingName && ( <LoadingIndicator className="account_loadingIndicator"/> )} </div> </div> </div> <div className="account-form-row"> <div className="account-label-container"> <label htmlFor="user-email" className="account-label">Email</label> </div> <div className="account-field-container"> <input id="user-email" type="email" autoCapitalize="none" autoComplete="email" spellCheck={false} className="text-input account_textInput" value={this.state.email} onChange={(e) => this.setState({email: e.target.value})} onBlur={(e) => this.onBlurInput('email', e.target.value)} disabled={isSavingEmail}/> <div className="account_loadingIndicatorContainer"> {isSavingEmail && ( <LoadingIndicator className="account_loadingIndicator"/> )} </div> </div> </div> <div className="resource-list-header"> <div className="resource-list-header-text"> Logins </div> </div> <ul className="resourceList"> {loginServices.map((service) => { const lowerCaseServiceName = service.name.toLowerCase(); const isLinked = _.find(linkedServices, (service) => ( service.serviceName.toLowerCase() === lowerCaseServiceName )); return ( <li className="resourceListItem" key={service.name}> <img className="resource-list-account-icon" src={getLoginServiceImgUrl(lowerCaseServiceName)}/> {_.capitalize(service.name)} {isLinked && ( <button className="resourceListItem-deleteBtn" onClick={() => this.logout(lowerCaseServiceName)} disabled={linkedServices.length === 1}> Remove </button> )} {!isLinked && ( <a className="resourceListItem-primaryBtn" href={`/login/${lowerCaseServiceName}`}> Link </a> )} </li> ); } )} </ul> </div> </div> ); } constructor(props) { super(props); const {user} = props; this.state = { email: user.email, name: user.name, }; } onBlurInput = (field, newValue) => { const {updateProfile, user} = this.props; // If the user hasn't entered anything, we do nothing if (!newValue) { return; } // If the user hasn't changed the value, then we do not need to save if (user[field] === newValue) { return; } updateProfile({ id: user.id, attributes: { [field]: newValue } }); } logout = (serviceName) => { const {unlinkAccount} = this.props; const lowerCaseServiceName = serviceName.toLowerCase(); unlinkAccount(lowerCaseServiceName); } } function mapStateToProps(state) { return { user: state.auth.user || {}, userMeta: state.auth.userMeta || {} }; } function mapDispatchToProps(dispatch) { return bindActionCreators(authActionCreators, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Account);
import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; import createLogger from 'redux-logger'; export default function configureStore(reducers, initialState = {}) { const loggerMiddleware = createLogger(); return applyMiddleware( thunkMiddleware, loggerMiddleware )(createStore)(reducers, initialState); }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M14.06 9.02 5 18.08V19h.92l9.06-9.06z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M18.37 3.29c-.2-.2-.45-.29-.71-.29s-.51.1-.7.29l-1.83 1.83 3.75 3.75 1.83-1.83c.39-.39.39-1.02 0-1.41l-2.34-2.34zm-.56 6.65-3.75-3.75L3 17.25V21h3.75L17.81 9.94zM5 19v-.92l9.06-9.06.92.92L5.92 19H5z" }, "1")], 'ModeTwoTone'); exports.default = _default;
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z" }), 'PresentToAll'); exports.default = _default;
import VisualTOC from './diagrams/VisualTOC.html'; // eagerly initialize vtoc as it's above the fold const tocNav = document.getElementById('vtoc'); const visualTOC = new VisualTOC({target: tocNav}); // lazily initialize any diagram below the fold. E.G: // { // const figure = document.getElementById('StyleTransferExamples'); // figure.addEventListener("ready", function() { // const styleTransferExamples = new StyleTransferExamples({target: figure}); // }); // }
/*! * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ import {assert} from '@ciscospark/test-helper-chai'; export default function runAbstractStorageAdapterSpec(adapter) { const key = `key`; const namespace = `namespace`; const obj = {a: 1}; const primitive = 1; const options = { logger: console }; describe(`#bind()`, () => { // namespace and options.logger are required more to make sure we always // call bind correctly rather than to make sure the adapter uses them. it(`requires a namespace`, () => assert.isRejected(adapter.bind(), /`namespace` is required/)); it(`requires a logger option`, () => assert.isRejected(adapter.bind(namespace), /`options.logger` is required/)); it(`returns a db interface`, () => assert.isFulfilled(adapter.bind(namespace, options))); describe(`bound`, () => { let bound; before(() => adapter.bind(namespace, options) .then((b) => { bound = b; })); describe(`#put()`, () => { it(`puts a primitive into the store`, () => bound.put(key, primitive) .then(() => assert.becomes(bound.get(key), primitive))); [0, false, null].forEach((falsey) => { it(`puts falsey primitive \`${falsey}\` into the store`, () => bound.put(key, falsey) .then(() => assert.becomes(bound.get(key), falsey))); }); it(`puts an object into the store`, () => bound.put(key, obj) .then(() => assert.becomes(bound.get(key), obj))); it(`puts an array into the store`, () => bound.put(key, [1, 2]) .then(() => assert.becomes(bound.get(key), [1, 2]))); it(`puts an array back into the store`, () => bound.put(key, [1, 2]) .then(() => assert.becomes(bound.get(key), [1, 2])) .then(() => bound.put(key, [1, 2, 3])) .then(() => assert.becomes(bound.get(key), [1, 2, 3]))); it(`handles concurrency`, () => Promise.all([ bound.put(key, 1), bound.put(key, 2), bound.put(key, 3) ]) .then(() => assert.becomes(bound.get(key), 3))); it(`puts same key in different namespaces`, () => { return bound.put(key, primitive) .then(() => { return adapter.bind(`namespace2`, options) .then((b) => { const primitive2 = 2; b.put(key, primitive2) .then(() => Promise.all([ assert.becomes(bound.get(key), primitive), assert.becomes(b.get(key), primitive2) ])); }); }); }); }); describe(`#get()`, () => { it(`gets a primitive from the store`, () => bound.put(key, primitive) .then(() => assert.becomes(bound.get(key), primitive))); it(`gets an object from the store`, () => bound.put(key, obj) .then(() => assert.becomes(bound.get(key), obj))); it(`rejects if the key cannot be found`, () => assert.isRejected(bound.get(`notakey`))); }); describe(`#del()`, () => { it(`removes a primitive from the store`, () => bound.put(key, primitive) .then(() => assert.becomes(bound.get(key), primitive)) .then(() => assert.isFulfilled(bound.del(key))) .then(() => assert.isRejected(bound.get(key)))); it(`removes an object from the store`, () => bound.put(key, obj) .then(() => assert.becomes(bound.get(key), obj)) .then(() => assert.isFulfilled(bound.del(key))) .then(() => assert.isRejected(bound.get(key)))); it(`removes an item from the store when putting \`undefined\``, () => bound.put(key, undefined) .then(() => assert.isFulfilled(bound.del(key))) .then(() => assert.isRejected(bound.get(key)))); }); describe(`#clear()`, () => { it(`clears a primitive from the store`, () => bound.put(key, primitive) .then(() => assert.becomes(bound.get(key), primitive)) .then(() => assert.isFulfilled(bound.clear())) .then(() => assert.isRejected(bound.get(key)))); it(`clears an object from the store`, () => bound.put(key, obj) .then(() => assert.becomes(bound.get(key), obj)) .then(() => assert.isFulfilled(bound.clear(key))) .then(() => assert.isRejected(bound.get(key)))); it(`clears an item from the store when putting \`undefined\``, () => bound.put(key, undefined) .then(() => assert.isFulfilled(bound.clear(key))) .then(() => assert.isRejected(bound.get(key)))); }); }); }); }
/////////////////////////////////////////////////////// // Bonsai - Server - Worker Service // Dependencies // Application Imports import models from "bonsai-engine/db/models"; import { getRouteMap, route } from "bonsai-engine/routing"; import {BroadcastClient} from "bonsai-engine/queue"; import { newStore, Tracker } from "bonsai-engine/state"; import { uuid, handleDefaultRejections } from "bonsai-engine/utilities"; // Configuration import * as config from "config"; import { getDefaultControllers, } from "./routing"; import { debug } from "./utilities"; handleDefaultRejections(); // Initialize Database models.sequelize.sync(); // Routing var routeMap = []; var broadcast = new BroadcastClient({ path: config.rabbit.host, exchange: config.rabbit.broadcastqueue, router: (path, data) => route(routeMap, path, data) }); var store = newStore(); var tracker = new Tracker(broadcast, store); routeMap = getRouteMap(getDefaultControllers( tracker, models )); process.on('exit', c => { console.log(' [-] Worker Terminated PID ' + process.pid); }); Promise .all([broadcast.listen()]) .then(x => { console.log(' [+] Worker Started PID ' + process.pid); // Register Routes for (let routePath in routeMap) { broadcast.watch(routePath); } }) .catch(err => { console.error(' [X] Unable to start worker.'); console.error(err); console.error(err.stack); });
import Raspberry from "../models/Raspberry"; var _ = require("lodash"); /** * Configure a new raspberry * @param {String} req.body.name instance name * @param {Array<String>} req.body.modules instance modules names * @param {Object} res response object */ var add = function(req, res) { if (!req.body || !req.body.name || !req.body.modules) { return res.json({status: "error", error: {code: -1, message: "invalid request"}}); } Raspberry.add(req.body.name, req.body.modules) .then(function(raspberry) { return res.json({status: "success", data: raspberry}); }).catch(function(error) { return res.json({status: "error", error: error}); }); } /** * Get all connected rasberries */ var getAll = function(req, res) { Raspberry.getAll() .then(function(list) { return res.json({status: "success", data: { items: list, total: list.length }}); }) }; var get = function(req, res) { if (!req.params.name) return res.json({status: "error", error: {code: -1, message: "invalid request"}}); Raspberry.findOne(req.params.name) .then(function(raspberry) { return res.json({status: "success", data: { raspberry: raspberry }}); }).catch(res.json); }; module.exports = { add: add, getAll: getAll, get: get };
/** * Tweetie: A simple Twitter feed plugin * Author: Sonny T. <[email protected]>, sonnyt.com */ (function ($) { $.fn.twittie = function (options) { // Default settings var settings = $.extend({ 'count': 1, 'hideReplies': false, 'dateFormat': '%b/%d/%Y', 'template': '<span>{{date}}</span> - {{tweet}}' }, options); /** * Applies @reply, #hash and http links * @param {String} tweet A single tweet * @return {String} Fixed tweet */ var linking = function (tweet) { var parts = tweet.split(' '); var twit = ''; for (var i = 0, len = parts.length; i < len; i++) { var text = parts[i]; var link = "https://twitter.com/#!/"; // Fix hashtag links if (text.indexOf('#') !== -1) { text = '<a href="' + link + 'search/' + text.replace('#', '%23').replace(/[^A-Za-z0-9]/, '') + '" target="_blank">' + text + '</a>'; } // Fix reply links if (text.indexOf('@') !== -1) { text = '<a href="' + link + text.replace('@', '').replace(/[^A-Za-z0-9]/, '') + '" target="_blank">' + text + '</a>'; } // Fix regular http links if (text.indexOf('http://') !== -1) { text = '<a href="' + text + '" target="_blank">' + text + '</a>'; } twit += text + ' '; } return twit; }; /** * Formating a date * @param {String} twt_date Twitter date * @return {String} Formatted date */ var dating = function (twt_date) { // fix for IE var time = twt_date.split(' '); twt_date = new Date(Date.parse(time[1] + ' ' + time[2] + ', ' + time[5] + ' ' + time[3] + ' UTC')); var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var _date = { '%d': twt_date.getDate(), '%m': twt_date.getMonth()+1, '%b': months[twt_date.getMonth()].substr(0, 3), '%B': months[twt_date.getMonth()], '%y': String(twt_date.getFullYear()).slice(-2), '%Y': twt_date.getFullYear() }; var date = settings.dateFormat; var format = settings.dateFormat.match(/%[dmbByY]/g); for (var i = 0, len = format.length; i < len; i++) { date = date.replace(format[i], _date[format[i]]); } return date; }; /** * Templating a tweet using '{{ }}' braces * @param {Object} data Tweet details are passed * @return {String} Templated string */ var templating = function (data) { var temp = settings.template; var temp_variables = ['date', 'tweet', 'avatar']; for (var i = 0, len = temp_variables.length; i < len; i++) { temp = temp.replace(new RegExp('{{' + temp_variables[i] + '}}', 'gi'), data[temp_variables[i]]); } return temp; }; // Set loading this.html('<span>Loading...</span>'); var that = this; // Fetch tweets $.getJSON('api/tweet.php', { count: settings.count, exclude_replies: settings.hideReplies }, function (twt) { that.find('span').fadeOut('fast', function () { that.html('<ul></ul>'); for (var i = 0; i < settings.count; i++) { if (twt[i]) { var temp_data = { date: dating(twt[i].created_at), tweet: linking(twt[i].text), avatar: '<img src="'+ twt[i].user.profile_image_url +'" />' }; that.find('ul').append('<li>' + templating(temp_data) + '</li>'); } else { break; } } }); }); }; })(jQuery);
// Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` (`self`) in the browser, or `global` on the server. // We use `self` instead of `window` for `WebWorker` support. // 在 Client JavaScript 中 window 对象即是 self 对象,也就是说 window === self // 结果为 true var root = ( typeof self === 'object' && self.self === self && self ) || ( typeof global === 'object' && global.global === global && global ); // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeCreate = Object.create; // Naked function reference for surrogate-prototype-swapping. var Ctor = function(){}; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for their old module API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.8.3'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var optimizeCb = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. var cb = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value)) return _.matcher(value); return _.property(value); }; _.iteratee = function(value, context) { return cb(value, context, Infinity); }; // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. var restArgs = function(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); var index; for (index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); case 2: return func.call(this, arguments[0], arguments[1], rest); } var args = Array(startIndex + 1); for (index = 0; index < startIndex; index++) { args[index] = arguments[index]; } args[startIndex] = rest; return func.apply(this, args); }; }; // An internal function for creating a new object that inherits from another. var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; }; var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; // Helper for collection methods to determine whether a collection // should be iterated as an array or as an object // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; var getLength = property('length'); var isArrayLike = function(collection) { var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Create a reducing function iterating left or right. var createReduce = function(dir) { // Optimized iterator function as using arguments.length // in the main function will deoptimize the, see #1991. var reducer = function(obj, iteratee, memo, initial) { var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; if (!initial) { memo = obj[keys ? keys[index] : index]; index += dir; } for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; return function(obj, iteratee, memo, context) { var initial = arguments.length >= 3; return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); }; }; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = createReduce(1); // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = createReduce(-1); // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var key; if (isArrayLike(obj)) { key = _.findIndex(obj, predicate, context); } else { key = _.findKey(obj, predicate, context); } if (key !== void 0 && key !== -1) return obj[key]; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; predicate = cb(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given item (using `===`). // Aliased as `includes` and `include`. _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { if (!isArrayLike(obj)) obj = _.values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return _.indexOf(obj, item, fromIndex) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = restArgs(function(obj, method, args) { var isFunc = _.isFunction(method); return _.map(obj, function(value) { var func = isFunc ? method : value[method]; return func == null ? func : func.apply(value, args); }); }); // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = v; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = v; lastComputed = computed; } }); } return result; }; // Shuffle a collection. _.shuffle = function(obj) { return _.sample(obj, Infinity); }; // Sample **n** random values from a collection using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj); var length = getLength(sample); n = Math.max(Math.min(n, length), 0); var last = length - 1; for (var index = 0; index < n; index++) { var rand = _.random(index, last); var temp = sample[index]; sample[index] = sample[rand]; sample[rand] = temp; } return sample.slice(0, n); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = cb(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior, partition) { return function(obj, iteratee, context) { var result = partition ? [[], []] : {}; iteratee = cb(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = group(function(result, value, pass) { result[pass ? 0 : 1].push(value); }, true); // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; return _.initial(array, array.length - n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return _.rest(array, Math.max(0, array.length - n)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { output = output || []; var idx = output.length; for (var i = 0, length = getLength(input); i < length; i++) { var value = input[i]; if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { //flatten current level of array or arguments object if (shallow) { var j = 0, len = value.length; while (j < len) output[idx++] = value[j++]; } else { flatten(value, shallow, strict, output); idx = output.length; } } else if (!strict) { output[idx++] = value; } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false); }; // Return a version of the array that does not contain the specified value(s). _.without = restArgs(function(array, otherArrays) { return _.difference(array, otherArrays); }); // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!_.contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!_.contains(result, value)) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = restArgs(function(arrays) { return _.uniq(flatten(arrays, true, true)); }); // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; var j; for (j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = restArgs(function(array, rest) { rest = flatten(rest, true, true); return _.filter(array, function(value){ return !_.contains(rest, value); }); }); // Complement of _.zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices _.unzip = function(array) { var length = array && _.max(array, getLength).length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = restArgs(_.unzip); // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Generator function to create the findIndex and findLastIndex functions var createPredicateIndexFinder = function(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; }; // Returns the first index on an array-like that passes a predicate test _.findIndex = createPredicateIndexFinder(1); _.findLastIndex = createPredicateIndexFinder(-1); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Generator function to create the indexOf and lastIndexOf functions var createIndexFinder = function(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), _.isNaN); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Determines whether to execute a function as a constructor // or a normal function with the provided arguments var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (_.isObject(result)) return result; return self; }; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = restArgs(function(func, context, args) { if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); var bound = restArgs(function(callArgs) { return executeBound(func, bound, context, this, args.concat(callArgs)); }); return bound; }); // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder by default, allowing any combination of arguments to be // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. _.partial = restArgs(function(func, boundArgs) { var placeholder = _.partial.placeholder; var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }); _.partial.placeholder = _; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = restArgs(function(obj, keys) { keys = flatten(keys, false, false); var index = keys.length; if (index < 1) throw new Error('bindAll must be passed function names'); while (index--) { var key = keys[index]; obj[key] = _.bind(obj[key], obj); } }); // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = restArgs(function(func, wait, args) { return setTimeout(function(){ return func.apply(null, args); }, wait); }); // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = _.partial(_.delay, _, 1); // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed on and after the Nth call. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed up to (but not including) the Nth call. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); _.restArgs = restArgs; // Object Functions // ---------------- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; var collectNonEnumProps = function(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = _.isFunction(constructor) && constructor.prototype || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { keys.push(prop); } } }; // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve all the property names of an object. _.allKeys = function(obj) { if (!_.isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Returns the results of applying the iteratee to each element of the object // In contrast to _.map it returns an object _.mapObject = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = _.keys(obj), length = keys.length, results = {}; for (var index = 0; index < length; index++) { var currentKey = keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // An internal function for creating assigner functions. var createAssigner = function(keysFunc, undefinedOnly) { return function(obj) { var length = arguments.length; if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; }; // Extend a given object with all the properties in passed-in object(s). _.extend = createAssigner(_.allKeys); // Assigns a given object with all the own properties in the passed-in object(s) // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) _.extendOwn = _.assign = createAssigner(_.keys); // Returns the first key on an object that passes a predicate test _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = _.keys(obj), key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (predicate(obj[key], key, obj)) return key; } }; // Internal pick helper function to determine if `obj` has key `key`. var keyInObj = function(value, key, obj) { return key in obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = restArgs(function(obj, keys) { var result = {}, iteratee = keys[0]; if (obj == null) return result; if (_.isFunction(iteratee)) { if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); keys = _.allKeys(obj); } else { iteratee = keyInObj; keys = flatten(keys, false, false); obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }); // Return a copy of the object without the blacklisted properties. _.omit = restArgs(function(obj, keys) { var iteratee = keys[0], context; if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); if (keys.length > 1) context = keys[1]; } else { keys = _.map(flatten(keys, false, false), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }); // Fill in a given object with default properties. _.defaults = createAssigner(_.allKeys, true); // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. _.create = function(prototype, props) { var result = baseCreate(prototype); if (props) _.extendOwn(result, props); return result; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Returns whether an object has a given set of `key:value` pairs. _.isMatch = function(object, attrs) { var keys = _.keys(attrs), length = keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; }; // Internal recursive comparison function for `isEqual`. var eq, deepEq; eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // `NaN`s are equivalent, but non-reflexive. if (a !== a) return b !== b; // Exhaust primitive checks var type = typeof a; if (type !== 'function' && type !== 'object' && typeof b !== 'object') return false; return deepEq(a, b, aStack, bStack); }; // Internal recursive comparison function for `isEqual`. deepEq = function(a, b, aStack, bStack) { // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } var areArrays = className === '[object Array]'; if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // Deep compare objects. var keys = _.keys(a), key; length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (_.keys(b).length !== length) return false; while (length--) { // Deep compare each member key = keys[length]; if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), and in Safari 8 (#1929). if (typeof /./ != 'function' && typeof Int8Array != 'object') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; // Predicate-generating functions. Often useful outside of Underscore. _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = property; // Generates a function for a given object that returns a given property. _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. _.matcher = _.matches = function(attrs) { attrs = _.extendOwn({}, attrs); return function(obj) { return _.isMatch(obj, attrs); }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, prop, fallback) { var value = object == null ? void 0 : object[prop]; if (value === void 0) { value = fallback; } return _.isFunction(value) ? value.call(object) : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escapeRegExp, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offset. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; var render; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var chainResult = function(instance, obj) { return instance._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return chainResult(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return chainResult(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return chainResult(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxy for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return '' + this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }());
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.compile = compile; exports.precompile = precompile; var _htmlbars = require("htmlbars"); // Return an executable function (object) version of the compiled template string function compile(string) { return new Function("return " + (0, _htmlbars.compileSpec)(string))(); // jshint ignore:line } // Return a precompiled (string) version of the compiled template string function precompile(string) { return (0, _htmlbars.compileSpec)(string); }
/* * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */ /*global define */ define(function (require, exports, module) { "use strict"; var Acorn = require("thirdparty/acorn/acorn"); var LANGUAGE_ID = "javascript", HTML_LANGUAGE_ID = "html", PHP_LANGUAGE_ID = "php", SUPPORTED_LANGUAGES = [LANGUAGE_ID, HTML_LANGUAGE_ID, PHP_LANGUAGE_ID], SINGLE_QUOTE = "'", DOUBLE_QUOTE = "\""; /** * Create a hint token with name value that occurs at the given list of * positions. * * @param {string} value - name of the new hint token * @param {?Array.<number>=} positions - optional list of positions at which * the token occurs * @return {Object} - a new hint token */ function makeToken(value, positions) { positions = positions || []; return { value: value, positions: positions }; } /** * Is the string key perhaps a valid JavaScript identifier? * * @param {string} key - string to test. * @return {boolean} - could key be a valid identifier? */ function maybeIdentifier(key) { var result = false, i; for (i = 0; i < key.length; i++) { result = Acorn.isIdentifierChar(key.charCodeAt(i)); if (!result) { break; } } return result; } /** * Is the token's class hintable? (A very conservative test.) * * @param {Object} token - the token to test for hintability * @return {boolean} - could the token be hintable? */ function hintable(token) { function _isInsideRegExp(token) { return token.state && (token.state.lastType === "regexp" || (token.state.localState && token.state.localState.lastType === "regexp")); } switch (token.type) { case "comment": case "number": case "regexp": case "string": // exclude variable & param decls case "def": return false; case "string-2": // exclude strings inside a regexp return !_isInsideRegExp(token); default: return true; } } /** * Determine if hints should be displayed for the given key. * * @param {string} key - key entered by the user * @param {boolean} showOnDot - show hints on dot ("."). * @return {boolean} true if the hints should be shown for the key, * false otherwise. */ function hintableKey(key, showOnDot) { return (key === null || (showOnDot && key === ".") || maybeIdentifier(key)); } /* * Get a JS-hints-specific event name. Used to prevent event namespace * pollution. * * @param {string} name - the unqualified event name * @return {string} - the qualified event name */ function eventName(name) { var EVENT_TAG = "brackets-js-hints"; return name + "." + EVENT_TAG; } /* * Annotate a list of tokens as literals of a particular kind; * if string literals, annotate with an appropriate delimiter. * * @param {Array.<Object>} literals - list of hint tokens * @param {string} kind - the kind of literals in the list (e.g., "string") * @return {Array.<Object>} - the input array; to each object in the array a * new literal {boolean} property has been added to indicate that it * is a literal hint, and also a new kind {string} property to indicate * the literal kind. For string literals, a delimiter property is also * added to indicate what the default delimiter should be (viz. a * single or double quotation mark). */ function annotateLiterals(literals, kind) { return literals.map(function (t) { t.literal = true; t.kind = kind; t.origin = "ecma5"; if (kind === "string") { if (/[\\\\]*[^\\]"/.test(t.value)) { t.delimiter = SINGLE_QUOTE; } else { t.delimiter = DOUBLE_QUOTE; } } return t; }); } /* * Annotate a list of tokens as keywords * * @param {Array.<Object>} keyword - list of keyword tokens * @return {Array.<Object>} - the input array; to each object in the array a * new keyword {boolean} property has been added to indicate that the * hint is a keyword. */ function annotateKeywords(keywords) { return keywords.map(function (t) { t.keyword = true; t.origin = "ecma5"; return t; }); } function isSupportedLanguage(languageId) { return SUPPORTED_LANGUAGES.indexOf(languageId) !== -1; } var KEYWORD_NAMES = [ "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "export", "extends", "finally", "for", "function", "if", "import", "in", "instanceof", "let", "new", "return", "super", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with", "yield" ], KEYWORD_TOKENS = KEYWORD_NAMES.map(function (t) { return makeToken(t, []); }), KEYWORDS = annotateKeywords(KEYWORD_TOKENS); var LITERAL_NAMES = [ "true", "false", "null" ], LITERAL_TOKENS = LITERAL_NAMES.map(function (t) { return makeToken(t, []); }), LITERALS = annotateLiterals(LITERAL_TOKENS); exports.makeToken = makeToken; exports.hintable = hintable; exports.hintableKey = hintableKey; exports.maybeIdentifier = maybeIdentifier; exports.eventName = eventName; exports.annotateLiterals = annotateLiterals; exports.isSupportedLanguage = isSupportedLanguage; exports.KEYWORDS = KEYWORDS; exports.LITERALS = LITERALS; exports.LANGUAGE_ID = LANGUAGE_ID; exports.SINGLE_QUOTE = SINGLE_QUOTE; exports.DOUBLE_QUOTE = DOUBLE_QUOTE; exports.SUPPORTED_LANGUAGES = SUPPORTED_LANGUAGES; });
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function FormValidationSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="forms-validation">Validation states</Anchor> <small>FormControl.Feedback</small> </h2> <p>Set <code>validationState</code> to one of <code>'success'</code>, <code>'warning'</code> or <code>'error'</code> to show validation state. Set <code>validationState</code> to <code>null</code> (or <code>undefined</code>) to hide validation state. Add <code>{'<FormControl.Feedback>'}</code> for a feedback icon when validation state is set.</p> <ReactPlayground codeText={Samples.FormValidation} /> <h3><Anchor id="forms-validation-props">Props</Anchor></h3> <h4><Anchor id="forms-props-form-control-feedback">FormControl.Feedback</Anchor></h4> <PropTable component="FormControlFeedback" /> </div> ); }
'use strict'; /** * * @author xiaoping ([email protected]) * @type js * */ var koa = require('koa'), onerror = require('koa-onerror'), cors = require('koa-cors'), requestLog = require('./middlewares/requestLog'), execTime = require('./middlewares/execTime'), api = require('./routes/api'), config = require('./config'), logger = require('./common/logger'), app = koa(); onerror(app); app.use(cors({ credentials: true })); // cors // log execution time app.use(execTime); // log request app.use(requestLog); api.forEach(function (route) { app.use(route.routes()); app.use(route.allowedMethods()); }); // app.use(router.routes()) app.on('error', function (err, ctx) { logger.error('server error', err, ctx); }); app.listen(config.port, function () { logger.log('server listening on port', config.port); logger.log(''); });
'use strict'; var _ = require('lodash'); var path = require('path'); var fs = require('fs'); var through2 = require('through2'); var gettextParser = require('gettext-parser'); var hbsTransFn = require('./lib/handlebars-translator'); var jsTransFn = require('./lib/javascript-translator'); // Publish a Node.js require() handler for .handlebars and .hbs files var extension = function(module, filename) { module.exports = fs.readFileSync(filename, 'utf8'); }; require.extensions['.handlebars'] = extension; require.extensions['.hbs'] = extension; var hbsTransObj = { fn: hbsTransFn, re: /\{\{trans\s*(?:"([^"]+)"|\'([^\']+)\')\s*\}\}/g, interpolateOptName: 'interpolateHbs' }; var translators = { '.handlebars': hbsTransObj, '.hbs': hbsTransObj, '.js': { fn: jsTransFn, re: /trans\(\s*(?:"([^"]+)"|\'([^\']+)\')\s*\)\s*/g, interpolateOptName: 'interpolateJs' }, }; var getTranslator = function(catalog, opts, ext) { var transObj = translators[ext]; var re = opts[transObj.interpolateOptName] || transObj.re; return function(chunk, enc, callback) { var translated = transObj.fn(chunk.toString(), catalog, re); callback(null, translated); }; }; var getJSONCatalog = function(locale, localeDirs) { var catalogDir = function(localeDir) { var fp = path.join(localeDir, locale, 'LC_MESSAGES', 'messages.po'); var hasPo = fs.existsSync(fp); var po = hasPo ? fs.readFileSync(fp, {encoding: 'utf8'}) : null; var catalog = po ? gettextParser.po.parse(po).translations[''] : {}; return catalog; }; var makeMasterCatalog = function(localeDirs) { var catalogs = _.map(localeDirs, catalogDir); return _.reduce(catalogs, _.defaults); }; var catalog = makeMasterCatalog(localeDirs); return _.transform(catalog, function(acc, msgObject, msgKey) { var msgId = msgObject.msgid; var msg = (msgObject.msgstr && msgObject.msgstr[0]) || msgId; acc[msgId] = msg; }); }; var acceptedExtensions = [ '.handlebars', '.hbs', '.js' ]; var translatable = function(file) { var ext = path.extname(file); return _.include(acceptedExtensions, ext); }; var i18n = function(file, opts) { if(!translatable(file)) { return through2(); } var extName = path.extname(file); var catalog = getJSONCatalog(opts.locale, opts.localeDirs); var translator = getTranslator(catalog, opts, extName); return through2(translator); }; i18n.fast = function(fastOpts) { var catalog = getJSONCatalog(fastOpts.locale, fastOpts.localeDirs); return function(file, opts) { if(!translatable(file)) { return through2(); } var extName = path.extname(file); var mergedOpts = _.extend({}, opts, fastOpts); var translator = getTranslator(catalog, mergedOpts, extName); return through2(translator); }; }; module.exports = i18n;
define([ 'jquery', 'underscore', 'backbone', 'oroui/js/modal', 'oroui/js/mediator', 'orotranslation/js/translator', 'routing' ], function($, _, Backbone, modal, mediator, __, routing) { 'use strict'; /** * @extends oro.Modal */ var WidgetPickerDialog = modal.extend({ open: function() { Backbone.BootstrapModal.prototype.open.apply(this, arguments); var addWidgetControls = $('.add-widget-button'); var collapseControls = $('.dashboard-picker-collapse'); collapseControls.unbind('click', this.options.collapseCallback); collapseControls.bind('click', {}, this.options.collapseCallback); addWidgetControls.unbind('click', this.options.clickAddToDashboardCallback); addWidgetControls.bind('click', {controls: addWidgetControls}, this.options.clickAddToDashboardCallback); } }); /** * @export orodashboard/js/widget-picker * @class orodashboard.WidgetPicker */ return { /** * @property {integer} */ targetColumn: 0, /** * @property {Backbone.BootstrapModal} */ dialog: null, /** * @property {integer} */ dashboardId: null, /** * @param {integer} dashboardId */ init: function(dashboardId) { this.dashboardId = dashboardId; this.dialog = new WidgetPickerDialog({ content: $('#available-dashboard-widgets').html(), className: 'modal dashboard-widgets-wrapper', title: __('oro.dashboard.add_dashboard_widgets.title'), clickAddToDashboardCallback: _.bind(this._onClickAddToDashboard, this), collapseCallback: this._collapseDelegate }); $('.dashboard-widgets-add').bind('click', _.bind(this._onClickAddWidget, this)); }, /** * @private */ _collapseDelegate: function() { var $this = $(this); var container = $this.parents('.dashboard-widget-container'); $this.toggleClass('collapsed-state'); container.find('.dashboard-widgets-description').fadeToggle(); }, /** * @param {Event} event * @private */ _onClickAddToDashboard: function(event) { var $control = $(event.target); if ($control.hasClass('disabled')) { return; } var widgetContainer = $control.parents('.dashboard-widget-container'); var controls = event.data.controls; var self = this; this._startLoading(controls, widgetContainer); $.post( routing.generate('oro_api_post_dashboard_widget_add_widget'), { widgetName: $control.data('widget-name'), dashboardId: this.dashboardId, targetColumn: this.targetColumn }, function(response) { mediator.trigger('dashboard:widget:add', response); self._endLoading(controls, widgetContainer); }, 'json' ); }, /** * @param {jQuery} controls collection * @param {jQuery} widgetContainer current widget container * @private */ _startLoading: function(controls, widgetContainer) { controls.addClass('disabled'); var widgetButtonWrapper = widgetContainer.find('.dashboard-widgets-pick-wrapper'); widgetButtonWrapper.addClass('loading-content'); widgetButtonWrapper.find('.add-widget-button').hide(); }, /** * @param {jQuery} controls collection * @param {jQuery} widgetContainer current widget container * @private */ _endLoading: function(controls, widgetContainer) { controls.removeClass('disabled'); var widgetButtonWrapper = widgetContainer.find('.dashboard-widgets-pick-wrapper'); widgetButtonWrapper.removeClass('loading-content'); //fix case if modal window closed after press and before loading complete widgetButtonWrapper.find('.add-widget-button').css('display', 'inline-block'); var previous = widgetContainer.css('background-color'); var animateFinish = function() { animateFinish = function() { widgetContainer.css({backgroundColor: ''}); }; widgetContainer.animate({backgroundColor: previous}, animateFinish); }; widgetContainer.animate({backgroundColor: '#F5F55B'}, 50, animateFinish); }, /** * @param {Event} event * @private */ _onClickAddWidget: function(event) { event.preventDefault(); var columnIndex = $(event.target).closest('.dashboard-column').index(); this.targetColumn = (columnIndex === -1) ? 0 : columnIndex; this.dialog.open(); } }; });
export default Rx.Observable;
module.exports = exports = function(app) { require('./map_controller')(app); };
/* turn.js 4.1.0 | Copyright (c) 2012 Emmanuel Garcia | turnjs.com | turnjs.com/license.txt */ (function(f){function r(a,b){return a[0]==b[0]?!1:a.attr("page")?!0:a.parent()[0]?r(a.parent(),b):!1}function u(a){function b(a){this.name="TurnJsError";this.message=a}b.prototype=Error();b.prototype.constructor=b;return new b(a)}function t(a,b,d){return q&&d?" translate3d("+a+"px,"+b+"px, 0px) ":" translate("+a+"px, "+b+"px) "}function v(a,b){return q&&b?" scale3d("+a+", "+a+", 1) ":" scale("+a+") "}function h(a,b){return{x:a,y:b}}function m(a,b){return function(){return a.apply(b,arguments)}}var q, w={max:2,flipbook:null,easeFunction:"ease-in-out",duration:500,when:{}},j={init:function(a){var b=this,d=this.data(),a=f.extend({},w,a);if(!a.flipbook||!a.flipbook.turn("is"))throw u("options.$flipbook is required");q="WebKitCSSMatrix"in window||"MozPerspective"in document.body.style;if("function"!=typeof a.max){var e=a.max;a.max=function(){return e}}d.zoom={opts:a,axis:h(0,0),scrollPos:h(0,0),eventQueue:[],mouseupEvent:function(){return j._eMouseUp.apply(b,arguments)},eventTouchStart:m(j._eTouchStart, b),eventTouchMove:m(j._eTouchMove,b),eventTouchEnd:m(j._eTouchEnd,b),flipbookEvents:{zooming:m(j._eZoom,b),pressed:m(j._ePressed,b),released:m(j._eReleased,b),start:m(j._eStart,b),turning:m(j._eTurning,b),turned:m(j._eTurned,b),destroying:m(j._eDestroying,b)}};for(var c in a.when)Object.prototype.hasOwnProperty.call(a.when,c)&&this.bind("zoom."+c,a.when[c]);for(c in d.zoom.flipbookEvents)Object.prototype.hasOwnProperty.call(d.zoom.flipbookEvents,c)&&a.flipbook.bind(c,d.zoom.flipbookEvents[c]);this.css({position:"relative", overflow:"hidden"});f.isTouch?(a.flipbook.bind("touchstart",d.zoom.eventTouchStart).bind("touchmove",d.zoom.eventTouchMove).bind("touchend",d.zoom.eventTouchEnd),this.bind("touchstart",j._tap)):this.mousedown(j._mousedown).click(j._tap)},_tap:function(a){var b=f(this),d=b.data().zoom;!d.draggingCorner&&!d.dragging&&r(f(a.target),b)&&(j._addEvent.call(b,"tap",a),(a=j._eventSeq.call(b))&&b.trigger(a))},_addEvent:function(a,b){var d=this.data().zoom,e=(new Date).getTime();d.eventQueue.push({name:a,timestamp:e, event:b});10<d.eventQueue.length&&d.eventQueue.splice(0,1)},_eventSeq:function(){var a=this.data().zoom.eventQueue,b=a.length-1;if(0<b&&"tap"==a[b].name&&"tap"==a[b-1].name&&a[b].event.pageX==a[b-1].event.pageX&&a[b].event.pageY==a[b-1].event.pageY&&200>a[b].timestamp-a[b-1].timestamp&&50<a[b].timestamp-a[b-1].timestamp)return f.extend(a[b].event,{type:"zoom.doubleTap"});if("tap"==a[b].name)return f.extend(a[b].event,{type:"zoom.tap"})},_prepareZoom:function(){var a,b=0,d=this.data().zoom,e=1/this.zoom("value"); a=d.opts.flipbook;var c=a.turn("direction"),j=a.data(),l=a.offset(),i=this.offset(),g={height:a.height()},k=a.turn("view");"double"==a.turn("display")&&a.data().opts.autoCenter?k[0]?k[1]?(g.width=a.width(),a=h(l.left-i.left,l.top-i.top)):(g.width=a.width()/2,b="ltr"==c?0:g.width,a=h("ltr"==c?l.left-i.left:l.left-i.left+g.width,l.top-i.top)):(g.width=a.width()/2,b="ltr"==c?g.width:0,a=h("ltr"==c?l.left-i.left+g.width:l.left-i.left,l.top-i.top)):(g.width=a.width(),a=h(l.left-i.left,l.top-i.top));d.zoomer|| (d.zoomer=f("<div />",{"class":"zoomer",css:{overflow:"hidden",position:"absolute",zIndex:"1000000"}}).mousedown(function(){return!1}).appendTo(this));d.zoomer.css({top:a.y,left:a.x,width:g.width,height:g.height});c=k.join(",");if(c!=d.zoomerView){d.zoomerView=c;d.zoomer.find("*").remove();for(c=0;c<k.length;c++)if(k[c]){var i=j.pageObjs[k[c]].offset(),m=f(j.pageObjs[k[c]]);m.clone().transform("").css({width:m.width()*e,height:m.height()*e,position:"absolute",display:"",top:(i.top-l.top)*e,left:(i.left- l.left-b)*e}).appendTo(d.zoomer)}}return{pos:a,size:g}},value:function(){return this.data().zoom.opts.flipbook.turn("zoom")},zoomIn:function(a){var b=this,d=this.data().zoom,e=d.opts.flipbook,c=d.opts.max();e.offset();var s=this.offset();if(d.zoomIn)return this;e.turn("stop");var l=f.Event("zoom.change");this.trigger(l,[c]);if(l.isDefaultPrevented())return this;var i=j._prepareZoom.call(this),g=i.pos,k=h(i.size.width/2,i.size.height/2),l=f.cssPrefix(),m=f.cssTransitionEnd(),q=e.data().opts.autoCenter; d.scale=c;e.data().noCenter=!0;a="undefined"!=typeof a?"x"in a&&"y"in a?h(a.x-g.x,a.y-g.y):f.isTouch?h(a.originalEvent.touches[0].pageX-g.x-s.left,a.originalEvent.touches[0].pageY-g.y-s.top):h(a.pageX-g.x-s.left,a.pageY-g.y-s.top):h(k.x,k.y);if(0>a.x||0>a.y||a.x>i.width||a.y>i.height)a.x=k.x,a.y=k.y;var n=h((a.x-k.x)*c+k.x,(a.y-k.y)*c+k.y),a=h(i.size.width*c>this.width()?a.x-n.x:0,i.size.height*c>this.height()?a.y-n.y:0),n=h(Math.abs(i.size.width*c-this.width()),Math.abs(i.size.height*c-this.height())), i=h(Math.min(0,i.size.width*c-this.width()),Math.min(0,i.size.height*c-this.height())),p=h(k.x*c-k.x-g.x-a.x,k.y*c-k.y-g.y-a.y);p.y>n.y?a.y=p.y-n.y+a.y:p.y<i.y&&(a.y=p.y-i.y+a.y);p.x>n.x?a.x=p.x-n.x+a.x:p.x<i.x&&(a.x=p.x-i.x+a.x);p=h(k.x*c-k.x-g.x-a.x,k.y*c-k.y-g.y-a.y);g={};g[l+"transition"]=l+"transform "+d.opts.easeFunction+" "+d.opts.duration+"ms";var r=function(){b.trigger("zoom.zoomIn");d.zoomIn=!0;d.flipPosition=h(e.css("left"),e.css("top"));e.turn("zoom",c).css({position:"absolute",margin:"", top:0,left:0});var a=e.offset();d.axis=h(a.left-s.left,a.top-s.top);if(q&&"double"==e.turn("display")&&("ltr"==e.turn("direction")&&!e.turn("view")[0]||"rtl"==e.turn("direction")&&!e.turn("view")[1]))d.axis.x+=e.width()/2;b.zoom("scroll",p);b.bind(f.mouseEvents.down,j._eMouseDown);b.bind(f.mouseEvents.move,j._eMouseMove);f(document).bind(f.mouseEvents.up,d.mouseupEvent);b.bind("mousewheel",j._eMouseWheel);setTimeout(function(){d.zoomer.hide();d.zoomer.remove();d.zoomer=null;d.zoomerView=null},50)}; d.zoomer.css(g).show();m?d.zoomer.bind(m,function(){f(this).unbind(m);r()}):setTimeout(r,d.opts.duration);d.zoomer.transform(t(a.x,a.y,!0)+v(c,!0));return this},zoomOut:function(a){var b,d=this,e=this.data().zoom,c=e.opts.flipbook,m=1/e.scale,l=f.cssPrefix(),i=f.cssTransitionEnd();b=this.offset();a="undefined"!=typeof a?a:e.opts.duration;if(e.zoomIn){var g=f.Event("zoom.change");this.trigger(g,[1]);if(g.isDefaultPrevented())return this;e.zoomIn=!1;e.scale=1;c.data().noCenter=!1;d.unbind(f.mouseEvents.down, j._eMouseDown);d.unbind(f.mouseEvents.move,j._eMouseMove);f(document).unbind(f.mouseEvents.up,e.mouseupEvent);d.unbind("mousewheel",j._eMouseWheel);g={};g[l+"transition"]=l+"transform "+e.opts.easeFunction+" "+a+"ms";c.css(g);var k=f("<div />",{css:{position:"relative",top:e.flipPosition.y,left:e.flipPosition.x,width:c.width()*m,height:c.height()*m,background:"blue"}}).appendTo(c.parent()),g=h(k.offset().left-b.left,k.offset().top-b.top);k.remove();var q=c.data().opts.autoCenter;q&&"double"==c.turn("display")&& (c.turn("view")[0]?c.turn("view")[1]||(g.x="ltr"==c.turn("direction")?g.x+k.width()/4:g.x-k.width()/4):g.x="ltr"==c.turn("direction")?g.x-k.width()/4:g.x+k.width()/4);var r=f.findPos(c[0]);b=h(-c.width()/2-r.left+k.width()/2+g.x+b.left,-c.height()/2-r.top+k.height()/2+g.y+b.top);var n=function(){c[0].style.removeProperty?(c[0].style.removeProperty(l+"transition"),c.transform(c.turn("options").acceleration?t(0,0,!0):"").turn("zoom",1),c[0].style.removeProperty("margin"),c.css({position:"relative", top:e.flipPosition.y,left:e.flipPosition.x})):c.transform("none").turn("zoom",1).css({margin:"",top:e.flipPosition.y,left:e.flipPosition.x,position:"relative"});q&&c.turn("center");d.trigger("zoom.zoomOut")};0===a?n():(i?c.bind(i,function(){f(this).unbind(i);n()}):setTimeout(n,a),c.transform(t(b.x,b.y,!0)+v(m,!0)));return this}},flipbookWidth:function(){var a=this.data().zoom.opts.flipbook,b=a.turn("view");return"double"==a.turn("display")&&(!b[0]||!b[1])?a.width()/2:a.width()},scroll:function(a, b,d){var e=this.data().zoom,c=e.opts.flipbook,j=this.zoom("flipbookWidth"),l=f.cssPrefix();if(q){var i={};i[l+"transition"]=d?l+"transform 200ms":"none";c.css(i);c.transform(t(-e.axis.x-a.x,-e.axis.y-a.y,!0))}else c.css({top:-e.axis.y-a.y,left:-e.axis.x-a.x});if(!b){var g,b=h(Math.min(0,(j-this.width())/2),Math.min(0,(c.height()-this.height())/2)),c=h(j>this.width()?j-this.width():(j-this.width())/2,c.height()>this.height()?c.height()-this.height():(c.height()-this.height())/2);a.y<b.y?(a.y=b.y,g= !0):a.y>c.y&&(a.y=c.y,g=!0);a.x<b.x?(a.x=b.x,g=!0):a.x>c.x&&(a.x=c.x,g=!0);g&&this.zoom("scroll",a,!0,!0)}e.scrollPos=h(a.x,a.y)},resize:function(){var a=this.data().zoom,b=a.opts.flipbook;if(1<this.zoom("value")){var d=b.offset(),e=this.offset();a.axis=h(d.left-e.left+(a.axis.x+a.scrollPos.x),d.top-e.top+(a.axis.y+a.scrollPos.y));"double"==b.turn("display")&&("ltr"==b.turn("direction")&&!b.turn("view")[0])&&(a.axis.x+=b.width()/2);this.zoom("scroll",a.scrollPos)}},_eZoom:function(){for(var a=this.data().zoom, b=a.opts.flipbook,d=b.turn("view"),e=0;e<d.length;e++)d[e]&&this.trigger("zoom.resize",[a.scale,d[e],b.data().pageObjs[d[e]]])},_eStart:function(a){1!=this.zoom("value")&&a.preventDefault()},_eTurning:function(a,b,d){var e=this,a=this.zoom("value"),c=this.data().zoom,b=c.opts.flipbook;c.page=b.turn("page");if(1!=a){for(c=0;c<d.length;c++)d[c]&&this.trigger("zoom.resize",[a,d[c],b.data().pageObjs[d[c]]]);setTimeout(function(){e.zoom("resize")},0)}},_eTurned:function(a,b){if(1!=this.zoom("value")){var d= this.data().zoom,e=d.opts.flipbook;b>d.page?this.zoom("scroll",h(0,d.scrollPos.y),!1,!0):b<d.page&&this.zoom("scroll",h(e.width(),d.scrollPos.y),!1,!0)}},_ePressed:function(){f(this).data().zoom.draggingCorner=!0},_eReleased:function(){var a=f(this).data().zoom;setTimeout(function(){a.draggingCorner=!1},1)},_eMouseDown:function(a){f(this).data().zoom.draggingCur=f.isTouch?h(a.originalEvent.touches[0].pageX,a.originalEvent.touches[0].pageY):h(a.pageX,a.pageY);return!1},_eMouseMove:function(a){var b= f(this).data().zoom;if(b.draggingCur){b.dragging=!0;var a=f.isTouch?h(a.originalEvent.touches[0].pageX,a.originalEvent.touches[0].pageY):h(a.pageX,a.pageY),d=h(a.x-b.draggingCur.x,a.y-b.draggingCur.y);f(this).zoom("scroll",h(b.scrollPos.x-d.x,b.scrollPos.y-d.y),!0);b.draggingCur=a;return!1}},_eMouseUp:function(){var a=f(this).data().zoom;a.dragging&&f(this).zoom("scroll",a.scrollPos);a.draggingCur=null;setTimeout(function(){a.dragging=!1},1)},_eMouseWheel:function(a,b,d,e){a=f(this).data().zoom;d= h(a.scrollPos.x+10*d,a.scrollPos.y-10*e);f(this).zoom("scroll",d,!1,!0)},_eTouchStart:function(a){var b=f(this).data().zoom,a=h(a.originalEvent.touches[0].pageX,a.originalEvent.touches[0].pageY);b.touch={};b.touch.initial=a;b.touch.last=a;b.touch.timestamp=(new Date).getTime();b.touch.speed=h(0,0)},_eTouchMove:function(a){var b=f(this).data().zoom,d=f(this).zoom("value"),e=b.opts.flipbook,c=(new Date).getTime(),a=h(a.originalEvent.touches[0].pageX,a.originalEvent.touches[0].pageY);b.touch&&(1==d&& !e.data().mouseAction)&&(b.touch.motion=h(a.x-b.touch.last.x,a.y-b.touch.last.y),b.touch.speed.x=0===b.touch.speed.x?b.touch.motion.x/(c-b.touch.timestamp):(b.touch.speed.x+b.touch.motion.x/(c-b.touch.timestamp))/2,b.touch.last=a,b.touch.timestamp=c)},_eTouchEnd:function(){var a=f(this).data().zoom;if(a.touch&&1==f(this).zoom("value")){var b=Math.abs(a.touch.initial.y-a.touch.last.y);50>b&&(-1>a.touch.speed.x||-100>a.touch.last.x-a.touch.initial.x)?this.trigger("zoom.swipeLeft"):50>b&&(1<a.touch.speed.x|| 100<a.touch.last.x-a.touch.initial.x)&&this.trigger("zoom.swipeRight")}},_eDestroying:function(){var a=this,b=this.data().zoom,d=b.opts.flipbook;this.zoom("zoomOut",0);f.each("tap doubleTap resize zoomIn zoomOut swipeLeft swipeRight".split(" "),function(b,d){a.unbind("zoom."+d)});for(var e in b.flipbookEvents)Object.prototype.hasOwnProperty.call(b.flipbookEvents,e)&&d.unbind(e,b.flipbookEvents[e]);d.unbind("touchstart",b.eventTouchStart).unbind("touchmove",b.eventTouchMove).unbind("touchend",b.eventTouchEnd); this.unbind("touchstart",j._tap).unbind("click",j._tap);b=null;this.data().zoom=null}};f.extend(f.fn,{zoom:function(){var a=arguments;if(!a[0]||"object"==typeof a[0])return j.init.apply(f(this[0]),a);if(j[a[0]])return j[a[0]].apply(f(this[0]),Array.prototype.slice.call(a,1));throw u(a[0]+" is not a method");}})})(jQuery);
var searchData= [ ['renderer',['Renderer',['../class_c_m_u462_1_1_renderer.html',1,'CMU462']]] ];
'use strict'; var childProcess = require('child_process'); function run(args, cb) { childProcess.execFile('df', args, function (err, stdout) { if (err) { cb(err); return; } cb(null, stdout.trim().split('\n').slice(1).map(function (el) { var cl = el.split(/\s+(?=[\d\/])/); return { filesystem: cl[0], size: parseInt(cl[1], 10) * 1024, used: parseInt(cl[2], 10) * 1024, available: parseInt(cl[3], 10) * 1024, capacity: parseInt(cl[4], 10) / 100, mountpoint: cl[5] }; })); }); }; var df = module.exports = function (cb) { run(['-kP'], cb); }; df.fs = function (name, cb) { if (typeof name !== 'string') { throw new Error('name required'); } run(['-kP'], function (err, data) { if (err) { cb(err); return; } var ret; data.forEach(function (el) { if (el.filesystem === name) { ret = el; } }); cb(null, ret); }); }; df.file = function (file, cb) { if (typeof file !== 'string') { throw new Error('file required'); } run(['-kP', file], function (err, data) { if (err) { cb(err); return; } cb(null, data[0]); }); };
var config = require('../javascripts/config'); var utils= require('../javascripts/utils'); var sqlite3 = require('sqlite3').verbose(); module.exports = { db: new sqlite3.Database(config.tsdbPath), warps: [], users: [], groups: [], initialize: function () { this.loadGroups(); this.loadWarps(); }, loadGroups: function () { this.db.all("SELECT * FROM GroupList", function (err, rows) { if (err) { console.log(err); return; } this.groups = []; for (var i = 0; i < rows.length; i++) { this.groups[rows[i].Usergroup] = rows[i]; } }); }, loadWarps: function () { this.db.all("SELECT * FROM Warps", function (err, rows) { if (err) { console.log(err); return; } this.warps = []; for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (!row.Private || row.Private == 0 || !row.WarpName) { this.warps[i] = { name: row.WarpName, x: row.X, y: row.Y }; } } }); }, getUser: function (name, callback) { this.db.all("SELECT * FROM Users WHERE Username = @0", name, function (err, rows) { if (err || rows.length <= 0) callback(null); else callback(rows[0]); }); }, setUser: function (uid, user) { this.users[uid] = user; } }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "m21.68 9.71-3.72 8.19c-.23.49-.96.33-.96-.21V11h-1.5c-.28 0-.5-.22-.5-.5v-6c0-.28.22-.5.5-.5h5.76c.35 0 .6.36.46.69L20 9h1.22c.37 0 .61.38.46.71zM15 13v7H4c-1.1 0-2-.9-2-2v-3c0-1.1.9-2 2-2h11zm-8.75 3.5c0-.41-.34-.75-.75-.75s-.75.34-.75.75.34.75.75.75.75-.34.75-.75zM13 4v7H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2h9zM6.25 7.5c0-.41-.34-.75-.75-.75s-.75.34-.75.75.34.75.75.75.75-.34.75-.75z" }), 'DynamicFormRounded');
var isIE6 = ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1)); var isIE7 = ((navigator.userAgent.indexOf("MSIE 7.") != -1) && (navigator.userAgent.indexOf("Opera") == -1)); var isChrome = ((navigator.userAgent.indexOf("Chrome") != -1)); var isSafari = ((navigator.userAgent.indexOf("Safari") != -1)); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; } jQuery.fn.centerHoriz = function () { this.css("position","absolute"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; } jQuery.fn.centerHorizHalo = function () { this.css("position","absolute"); this.css("left", (($(window).width() - 1468) / 2) + $(window).scrollLeft() + "px"); return this; } jQuery.fn.heightTot = function () { this.css("height", ($(window).height() + "px")); return this; } jQuery.fn.widthTot = function () { this.css("width", ($(window).width() + "px")); return this; } jQuery.fn.heightTot2 = function () { this.css("height", ($("#containerGlobal").height() + "px")); $(".block_hallo ").css("position","absolute"); return this; } function doCenterHoris(tothing) { tothing.centerHoriz(); }; function doWidthHoris(tothing) { tothing.widthTot(); }; function doHeightTot(tothing) { tothing.heightTot(); }; function doHeightTot2(tothing) { tothing.heightTot2(); }; $(document).ready(function(){ $(".clickable").click( function() { window.location = $(this).attr("url"); }).hover( function() { $(this).addClass('overblock'); }, function() { $(this).removeClass('overblock'); } ); //background for input on hover anf focus $("input").hover(function(){ $(this).addClass("write_hover"); },function(){ $(this).removeClass("write_hover"); }); $("input").click(function(){ $(this).addClass("write"); }); $("input").blur(function(){ $(this).removeClass("write"); }); $("input").focus(function(){ $(this).addClass("write"); }); $("textarea").hover(function(){ $(this).addClass("write_hover"); },function(){ $(this).removeClass("write_hover"); }); $("textarea").click(function(){ $(this).addClass("write"); }); $("textarea").blur(function(){ $(this).removeClass("write"); }); $("textarea").focus(function(){ $(this).addClass("write"); }); $("#contact_form #name").addClass("write"); $("#contact_form #name").focus(); $(".blockLink").hover(function(){ $(this).addClass("blockHover"); $(".blockHover").click(function(){ var link= $(this).attr('rel'); window.location.replace(link); }); },function(){ $(this).removeClass("blockHover"); $(".blockHover").unbind(); }); $(".back-dyn").widthTot(); $("#root2").widthTot(); $("#root").centerHoriz(); $("#imgBg").centerHoriz(); $("#root2").centerHoriz(); $("#infosHome").centerHoriz(); $(".news_last").centerHoriz(); $("#halo").centerHorizHalo(); $("#halo").heightTot2(); $(".back-dyn").heightTot(); $(window).resize(function() { doWidthHoris($("#root2"));doWidthHoris($(".back-dyn"));doCenterHoris($("#halo"));doCenterHoris($("#imgBg"));doCenterHoris($("#root"));doCenterHoris($("#root2"));doCenterHoris($(".news_last"));doHeightTot($(".back-dyn")) }); /**************************/ /*****nav langue **********/ $('form#langForm a').click ( function() { var inputTarget=$(this).attr("data-inputtarget"); var reponse=$(this).attr("data-send"); var inputlabel=$(this).text(); $('input#'+inputTarget).attr("value", reponse); $('input#'+inputTarget).addClass("subhover"); $('#langForm').submit(); return false; } ) });
/* * Start looseleaf server */ // Create express server and exports for spark like modules var ll = require('looseleaf').init(__dirname); // For other controll modules exports = ll.app; // Only listen when run on $ node app.js if (!module.parent) { ll.start(); }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Track Schema */ var TrackSchema = new Schema({ date: { type: Date }, sheikh: { type: String, trim: true }, surah: { type: String, trim: true }, prayerLocation: { type: String, trim: true }, filePath: { type: String, trim: true } }, { collection: 'track' }); /** * Statics */ TrackSchema.statics.load = function(id, cb) { console.log(id); this.findOne({ _id: id }).populate().exec(cb); }; mongoose.model('Track', TrackSchema);
module.exports = { schema: { id: { type: 'serial', key: true }, song_id: String, title: String, artist: String, album: String, cover: String, mp3: String, ogg: String, lyric: String, update_at: { type: 'date', time: true, null: true } } }
'use strict'; var colors = require('colors/safe'); var util = require('util'); // logLevel = -1: log nothing // logLevel = 0: error, success and info // logLevel = 1: log // logLevel = 2: debug var logger = function logger() { var options = { logLevel: 0 }; var output = function(parameters) { var message = new Date().toLocaleTimeString() + ' - '; message += util.format.apply(console, parameters); return message; }; this.init = function(logLevel) { options.logLevel = logLevel; }; this.error = function() { if (options.logLevel >= 0) { console.error(colors.red(output(arguments))); } }; this.success = function() { if (options.logLevel >= 0) { console.log(colors.green(output(arguments))); } }; this.info = function() { if (options.logLevel >= 0) { console.log(output(arguments)); } }; this.log = function() { if (options.logLevel >= 1) { console.log(colors.yellow(output(arguments))); } }; this.debug = function() { if (options.logLevel >= 2) { console.log(output(arguments)); } }; }; logger.instance = null; logger.getInstance = function() { if (this.instance === null) { this.instance = new logger(); } return this.instance; }; module.exports = logger.getInstance();
/*! * CanJS - 2.1.4 * http://canjs.us/ * Copyright (c) 2014 Bitovi * Fri, 21 Nov 2014 22:25:48 GMT * Licensed MIT * Includes: CanJS default build * Download from: http://canjs.us/ */ steal("can/util", "can/map", "can/map/bubble.js",function (can, Map, bubble) { // Helpers for `observable` lists. var splice = [].splice, // test if splice works correctly spliceRemovesProps = (function () { // IE's splice doesn't remove properties var obj = { 0: "a", length: 1 }; splice.call(obj, 0, 1); return !obj[0]; })(); /** * @add can.List */ var list = Map.extend( /** * @static */ { /** * @property {can.Map} can.List.Map * * @description Specify the Map type used to make objects added to this list observable. * * @option {can.Map} When objects are added to a can.List, those objects are * converted into can.Map instances. For example: * * var list = new can.List(); * list.push({name: "Justin"}); * * var map = list.attr(0); * map.attr("name") //-> "Justin" * * By changing [can.List.Map], you can specify a different type of Map instance to * create. For example: * * var User = can.Map.extend({ * fullName: function(){ * return this.attr("first")+" "+this.attr("last") * } * }); * * User.List = can.List.extend({ * Map: User * }, {}); * * var list = new User.List(); * list.push({first: "Justin", last: "Meyer"}); * * var user = list.attr(0); * user.fullName() //-> "Justin Meyer" * * * */ Map: Map /** * @function can.Map.extend * * @signature `can.List.extend([name,] [staticProperties,] instanceProperties)` * * Creates a new extended constructor function. Learn more at [can.Construct.extend]. * * @param {String} [name] If provided, adds the extened List constructor function * to the window at the given name. * * @param {Object} [staticProperties] Properties and methods * directly on the constructor function. The most common property to set is [can.List.Map]. * * @param {Object} [instanceProperties] Properties and methods on instances of this list type. * * @body * * ## Use * * */ }, /** * @prototype */ { setup: function (instances, options) { this.length = 0; can.cid(this, ".map"); this._init = 1; this._computedBindings = {}; this._setupComputes(); instances = instances || []; var teardownMapping; if (can.isDeferred(instances)) { this.replace(instances); } else { teardownMapping = instances.length && can.Map.helpers.addToMap(instances, this); this.push.apply(this, can.makeArray(instances || [])); } if (teardownMapping) { teardownMapping(); } // this change needs to be ignored this.bind('change', can.proxy(this._changes, this)); can.simpleExtend(this, options); delete this._init; }, _triggerChange: function (attr, how, newVal, oldVal) { Map.prototype._triggerChange.apply(this, arguments); // `batchTrigger` direct add and remove events... var index = +attr; // Make sure this is not nested and not an expando if (!~attr.indexOf('.') && !isNaN(index)) { if (how === 'add') { can.batch.trigger(this, how, [newVal, index]); can.batch.trigger(this, 'length', [this.length]); } else if (how === 'remove') { can.batch.trigger(this, how, [oldVal, index]); can.batch.trigger(this, 'length', [this.length]); } else { can.batch.trigger(this, how, [newVal, index]); } } }, __get: function (attr) { if (attr) { if (this[attr] && this[attr].isComputed && can.isFunction(this.constructor.prototype[attr])) { return this[attr](); } else { return this[attr]; } } else { return this; } }, ___set: function (attr, val) { this[attr] = val; if (+attr >= this.length) { this.length = (+attr + 1); } }, _remove: function(prop, current) { // if removing an expando property if(isNaN(+prop)) { delete this[prop]; this._triggerChange(prop, "remove", undefined, current); } else { this.splice(prop, 1); } }, _each: function (callback) { var data = this.__get(); for (var i = 0; i < data.length; i++) { callback(data[i], i); } }, // Returns the serialized form of this list. /** * @hide * Returns the serialized form of this list. */ serialize: function () { return Map.helpers.serialize(this, 'serialize', []); }, /** * @function can.List.prototype.each each * @description Call a function on each element of a List. * @signature `list.each( callback(item, index) )` * * `each` iterates through the Map, calling a function * for each element. * * @param {function(*, Number)} callback the function to call for each element * The value and index of each element will be passed as the first and second * arguments, respectively, to the callback. If the callback returns false, * the loop will stop. * * @return {can.List} this List, for chaining * * @body * @codestart * var i = 0; * new can.Map([1, 10, 100]).each(function(element, index) { * i += element; * }); * * i; // 111 * * i = 0; * new can.Map([1, 10, 100]).each(function(element, index) { * i += element; * if(index >= 1) { * return false; * } * }); * * i; // 11 * @codeend */ // /** * @function can.List.prototype.splice splice * @description Insert and remove elements from a List. * @signature `list.splice(index[, howMany[, ...newElements]])` * @param {Number} index where to start removing or inserting elements * * @param {Number} [howMany] the number of elements to remove * If _howMany_ is not provided, `splice` will remove all elements from `index` to the end of the List. * * @param {*} newElements elements to insert into the List * * @return {Array} the elements removed by `splice` * * @body * `splice` lets you remove elements from and insert elements into a List. * * This example demonstrates how to do surgery on a list of numbers: * * @codestart * var list = new can.List([0, 1, 2, 3]); * * // starting at index 2, remove one element and insert 'Alice' and 'Bob': * list.splice(2, 1, 'Alice', 'Bob'); * list.attr(); // [0, 1, 'Alice', 'Bob', 3] * @codeend * * ## Events * * `splice` causes the List it's called on to emit _change_ events, * _add_ events, _remove_ events, and _length_ events. If there are * any elements to remove, a _change_ event, a _remove_ event, and a * _length_ event will be fired. If there are any elements to insert, a * separate _change_ event, an _add_ event, and a separate _length_ event * will be fired. * * This slightly-modified version of the above example should help * make it clear how `splice` causes events to be emitted: * * @codestart * var list = new can.List(['a', 'b', 'c', 'd']); * list.bind('change', function(ev, attr, how, newVals, oldVals) { * console.log('change: ' + attr + ', ' + how + ', ' + newVals + ', ' + oldVals); * }); * list.bind('add', function(ev, newVals, where) { * console.log('add: ' + newVals + ', ' + where); * }); * list.bind('remove', function(ev, oldVals, where) { * console.log('remove: ' + oldVals + ', ' + where); * }); * list.bind('length', function(ev, length) { * console.log('length: ' + length + ', ' + this.attr()); * }); * * // starting at index 2, remove one element and insert 'Alice' and 'Bob': * list.splice(2, 1, 'Alice', 'Bob'); // change: 2, 'remove', undefined, ['c'] * // remove: ['c'], 2 * // length: 5, ['a', 'b', 'Alice', 'Bob', 'd'] * // change: 2, 'add', ['Alice', 'Bob'], ['c'] * // add: ['Alice', 'Bob'], 2 * // length: 5, ['a', 'b', 'Alice', 'Bob', 'd'] * @codeend * * More information about binding to these events can be found under [can.List.attr attr]. */ splice: function (index, howMany) { var args = can.makeArray(arguments), added =[], i, len; // converting the arguments to the right type for (i = 2, len = args.length; i < len; i++) { args[i] = this.__type(args[i], i); added.push(args[i]); } // default howMany if not provided if (howMany === undefined) { howMany = args[1] = this.length - index; } var removed = splice.apply(this, args); // delete properties for browsers who's splice sucks (old ie) if (!spliceRemovesProps) { for (i = this.length; i < removed.length + this.length; i++) { delete this[i]; } } can.batch.start(); if (howMany > 0) { // tears down bubbling bubble.removeMany(this, removed); this._triggerChange("" + index, "remove", undefined, removed); } if (args.length > 2) { // make added items bubble to this list for (i = 0, len = added.length; i < len; i++) { bubble.set(this, i, added[i]); } this._triggerChange("" + index, "add", added, removed); } can.batch.stop(); return removed; }, /** * @description Get or set elements in a List. * @function can.List.prototype.attr attr * * @signature `list.attr()` * * Gets an array of all the elements in this `can.List`. * * @return {Array} An array with all the elements in this List. * * @signature `list.attr(index)` * * Reads an element from this `can.List`. * * @param {Number} index The element to read. * @return {*} The value at _index_. * * @signature `list.attr(index, value)` * * Assigns _value_ to the index _index_ on this `can.List`, expanding the list if necessary. * * @param {Number} index The element to set. * @param {*} value The value to assign at _index_. * @return {can.List} This list, for chaining. * * @signature `list.attr(elements[, replaceCompletely])` * * Merges the members of _elements_ into this List, replacing each from the beginning in order. If * _elements_ is longer than the current List, the current List will be expanded. If _elements_ * is shorter than the current List, the extra existing members are not affected (unless * _replaceCompletely_ is `true`). To remove elements without replacing them, use `[can.Map::removeAttr removeAttr]`. * * @param {Array} elements An array of elements to merge in. * * @param {bool} [replaceCompletely=false] whether to completely replace the elements of List * If _replaceCompletely_ is `true` and _elements_ is shorter than the List, the existing * extra members of the List will be removed. * * @return {can.List} This list, for chaining. * * @body * * * ## Use * * `attr` gets or sets elements on the `can.List` it's called on. Here's a tour through * how all of its forms work: * * var people = new can.List(['Alex', 'Bill']); * * // set an element: * people.attr(0, 'Adam'); * * // get an element: * people.attr(0); // 'Adam' * people[0]; // 'Adam' * * // get all elements: * people.attr(); // ['Adam', 'Bill'] * * // extend the array: * people.attr(4, 'Charlie'); * people.attr(); // ['Adam', 'Bill', undefined, undefined, 'Charlie'] * * // merge the elements: * people.attr(['Alice', 'Bob', 'Eve']); * people.attr(); // ['Alice', 'Bob', 'Eve', undefined, 'Charlie'] * * ## Deep properties * * `attr` can also set and read deep properties. All you have to do is specify * the property name as you normally would if you weren't using `attr`. * * @codestart * var people = new can.List([{name: 'Alex'}, {name: 'Bob'}]); * * // set a property: * people.attr('0.name', 'Alice'); * * // get a property: * people.attr('0.name'); // 'Alice' * people[0].attr('name'); // 'Alice' * * // get all properties: * people.attr(); // [{name: 'Alice'}, {name: 'Bob'}] * @codeend * * The discussion of deep properties under `[can.Map.prototype.attr]` may also * be enlightening. * * ## Events * * `can.List`s emit five types of events in response to changes. They are: * * - the _change_ event fires on every change to a List. * - the _set_ event is fired when an element is set. * - the _add_ event is fired when an element is added to the List. * - the _remove_ event is fired when an element is removed from the List. * - the _length_ event is fired when the length of the List changes. * * ### The _change_ event * * The first event that is fired is the _change_ event. The _change_ event is useful * if you want to react to all changes on an List. * * @codestart * var list = new can.List([]); * list.bind('change', function(ev, index, how, newVal, oldVal) { * console.log('Something changed.'); * }); * @codeend * * The parameters of the event handler for the _change_ event are: * * - _ev_ The event object. * - _index_ Where the change took place. * - _how_ Whether elements were added, removed, or set. * Possible values are `'add'`, `'remove'`, or `'set'`. * - _newVal_ The elements affected after the change * _newVal_ will be a single value when an index is set, an Array when elements * were added, and `undefined` if elements were removed. * - _oldVal_ The elements affected before the change. * _newVal_ will be a single value when an index is set, an Array when elements * were removed, and `undefined` if elements were added. * * Here is a concrete tour through the _change_ event handler's arguments: * * @codestart * var list = new can.List(); * list.bind('change', function(ev, index, how, newVal, oldVal) { * console.log(ev + ', ' + index + ', ' + how + ', ' + newVal + ', ' + oldVal); * }); * * list.attr(['Alexis', 'Bill']); // [object Object], 0, add, ['Alexis', 'Bill'], undefined * list.attr(2, 'Eve'); // [object Object], 2, add, Eve, undefined * list.attr(0, 'Adam'); // [object Object], 0, set, Adam, Alexis * list.attr(['Alice', 'Bob']); // [object Object], 0, set, Alice, Adam * // [object Object], 1, set, Bob, Bill * list.removeAttr(1); // [object Object], 1, remove, undefined, Bob * @codeend * * ### The _set_ event * * _set_ events are fired when an element at an index that already exists in the List is * modified. Actions can cause _set_ events to fire never also cause _length_ events * to fire (although some functions, such as `[can.List.prototype.splice splice]` * may cause unrelated sets of events to fire after being batched). * * The parameters of the event handler for the _set_ event are: * * - _ev_ The event object. * - _newVal_ The new value of the element. * - _index_ where the set took place. * * Here is a concrete tour through the _set_ event handler's arguments: * * @codestart * var list = new can.List(); * list.bind('set', function(ev, newVal, index) { * console.log(newVal + ', ' + index); * }); * * list.attr(['Alexis', 'Bill']); * list.attr(2, 'Eve'); * list.attr(0, 'Adam'); // Adam, 0 * list.attr(['Alice', 'Bob']); // Alice, 0 * // Bob, 1 * list.removeAttr(1); * @codeend * * ### The _add_ event * * _add_ events are fired when elements are added or inserted * into the List. * * The parameters of the event handler for the _add_ event are: * * - _ev_ The event object. * - _newElements_ The new elements. * If more than one element is added, _newElements_ will be an array. * Otherwise, it is simply the new element itself. * - _index_ Where the add or insert took place. * * Here is a concrete tour through the _add_ event handler's arguments: * * @codestart * var list = new can.List(); * list.bind('add', function(ev, newElements, index) { * console.log(newElements + ', ' + index); * }); * * list.attr(['Alexis', 'Bill']); // ['Alexis', 'Bill'], 0 * list.attr(2, 'Eve'); // Eve, 2 * list.attr(0, 'Adam'); * list.attr(['Alice', 'Bob']); * * list.removeAttr(1); * @codeend * * ### The _remove_ event * * _remove_ events are fired when elements are removed from the list. * * The parameters of the event handler for the _remove_ event are: * * - _ev_ The event object. * - _removedElements_ The removed elements. * If more than one element was removed, _removedElements_ will be an array. * Otherwise, it is simply the element itself. * - _index_ Where the removal took place. * * Here is a concrete tour through the _remove_ event handler's arguments: * * @codestart * var list = new can.List(); * list.bind('remove', function(ev, removedElements, index) { * console.log(removedElements + ', ' + index); * }); * * list.attr(['Alexis', 'Bill']); * list.attr(2, 'Eve'); * list.attr(0, 'Adam'); * list.attr(['Alice', 'Bob']); * * list.removeAttr(1); // Bob, 1 * @codeend * * ### The _length_ event * * _length_ events are fired whenever the list changes. * * The parameters of the event handler for the _length_ event are: * * - _ev_ The event object. * - _length_ The current length of the list. * If events were batched when the _length_ event was triggered, _length_ * will have the length of the list when `stopBatch` was called. Because * of this, you may recieve multiple _length_ events with the same * _length_ parameter. * * Here is a concrete tour through the _length_ event handler's arguments: * * @codestart * var list = new can.List(); * list.bind('length', function(ev, length) { * console.log(length); * }); * * list.attr(['Alexis', 'Bill']); // 2 * list.attr(2, 'Eve'); // 3 * list.attr(0, 'Adam'); * list.attr(['Alice', 'Bob']); * * list.removeAttr(1); // 2 * @codeend */ _attrs: function (items, remove) { if (items === undefined) { return Map.helpers.serialize(this, 'attr', []); } // Create a copy. items = can.makeArray(items); can.batch.start(); this._updateAttrs(items, remove); can.batch.stop(); }, _updateAttrs: function (items, remove) { var len = Math.min(items.length, this.length); for (var prop = 0; prop < len; prop++) { var curVal = this[prop], newVal = items[prop]; if (Map.helpers.isObservable(curVal) && Map.helpers.canMakeObserve(newVal)) { curVal.attr(newVal, remove); //changed from a coercion to an explicit } else if (curVal !== newVal) { this._set(prop, newVal); } else { } } if (items.length > this.length) { // Add in the remaining props. this.push.apply(this, items.slice(this.length)); } else if (items.length < this.length && remove) { this.splice(items.length); } } }), // Converts to an `array` of arguments. getArgs = function (args) { return args[0] && can.isArray(args[0]) ? args[0] : can.makeArray(args); }; // Create `push`, `pop`, `shift`, and `unshift` can.each({ /** * @function can.List.prototype.push push * @description Add elements to the end of a list. * @signature `list.push(...elements)` * * `push` adds elements onto the end of a List.] * * @param {*} elements the elements to add to the List * * @return {Number} the new length of the List * * @body * `push` is fairly straightforward: * * @codestart * var list = new can.List(['Alice']); * * list.push('Bob', 'Eve'); * list.attr(); // ['Alice', 'Bob', 'Eve'] * @codeend * * If you have an array you want to concatenate to the end * of the List, you can use `apply`: * * @codestart * var names = ['Bob', 'Eve'], * list = new can.List(['Alice']); * * list.push.apply(list, names); * list.attr(); // ['Alice', 'Bob', 'Eve'] * @codeend * * ## Events * * `push` causes _change_, _add_, and _length_ events to be fired. * * ## See also * * `push` has a counterpart in [can.List::pop pop], or you may be * looking for [can.List::unshift unshift] and its counterpart [can.List::shift shift]. */ push: "length", /** * @function can.List.prototype.unshift unshift * @description Add elements to the beginning of a List. * @signature `list.unshift(...elements)` * * `unshift` adds elements onto the beginning of a List. * * @param {*} elements the elements to add to the List * * @return {Number} the new length of the List * * @body * `unshift` adds elements to the front of the list in bulk in the order specified: * * @codestart * var list = new can.List(['Alice']); * * list.unshift('Bob', 'Eve'); * list.attr(); // ['Bob', 'Eve', 'Alice'] * @codeend * * If you have an array you want to concatenate to the beginning * of the List, you can use `apply`: * * @codestart * var names = ['Bob', 'Eve'], * list = new can.List(['Alice']); * * list.push.apply(list, names); * list.attr(); // ['Bob', 'Eve', 'Alice'] * @codeend * * ## Events * * `unshift` causes _change_, _add_, and _length_ events to be fired. * * ## See also * * `unshift` has a counterpart in [can.List::shift shift], or you may be * looking for [can.List::push push] and its counterpart [can.List::pop pop]. */ unshift: 0 }, // Adds a method // `name` - The method name. // `where` - Where items in the `array` should be added. function (where, name) { var orig = [][name]; list.prototype[name] = function () { // Get the items being added. var args = [], // Where we are going to add items. len = where ? this.length : 0, i = arguments.length, res, val; // Go through and convert anything to an `map` that needs to be converted. while (i--) { val = arguments[i]; args[i] = bubble.set(this, i, this.__type(val, i) ); } // Call the original method. res = orig.apply(this, args); if (!this.comparator || args.length) { this._triggerChange("" + len, "add", args, undefined); } return res; }; }); can.each({ /** * @function can.List.prototype.pop pop * @description Remove an element from the end of a List. * @signature `list.pop()` * * `push` removes an element from the end of a List. * * @return {*} the element just popped off the List, or `undefined` if the List was empty * * @body * `pop` is the opposite action from `[can.List.push push]`: * * @codestart * var list = new can.List(['Alice']); * * list.push('Bob', 'Eve'); * list.attr(); // ['Alice', 'Bob', 'Eve'] * * list.pop(); // 'Eve' * list.pop(); // 'Bob' * list.pop(); // 'Alice' * list.pop(); // undefined * @codeend * * ## Events * * `pop` causes _change_, _remove_, and _length_ events to be fired if the List is not empty * when it is called. * * ## See also * * `pop` has its counterpart in [can.List::push push], or you may be * looking for [can.List::unshift unshift] and its counterpart [can.List::shift shift]. */ pop: "length", /** * @function can.List.prototype.shift shift * @description Remove en element from the front of a list. * @signature `list.shift()` * * `shift` removes an element from the beginning of a List. * * @return {*} the element just shifted off the List, or `undefined` if the List is empty * * @body * `shift` is the opposite action from `[can.List::unshift unshift]`: * * @codestart * var list = new can.List(['Alice']); * * list.unshift('Bob', 'Eve'); * list.attr(); // ['Bob', 'Eve', 'Alice'] * * list.shift(); // 'Bob' * list.shift(); // 'Eve' * list.shift(); // 'Alice' * list.shift(); // undefined * @codeend * * ## Events * * `pop` causes _change_, _remove_, and _length_ events to be fired if the List is not empty * when it is called. * * ## See also * * `shift` has a counterpart in [can.List::unshift unshift], or you may be * looking for [can.List::push push] and its counterpart [can.List::pop pop]. */ shift: 0 }, // Creates a `remove` type method function (where, name) { list.prototype[name] = function () { var args = getArgs(arguments), len = where && this.length ? this.length - 1 : 0; var res = [][name].apply(this, args); // Create a change where the args are // `len` - Where these items were removed. // `remove` - Items removed. // `undefined` - The new values (there are none). // `res` - The old, removed values (should these be unbound). this._triggerChange("" + len, "remove", undefined, [res]); if (res && res.unbind) { bubble.remove(this, res); } return res; }; }); can.extend(list.prototype, { /** * @function can.List.prototype.indexOf indexOf * @description Look for an item in a List. * @signature `list.indexOf(item)` * * `indexOf` finds the position of a given item in the List. * * @param {*} item the item to find * * @return {Number} the position of the item in the List, or -1 if the item is not found. * * @body * @codestart * var list = new can.List(['Alice', 'Bob', 'Eve']); * list.indexOf('Alice'); // 0 * list.indexOf('Charlie'); // -1 * @codeend * * It is trivial to make a `contains`-type function using `indexOf`: * * @codestart * function(list, item) { * return list.indexOf(item) >= 0; * } * @codeend */ indexOf: function (item, fromIndex) { this.attr('length'); return can.inArray(item, this, fromIndex); }, /** * @function can.List.prototype.join join * @description Join a List's elements into a string. * @signature `list.join(separator)` * * `join` turns a List into a string by inserting _separator_ between the string representations * of all the elements of the List. * * @param {String} separator the string to seperate elements with * * @return {String} the joined string * * @body * @codestart * var list = new can.List(['Alice', 'Bob', 'Eve']); * list.join(', '); // 'Alice, Bob, Eve' * * var beatles = new can.List(['John', 'Paul', 'Ringo', 'George']); * beatles.join('&'); // 'John&Paul&Ringo&George' * @codeend */ join: function () { return [].join.apply(this.attr(), arguments); }, /** * @function can.List.prototype.reverse reverse * @description Reverse the order of a List. * @signature `list.reverse()` * * `reverse` reverses the elements of the List in place. * * @return {can.List} the List, for chaining * * @body * @codestart * var list = new can.List(['Alice', 'Bob', 'Eve']); * var reversedList = list.reverse(); * * reversedList.attr(); // ['Eve', 'Bob', 'Alice']; * list === reversedList; // true * @codeend */ reverse: function() { var list = can.makeArray([].reverse.call(this)); this.replace(list); }, /** * @function can.List.prototype.slice slice * @description Make a copy of a part of a List. * @signature `list.slice([start[, end]])` * * `slice` creates a copy of a portion of the List. * * @param {Number} [start=0] the index to start copying from * * @param {Number} [end] the first index not to include in the copy * If _end_ is not supplied, `slice` will copy until the end of the list. * * @return {can.List} a new `can.List` with the extracted elements * * @body * @codestart * var list = new can.List(['Alice', 'Bob', 'Charlie', 'Daniel', 'Eve']); * var newList = list.slice(1, 4); * newList.attr(); // ['Bob', 'Charlie', 'Daniel'] * @codeend * * `slice` is the simplest way to copy a List: * * @codestart * var list = new can.List(['Alice', 'Bob', 'Eve']); * var copy = list.slice(); * * copy.attr(); // ['Alice', 'Bob', 'Eve'] * list === copy; // false * @codeend */ slice: function () { var temp = Array.prototype.slice.apply(this, arguments); return new this.constructor(temp); }, /** * @function can.List.prototype.concat concat * @description Merge many collections together into a List. * @signature `list.concat(...args)` * @param {Array|can.List|*} args Any number of arrays, Lists, or values to add in * For each parameter given, if it is an Array or a List, each of its elements will be added to * the end of the concatenated List. Otherwise, the parameter itself will be added. * * @body * `concat` makes a new List with the elements of the List followed by the elements of the parameters. * * @codestart * var list = new can.List(); * var newList = list.concat( * 'Alice', * ['Bob', 'Charlie']), * new can.List(['Daniel', 'Eve']), * {f: 'Francis'} * ); * newList.attr(); // ['Alice', 'Bob', 'Charlie', 'Daniel', 'Eve', {f: 'Francis'}] * @codeend */ concat: function () { var args = []; can.each(can.makeArray(arguments), function (arg, i) { args[i] = arg instanceof can.List ? arg.serialize() : arg; }); return new this.constructor(Array.prototype.concat.apply(this.serialize(), args)); }, /** * @function can.List.prototype.forEach forEach * @description Call a function for each element of a List. * @signature `list.forEach(callback[, thisArg])` * @param {function(element, index, list)} callback a function to call with each element of the List * The three parameters that _callback_ gets passed are _element_, the element at _index_, _index_ the * current element of the list, and _list_ the List the elements are coming from. * @param {Object} [thisArg] the object to use as `this` inside the callback * * @body * `forEach` calls a callback for each element in the List. * * @codestart * var list = new can.List([1, 2, 3]); * list.forEach(function(element, index, list) { * list.attr(index, element * element); * }); * list.attr(); // [1, 4, 9] * @codeend */ forEach: function (cb, thisarg) { return can.each(this, cb, thisarg || this); }, /** * @function can.List.prototype.replace replace * @description Replace all the elements of a List. * @signature `list.replace(collection)` * @param {Array|can.List|can.Deferred} collection the collection of new elements to use * If a [can.Deferred] is passed, it must resolve to an `Array` or `can.List`. * The elements of the list are not actually removed until the Deferred resolves. * * @body * `replace` replaces all the elements of this List with new ones. * * `replace` is especially useful when `can.List`s are live-bound into `[can.Control]`s, * and you intend to populate them with the results of a `[can.Model]` call: * * @codestart * can.Control({ * init: function() { * this.list = new Todo.List(); * // live-bind the list into the DOM * this.element.html(can.view('list.mustache', this.list)); * // when this AJAX call returns, the live-bound DOM will be updated * this.list.replace(Todo.findAll()); * } * }); * @codeend * * Learn more about [can.Model.List making Lists of models]. * * ## Events * * A major difference between `replace` and `attr(newElements, true)` is that `replace` always emits * an _add_ event and a _remove_ event, whereas `attr` will cause _set_ events along with an _add_ or _remove_ * event if needed. Corresponding _change_ and _length_ events will be fired as well. * * The differences in the events fired by `attr` and `replace` are demonstrated concretely by this example: * @codestart * var attrList = new can.List(['Alexis', 'Bill']); * attrList.bind('change', function(ev, index, how, newVals, oldVals) { * console.log(index + ', ' + how + ', ' + newVals + ', ' + oldVals); * }); * * var replaceList = new can.List(['Alexis', 'Bill']); * replaceList.bind('change', function(ev, index, how, newVals, oldVals) { * console.log(index + ', ' + how + ', ' + newVals + ', ' + oldVals); * }); * * attrList.attr(['Adam', 'Ben'], true); // 0, set, Adam, Alexis * // 1, set, Ben, Bill * replaceList.replace(['Adam', 'Ben']); // 0, remove, undefined, ['Alexis', 'Bill'] * // 0, add, undefined, ['Adam', 'Ben'] * * attrList.attr(['Amber'], true); // 0, set, Amber, Adam * // 1, remove, undefined, Ben * replaceList.replace(['Amber']); // 0, remove, undefined, ['Adam', 'Ben'] * // 0, add, Amber, ['Adam', 'Ben'] * * attrList.attr(['Alice', 'Bob', 'Eve'], true); // 0, set, Alice, Amber * // 1, add, ['Bob', 'Eve'], undefined * replaceList.replace(['Alice', 'Bob', 'Eve']); // 0, remove, undefined, Amber * // 0, add, ['Alice', 'Bob', 'Eve'], Amber * @codeend */ replace: function (newList) { if (can.isDeferred(newList)) { newList.then(can.proxy(this.replace, this)); } else { this.splice.apply(this, [0, this.length].concat(can.makeArray(newList || []))); } return this; }, filter: function (callback, thisArg) { var filteredList = new can.List(), self = this, filtered; this.each(function(item, index, list){ filtered = callback.call( thisArg | self, item, index, self); if(filtered){ filteredList.push(item); } }); return filteredList; } }); can.List = Map.List = list; return can.List; });
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule RelayStoreTypes * * @format */ 'use strict';
define(['./toInteger'], function(toInteger) { /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } return after; });
// // Stub out `require` in rhino // function require(arg) { return less[arg.split('/')[1]]; }; // ecma-5.js // // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson // dantman Daniel Friesen // // Array // if (!Array.isArray) { Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]" || (obj instanceof Array); }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function(block, thisObject) { var len = this.length >>> 0; for (var i = 0; i < len; i++) { if (i in this) { block.call(thisObject, this[i], i, this); } } }; } if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp*/) { var len = this.length >>> 0; var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { res[i] = fun.call(thisp, this[i], i, this); } } return res; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (block /*, thisp */) { var values = []; var thisp = arguments[1]; for (var i = 0; i < this.length; i++) { if (block.call(thisp, this[i])) { values.push(this[i]); } } return values; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function(fun /*, initial*/) { var len = this.length >>> 0; var i = 0; // no value to return if no initial value and an empty array if (len === 0 && arguments.length === 1) throw new TypeError(); if (arguments.length >= 2) { var rv = arguments[1]; } else { do { if (i in this) { rv = this[i++]; break; } // if array contains no values, no initial value to return if (++i >= len) throw new TypeError(); } while (true); } for (; i < len; i++) { if (i in this) { rv = fun.call(null, rv, this[i], i, this); } } return rv; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (value /*, fromIndex */ ) { var length = this.length; var i = arguments[1] || 0; if (!length) return -1; if (i >= length) return -1; if (i < 0) i += length; for (; i < length; i++) { if (!Object.prototype.hasOwnProperty.call(this, i)) { continue } if (value === this[i]) return i; } return -1; }; } // // Object // if (!Object.keys) { Object.keys = function (object) { var keys = []; for (var name in object) { if (Object.prototype.hasOwnProperty.call(object, name)) { keys.push(name); } } return keys; }; } // // String // if (!String.prototype.trim) { String.prototype.trim = function () { return String(this).replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }; } var less, tree; if (typeof environment === "object" && ({}).toString.call(environment) === "[object Environment]") { // Rhino // Details on how to detect Rhino: https://github.com/ringo/ringojs/issues/88 if (typeof(window) === 'undefined') { less = {} } else { less = window.less = {} } tree = less.tree = {}; less.mode = 'rhino'; } else if (typeof(window) === 'undefined') { // Node.js less = exports, tree = require('./tree'); less.mode = 'node'; } else { // Browser if (typeof(window.less) === 'undefined') { window.less = {} } less = window.less, tree = window.less.tree = {}; less.mode = 'browser'; } // // less.js - parser // // A relatively straight-forward predictive parser. // There is no tokenization/lexing stage, the input is parsed // in one sweep. // // To make the parser fast enough to run in the browser, several // optimization had to be made: // // - Matching and slicing on a huge input is often cause of slowdowns. // The solution is to chunkify the input into smaller strings. // The chunks are stored in the `chunks` var, // `j` holds the current chunk index, and `current` holds // the index of the current chunk in relation to `input`. // This gives us an almost 4x speed-up. // // - In many cases, we don't need to match individual tokens; // for example, if a value doesn't hold any variables, operations // or dynamic references, the parser can effectively 'skip' it, // treating it as a literal. // An example would be '1px solid #000' - which evaluates to itself, // we don't need to know what the individual components are. // The drawback, of course is that you don't get the benefits of // syntax-checking on the CSS. This gives us a 50% speed-up in the parser, // and a smaller speed-up in the code-gen. // // // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. // // less.Parser = function Parser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk temp, // temporarily holds a chunk's state, for backtracking memo, // temporarily holds `i`, when backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // index of current chunk, in `input` parser; var that = this; // Top parser on an import tree must be sure there is one "env" // which will then be passed arround by reference. var env = env || { }; if (!env.contents) { env.contents={}; } // env.contents must be passed arround with top env // This function is called after all files // have been imported through `@import`. var finish = function () {}; var imports = this.imports = { paths: env && env.paths || [], // Search paths, when importing queue: [], // Files which haven't been imported yet files: {}, // Holds the imported parse trees contents: env.contents, // Holds the imported file contents mime: env && env.mime, // MIME type of .less files error: null, // Error in parsing/evaluating an import push: function (path, callback) { var that = this; this.queue.push(path); // // Import a file asynchronously // less.Parser.importer(path, this.paths, function (e, root) { that.queue.splice(that.queue.indexOf(path), 1); // Remove the path from the queue var imported = path in that.files; that.files[path] = root; // Store the root if (e && !that.error) { that.error = e } callback(e, root, imported); if (that.queue.length === 0) { finish(e) } // Call `finish` if we're done importing }, env); } }; function save() { temp = chunks[j], memo = i, current = i } function restore() { chunks[j] = temp, i = memo, current = i } function sync() { if (i > current) { chunks[j] = chunks[j].slice(i - current); current = i; } } function isWhitespace(c) { // Could change to \s? var code = c.charCodeAt(0); return code === 32 || code === 10 || code === 9; } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { var match, args, length, index, k; // // Non-terminal // if (tok instanceof Function) { return tok.call(parser.parsers); // // Terminal // // Either match a single character in the input, // or match a regexp in the current chunk (chunk[j]). // } else if (typeof(tok) === 'string') { match = input.charAt(i) === tok ? tok : null; length = 1; sync (); } else { sync (); if (match = tok.exec(chunks[j])) { length = match[0].length; } else { return null; } } // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. // if (match) { skipWhitespace(length); if(typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } } function skipWhitespace(length) { var oldi = i, oldj = j, endIndex = i + chunks[j].length, mem = i += length; while (i < endIndex) { if (! isWhitespace(input.charAt(i))) { break } i++; } chunks[j] = chunks[j].slice(length + (i - mem)); current = i; if (chunks[j].length === 0 && j < chunks.length - 1) { j++ } return oldi !== i || oldj !== j; } function expect(arg, msg) { var result = $(arg); if (! result) { error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'" : "unexpected token")); } else { return result; } } function error(msg, type) { throw { index: i, type: type || 'Syntax', message: msg }; } // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { if (tok.test(chunks[j])) { return true; } else { return false; } } } function getInput(e, env) { if (e.filename && env.filename && (e.filename !== env.filename)) { return parser.imports.contents[e.filename]; } else { return input; } } function getLocation(index, input) { for (var n = index, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ } return { line: typeof(index) === 'number' ? (input.slice(0, index).match(/\n/g) || "").length : null, column: column }; } function LessError(e, env) { var input = getInput(e, env), loc = getLocation(e.index, input), line = loc.line, col = loc.column, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = e.call && (getLocation(e.call, input).line + 1); this.callExtract = lines[getLocation(e.call, input).line]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } this.env = env = env || {}; // The optimization level dictates the thoroughness of the parser, // the lower the number, the less nodes it will create in the tree. // This could matter for debugging, or if you want to access // the individual nodes in the tree. this.optimization = ('optimization' in this.env) ? this.env.optimization : 1; this.env.filename = this.env.filename || null; // // The Parser // return parser = { imports: imports, // // Parse an input string into an abstract syntax tree, // call `callback` when done. // parse: function (str, callback) { var root, start, end, zone, line, lines, buff = [], c, error = null; i = j = current = furthest = 0; input = str.replace(/\r\n/g, '\n'); // Remove potential UTF Byte Order Mark input = input.replace(/^\uFEFF/, ''); // Split the input into chunks. chunks = (function (chunks) { var j = 0, skip = /(?:@\{[\w-]+\}|[^"'`\{\}\/\(\)\\])+/g, comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g, string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`]|\\.)*)`/g, level = 0, match, chunk = chunks[0], inParam; for (var i = 0, c, cc; i < input.length; i++) { skip.lastIndex = i; if (match = skip.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); } } c = input.charAt(i); comment.lastIndex = string.lastIndex = i; if (match = string.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); c = input.charAt(i); } } if (!inParam && c === '/') { cc = input.charAt(i + 1); if (cc === '/' || cc === '*') { if (match = comment.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); c = input.charAt(i); } } } } switch (c) { case '{': if (! inParam) { level ++; chunk.push(c); break } case '}': if (! inParam) { level --; chunk.push(c); chunks[++j] = chunk = []; break } case '(': if (! inParam) { inParam = true; chunk.push(c); break } case ')': if ( inParam) { inParam = false; chunk.push(c); break } default: chunk.push(c); } } if (level > 0) { error = new(LessError)({ index: i, type: 'Parse', message: "missing closing `}`", filename: env.filename }, env); } return chunks.map(function (c) { return c.join('') });; })([[]]); if (error) { return callback(error); } // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { root = new(tree.Ruleset)([], $(this.parsers.primary)); root.root = true; } catch (e) { return callback(new(LessError)(e, env)); } root.toCSS = (function (evaluate) { var line, lines, column; return function (options, variables) { var frames = [], importError; options = options || {}; // // Allows setting variables with a hash, so: // // `{ color: new(tree.Color)('#f01') }` will become: // // new(tree.Rule)('@color', // new(tree.Value)([ // new(tree.Expression)([ // new(tree.Color)('#f01') // ]) // ]) // ) // if (typeof(variables) === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables).map(function (k) { var value = variables[k]; if (! (value instanceof tree.Value)) { if (! (value instanceof tree.Expression)) { value = new(tree.Expression)([value]); } value = new(tree.Value)([value]); } return new(tree.Rule)('@' + k, value, false, 0); }); frames = [new(tree.Ruleset)(null, variables)]; } try { var css = evaluate.call(this, { frames: frames }) .toCSS([], { compress: options.compress || false }); } catch (e) { throw new(LessError)(e, env); } if ((importError = parser.imports.error)) { // Check if there was an error during importing if (importError instanceof LessError) throw importError; else throw new(LessError)(importError, env); } if (options.yuicompress && less.mode === 'node') { return require('./cssmin').compressor.cssmin(css); } else if (options.compress) { return css.replace(/(\s)+/g, "$1"); } else { return css; } }; })(root.eval); // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occured. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. if (i < input.length - 1) { i = furthest; lines = input.split('\n'); line = (input.slice(0, i).match(/\n/g) || "").length + 1; for (var n = i, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ } error = { type: "Parse", message: "Syntax Error on line " + line, index: i, filename: env.filename, line: line, column: column, extract: [ lines[line - 2], lines[line - 1], lines[line] ] }; } if (this.imports.queue.length > 0) { finish = function (e) { if (e) callback(e); else callback(null, root); }; } else { callback(error, root); } }, // // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // Here's some LESS code: // // .class { // color: #fff; // border: 1px solid #000; // width: @w + 4px; // > .child {...} // } // // And here's what the parse tree might look like: // // Ruleset (Selector '.class', [ // Rule ("color", Value ([Expression [Color #fff]])) // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) // Ruleset (Selector [Element '>', '.child'], [...]) // ]) // // In general, most rules will try to parse a token with the `$()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. // parsers: { // // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. // primary: function () { var node, root = []; while ((node = $(this.mixin.definition) || $(this.rule) || $(this.ruleset) || $(this.mixin.call) || $(this.comment) || $(this.directive)) || $(/^[\s\n]+/)) { node && root.push(node); } return root; }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function () { var comment; if (input.charAt(i) !== '/') return; if (input.charAt(i + 1) === '/') { return new(tree.Comment)($(/^\/\/.*/), true); } else if (comment = $(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) { return new(tree.Comment)(comment); } }, // // Entities are tokens which can be found inside an Expression // entities: { // // A string, which supports escaping " and ' // // "milky way" 'he\'s the one!' // quoted: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++, e = true } // Escaped strings if (input.charAt(j) !== '"' && input.charAt(j) !== "'") return; e && $('~'); if (str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/)) { return new(tree.Quoted)(str[0], str[1] || str[2], e); } }, // // A catch-all word, such as: // // black border-collapse // keyword: function () { var k; if (k = $(/^[_A-Za-z-][_A-Za-z0-9-]*/)) { if (tree.colors.hasOwnProperty(k)) { // detect named color return new(tree.Color)(tree.colors[k].slice(1)); } else { return new(tree.Keyword)(k); } } }, // // A function call // // rgb(255, 0, 255) // // We also try to catch IE's `alpha()`, but let the `alpha` parser // deal with the details. // // The arguments are parsed with the `entities.arguments` parser. // call: function () { var name, nameLC, args, alpha_ret, index = i; if (! (name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(chunks[j]))) return; name = name[1]; nameLC = name.toLowerCase(); if (nameLC === 'url') { return null } else { i += name.length } if (nameLC === 'alpha') { alpha_ret = $(this.alpha); if(typeof alpha_ret !== 'undefined') { return alpha_ret; } } $('('); // Parse the '(' and consume whitespace. args = $(this.entities.arguments); if (! $(')')) return; if (name) { return new(tree.Call)(name, args, index, env.filename) } }, arguments: function () { var args = [], arg; while (arg = $(this.entities.assignment) || $(this.expression)) { args.push(arg); if (! $(',')) { break } } return args; }, literal: function () { return $(this.entities.ratio) || $(this.entities.dimension) || $(this.entities.color) || $(this.entities.quoted); }, // Assignments are argument entities for calls. // They are present in ie filter properties as shown below. // // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) // assignment: function () { var key, value; if ((key = $(/^\w+(?=\s?=)/i)) && $('=') && (value = $(this.entity))) { return new(tree.Assignment)(key, value); } }, // // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. // url: function () { var value; if (input.charAt(i) !== 'u' || !$(/^url\(/)) return; value = $(this.entities.quoted) || $(this.entities.variable) || $(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ""; expect(')'); return new(tree.URL)((value.value != null || value instanceof tree.Variable) ? value : new(tree.Anonymous)(value), imports.paths); }, // // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. // variable: function () { var name, index = i; if (input.charAt(i) === '@' && (name = $(/^@@?[\w-]+/))) { return new(tree.Variable)(name, index, env.filename); } }, // A variable entity useing the protective {} e.g. @{var} variableCurly: function () { var name, curly, index = i; if (input.charAt(i) === '@' && (curly = $(/^@\{([\w-]+)\}/))) { return new(tree.Variable)("@" + curly[1], index, env.filename); } }, // // A Hexadecimal color // // #4F3C2F // // `rgb` and `hsl` colors are parsed through the `entities.call` parser. // color: function () { var rgb; if (input.charAt(i) === '#' && (rgb = $(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { return new(tree.Color)(rgb[1]); } }, // // A Dimension, that is, a number and a unit // // 0.5em 95% // dimension: function () { var value, c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) return; if (value = $(/^(-?\d*\.?\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn|dpi|dpcm|dppx|rem|vw|vh|vmin|vm|ch)?/)) { return new(tree.Dimension)(value[1], value[2]); } }, // // A Ratio // // 16/9 // ratio: function () { var value, c = input.charCodeAt(i); if (c > 57 || c < 48) return; if (value = $(/^(\d+\/\d+)/)) { return new(tree.Ratio)(value[1]); } }, // // JavaScript code to be evaluated // // `window.location.href` // javascript: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++, e = true } // Escaped strings if (input.charAt(j) !== '`') { return } e && $('~'); if (str = $(/^`([^`]*)`/)) { return new(tree.JavaScript)(str[1], i, e); } } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink: // variable: function () { var name; if (input.charAt(i) === '@' && (name = $(/^(@[\w-]+)\s*:/))) { return name[1] } }, // // A font size/line-height shorthand // // small/12px // // We need to peek first, or we'll match on keywords and dimensions // shorthand: function () { var a, b; if (! peek(/^[@\w.%-]+\/[@\w.-]+/)) return; save(); if ((a = $(this.entity)) && $('/') && (b = $(this.entity))) { return new(tree.Shorthand)(a, b); } restore(); }, // // Mixins // mixin: { // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // .rounded(4px, black); // .button; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // call: function () { var elements = [], e, c, args = [], arg, index = i, s = input.charAt(i), name, value, important = false; if (s !== '.' && s !== '#') { return } save(); // stop us absorbing part of an invalid selector while (e = $(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)) { elements.push(new(tree.Element)(c, e, i)); c = $('>'); } if ($('(')) { while (arg = $(this.expression)) { value = arg; name = null; // Variable if (arg.value.length == 1) { var val = arg.value[0]; if (val instanceof tree.Variable) { if ($(':')) { if (value = $(this.expression)) { name = val.name; } else { throw new(Error)("Expected value"); } } } } args.push({ name: name, value: value }); if (! $(',')) { break } } if (! $(')')) throw new(Error)("Expected )"); } if ($(this.important)) { important = true; } if (elements.length > 0 && ($(';') || peek('}'))) { return new(tree.mixin.Call)(elements, args, index, env.filename, important); } restore(); }, // // A Mixin definition, with a list of parameters // // .rounded (@radius: 2px, @color) { // ... // } // // Until we have a finer grained state-machine, we have to // do a look-ahead, to make sure we don't have a mixin call. // See the `rule` function for more information. // // We start by matching `.rounded (`, and then proceed on to // the argument list, which has optional default values. // We store the parameters in `params`, with a `value` key, // if there is a value, such as in the case of `@radius`. // // Once we've got our params list, and a closing `)`, we parse // the `{...}` block. // definition: function () { var name, params = [], match, ruleset, param, value, cond, variadic = false; if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') || peek(/^[^{]*(;|})/)) return; save(); if (match = $(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/)) { name = match[1]; do { if (input.charAt(i) === '.' && $(/^\.{3}/)) { variadic = true; break; } else if (param = $(this.entities.variable) || $(this.entities.literal) || $(this.entities.keyword)) { // Variable if (param instanceof tree.Variable) { if ($(':')) { value = expect(this.expression, 'expected expression'); params.push({ name: param.name, value: value }); } else if ($(/^\.{3}/)) { params.push({ name: param.name, variadic: true }); variadic = true; break; } else { params.push({ name: param.name }); } } else { params.push({ value: param }); } } else { break; } } while ($(',')) // .mixincall("@{a}"); // looks a bit like a mixin definition.. so we have to be nice and restore if (!$(')')) { furthest = i; restore(); } if ($(/^when/)) { // Guard cond = expect(this.conditions, 'expected condition'); } ruleset = $(this.block); if (ruleset) { return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { restore(); } } } }, // // Entities are the smallest recognized token, // and can be found inside a rule's value. // entity: function () { return $(this.entities.literal) || $(this.entities.variable) || $(this.entities.url) || $(this.entities.call) || $(this.entities.keyword) || $(this.entities.javascript) || $(this.comment); }, // // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. // end: function () { return $(';') || peek('}'); }, // // IE's alpha function // // alpha(opacity=88) // alpha: function () { var value; if (! $(/^\(opacity=/i)) return; if (value = $(/^\d+/) || $(this.entities.variable)) { expect(')'); return new(tree.Alpha)(value); } }, // // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // element: function () { var e, t, c, v; c = $(this.combinator); e = $(/^(?:\d+\.\d+|\d+)%/) || $(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || $('*') || $('&') || $(this.attribute) || $(/^\([^)@]+\)/) || $(/^[\.#](?=@)/) || $(this.entities.variableCurly); if (! e) { if ($('(') && (v = ($(this.entities.variableCurly) || $(this.entities.variable))) && $(')')) { e = new(tree.Paren)(v); } } if (e) { return new(tree.Element)(c, e, i) } }, // // Combinators combine elements together, in a Selector. // // Because our parser isn't white-space sensitive, special care // has to be taken, when parsing the descendant combinator, ` `, // as it's an empty space. We have to check the previous character // in the input, to see if it's a ` ` character. More info on how // we deal with this in *combinator.js*. // combinator: function () { var match, c = input.charAt(i); if (c === '>' || c === '+' || c === '~') { i++; while (input.charAt(i).match(/\s/)) { i++ } return new(tree.Combinator)(c); } else if (input.charAt(i - 1).match(/\s/)) { return new(tree.Combinator)(" "); } else { return new(tree.Combinator)(null); } }, // // A CSS Selector // // .class > div + h1 // li a:hover // // Selectors are made out of one or more Elements, see above. // selector: function () { var sel, e, elements = [], c, match; // depreciated, will be removed soon if ($('(')) { sel = $(this.entity); expect(')'); return new(tree.Selector)([new(tree.Element)('', sel, i)]); } while (e = $(this.element)) { c = input.charAt(i); elements.push(e) if (c === '{' || c === '}' || c === ';' || c === ',') { break } } if (elements.length > 0) { return new(tree.Selector)(elements) } }, tag: function () { return $(/^[A-Za-z][A-Za-z-]*[0-9]?/) || $('*'); }, attribute: function () { var attr = '', key, val, op; if (! $('[')) return; if (key = $(/^[_A-Za-z0-9-]+/) || $(this.entities.quoted)) { if ((op = $(/^[|~*$^]?=/)) && (val = $(this.entities.quoted) || $(/^[\w-]+/))) { attr = [key, op, val.toCSS ? val.toCSS() : val].join(''); } else { attr = key } } if (! $(']')) return; if (attr) { return "[" + attr + "]" } }, // // The `block` rule is used by `ruleset` and `mixin.definition`. // It's a wrapper around the `primary` rule, with added `{}`. // block: function () { var content; if ($('{') && (content = $(this.primary)) && $('}')) { return content; } }, // // div, .class, body > p {...} // ruleset: function () { var selectors = [], s, rules, match; save(); while (s = $(this.selector)) { selectors.push(s); $(this.comment); if (! $(',')) { break } $(this.comment); } if (selectors.length > 0 && (rules = $(this.block))) { return new(tree.Ruleset)(selectors, rules, env.strictImports); } else { // Backtrack furthest = i; restore(); } }, rule: function () { var name, value, c = input.charAt(i), important, match; save(); if (c === '.' || c === '#' || c === '&') { return } if (name = $(this.variable) || $(this.property)) { if ((name.charAt(0) != '@') && (match = /^([^@+\/'"*`(;{}-]*);/.exec(chunks[j]))) { i += match[0].length - 1; value = new(tree.Anonymous)(match[1]); } else if (name === "font") { value = $(this.font); } else { value = $(this.value); } important = $(this.important); if (value && $(this.end)) { return new(tree.Rule)(name, value, important, memo); } else { furthest = i; restore(); } } }, // // An @import directive // // @import "lib"; // // Depending on our environemnt, importing is done differently: // In the browser, it's an XHR request, in Node, it would be a // file-system operation. The function used for importing is // stored in `import`, which we pass to the Import constructor. // "import": function () { var path, features, index = i; save(); var dir = $(/^@import(?:-(once))?\s+/); if (dir && (path = $(this.entities.quoted) || $(this.entities.url))) { features = $(this.mediaFeatures); if ($(';')) { return new(tree.Import)(path, imports, features, (dir[1] === 'once'), index); } } restore(); }, mediaFeature: function () { var e, p, nodes = []; do { if (e = $(this.entities.keyword)) { nodes.push(e); } else if ($('(')) { p = $(this.property); e = $(this.entity); if ($(')')) { if (p && e) { nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, i, true))); } else if (e) { nodes.push(new(tree.Paren)(e)); } else { return null; } } else { return null } } } while (e); if (nodes.length > 0) { return new(tree.Expression)(nodes); } }, mediaFeatures: function () { var e, features = []; do { if (e = $(this.mediaFeature)) { features.push(e); if (! $(',')) { break } } else if (e = $(this.entities.variable)) { features.push(e); if (! $(',')) { break } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules; if ($(/^@media/)) { features = $(this.mediaFeatures); if (rules = $(this.block)) { return new(tree.Media)(rules, features); } } }, // // A CSS Directive // // @charset "utf-8"; // directive: function () { var name, value, rules, identifier, e, nodes, nonVendorSpecificName, hasBlock, hasIdentifier; if (input.charAt(i) !== '@') return; if (value = $(this['import']) || $(this.media)) { return value; } save(); name = $(/^@[a-z-]+/); nonVendorSpecificName = name; if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1); } switch(nonVendorSpecificName) { case "@font-face": hasBlock = true; break; case "@viewport": case "@top-left": case "@top-left-corner": case "@top-center": case "@top-right": case "@top-right-corner": case "@bottom-left": case "@bottom-left-corner": case "@bottom-center": case "@bottom-right": case "@bottom-right-corner": case "@left-top": case "@left-middle": case "@left-bottom": case "@right-top": case "@right-middle": case "@right-bottom": hasBlock = true; break; case "@page": case "@document": case "@supports": case "@keyframes": hasBlock = true; hasIdentifier = true; break; } if (hasIdentifier) { name += " " + ($(/^[^{]+/) || '').trim(); } if (hasBlock) { if (rules = $(this.block)) { return new(tree.Directive)(name, rules); } } else { if ((value = $(this.entity)) && $(';')) { return new(tree.Directive)(name, value); } } restore(); }, font: function () { var value = [], expression = [], weight, shorthand, font, e; while (e = $(this.shorthand) || $(this.entity)) { expression.push(e); } value.push(new(tree.Expression)(expression)); if ($(',')) { while (e = $(this.expression)) { value.push(e); if (! $(',')) { break } } } return new(tree.Value)(value); }, // // A Value is a comma-delimited list of Expressions // // font-family: Baskerville, Georgia, serif; // // In a Rule, a Value represents everything after the `:`, // and before the `;`. // value: function () { var e, expressions = [], important; while (e = $(this.expression)) { expressions.push(e); if (! $(',')) { break } } if (expressions.length > 0) { return new(tree.Value)(expressions); } }, important: function () { if (input.charAt(i) === '!') { return $(/^! *important/); } }, sub: function () { var e; if ($('(') && (e = $(this.expression)) && $(')')) { return e; } }, multiplication: function () { var m, a, op, operation; if (m = $(this.operand)) { while (!peek(/^\/\*/) && (op = ($('/') || $('*'))) && (a = $(this.operand))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; } }, addition: function () { var m, a, op, operation; if (m = $(this.multiplication)) { while ((op = $(/^[-+]\s+/) || (!isWhitespace(input.charAt(i - 1)) && ($('+') || $('-')))) && (a = $(this.multiplication))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; } }, conditions: function () { var a, b, index = i, condition; if (a = $(this.condition)) { while ($(',') && (b = $(this.condition))) { condition = new(tree.Condition)('or', condition || a, b, index); } return condition || a; } }, condition: function () { var a, b, c, op, index = i, negate = false; if ($(/^not/)) { negate = true } expect('('); if (a = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { if (op = $(/^(?:>=|=<|[<=>])/)) { if (b = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { c = new(tree.Condition)(op, a, b, index, negate); } else { error('expected expression'); } } else { c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); } expect(')'); return $(/^and/) ? new(tree.Condition)('and', c, $(this.condition)) : c; } }, // // An operand is anything that can be part of an operation, // such as a Color, or a Variable // operand: function () { var negate, p = input.charAt(i + 1); if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $('-') } var o = $(this.sub) || $(this.entities.dimension) || $(this.entities.color) || $(this.entities.variable) || $(this.entities.call); return negate ? new(tree.Operation)('*', [new(tree.Dimension)(-1), o]) : o; }, // // Expressions either represent mathematical operations, // or white-space delimited Entities. // // 1px solid black // @var * 2 // expression: function () { var e, delim, entities = [], d; while (e = $(this.addition) || $(this.entity)) { entities.push(e); } if (entities.length > 0) { return new(tree.Expression)(entities); } }, property: function () { var name; if (name = $(/^(\*?-?[_a-z0-9-]+)\s*:/)) { return name[1]; } } } }; }; if (less.mode === 'browser' || less.mode === 'rhino') { // // Used by `@import` directives // less.Parser.importer = function (path, paths, callback, env) { if (!/^([a-z-]+:)?\//.test(path) && paths.length > 0) { path = paths[0] + path; } // We pass `true` as 3rd argument, to force the reload of the import. // This is so we can get the syntax tree as opposed to just the CSS output, // as we need this to evaluate the current stylesheet. // __ Now using the hack of passing a ref to top parser's content cache in the 1st arg. __ loadStyleSheet({ href: path, title: path, type: env.mime, contents: env.contents }, function (e) { if (e && typeof(env.errback) === "function") { env.errback.call(null, path, paths, callback, env); } else { callback.apply(null, arguments); } }, true); }; } (function (tree) { tree.functions = { rgb: function (r, g, b) { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var rgb = [r, g, b].map(function (c) { return number(c) }), a = number(a); return new(tree.Color)(rgb, a); }, hsl: function (h, s, l) { return this.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { h = (number(h) % 360) / 360; s = number(s); l = number(l); a = number(a); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; return this.rgba(hue(h + 1/3) * 255, hue(h) * 255, hue(h - 1/3) * 255, a); function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; else if (h * 2 < 1) return m2; else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6; else return m1; } }, hue: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().h)); }, saturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%'); }, lightness: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%'); }, red: function (color) { return new(tree.Dimension)(color.rgb[0]); }, green: function (color) { return new(tree.Dimension)(color.rgb[1]); }, blue: function (color) { return new(tree.Dimension)(color.rgb[2]); }, alpha: function (color) { return new(tree.Dimension)(color.toHSL().a); }, luma: function (color) { return new(tree.Dimension)(Math.round((0.2126 * (color.rgb[0]/255) + 0.7152 * (color.rgb[1]/255) + 0.0722 * (color.rgb[2]/255)) * color.alpha * 100), '%'); }, saturate: function (color, amount) { var hsl = color.toHSL(); hsl.s += amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, desaturate: function (color, amount) { var hsl = color.toHSL(); hsl.s -= amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, lighten: function (color, amount) { var hsl = color.toHSL(); hsl.l += amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, darken: function (color, amount) { var hsl = color.toHSL(); hsl.l -= amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, fadein: function (color, amount) { var hsl = color.toHSL(); hsl.a += amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fadeout: function (color, amount) { var hsl = color.toHSL(); hsl.a -= amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fade: function (color, amount) { var hsl = color.toHSL(); hsl.a = amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, spin: function (color, amount) { var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return hsla(hsl); }, // // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { if (!weight) { weight = new(tree.Dimension)(50); } var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new(tree.Color)(rgb, alpha); }, greyscale: function (color) { return this.desaturate(color, new(tree.Dimension)(100)); }, contrast: function (color, dark, light, threshold) { if (typeof light === 'undefined') { light = this.rgba(255, 255, 255, 1.0); } if (typeof dark === 'undefined') { dark = this.rgba(0, 0, 0, 1.0); } if (typeof threshold === 'undefined') { threshold = 0.43; } else { threshold = threshold.value; } if (((0.2126 * (color.rgb[0]/255) + 0.7152 * (color.rgb[1]/255) + 0.0722 * (color.rgb[2]/255)) * color.alpha) < threshold) { return light; } else { return dark; } }, e: function (str) { return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str); }, escape: function (str) { return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29")); }, '%': function (quoted /* arg, arg, ...*/) { var args = Array.prototype.slice.call(arguments, 1), str = quoted.value; for (var i = 0; i < args.length; i++) { str = str.replace(/%[sda]/i, function(token) { var value = token.match(/s/i) ? args[i].value : args[i].toCSS(); return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; }); } str = str.replace(/%%/g, '%'); return new(tree.Quoted)('"' + str + '"', str); }, round: function (n, f) { var fraction = typeof(f) === "undefined" ? 0 : f.value; if (n instanceof tree.Dimension) { return new(tree.Dimension)(number(n).toFixed(fraction), n.unit); } else if (typeof(n) === 'number') { return n.toFixed(fraction); } else { throw { type: "Argument", message: "argument must be a number" }; } }, ceil: function (n) { return this._math('ceil', n); }, floor: function (n) { return this._math('floor', n); }, _math: function (fn, n) { if (n instanceof tree.Dimension) { return new(tree.Dimension)(Math[fn](number(n)), n.unit); } else if (typeof(n) === 'number') { return Math[fn](n); } else { throw { type: "Argument", message: "argument must be a number" }; } }, argb: function (color) { return new(tree.Anonymous)(color.toARGB()); }, percentage: function (n) { return new(tree.Dimension)(n.value * 100, '%'); }, color: function (n) { if (n instanceof tree.Quoted) { return new(tree.Color)(n.value.slice(1)); } else { throw { type: "Argument", message: "argument must be a string" }; } }, iscolor: function (n) { return this._isa(n, tree.Color); }, isnumber: function (n) { return this._isa(n, tree.Dimension); }, isstring: function (n) { return this._isa(n, tree.Quoted); }, iskeyword: function (n) { return this._isa(n, tree.Keyword); }, isurl: function (n) { return this._isa(n, tree.URL); }, ispixel: function (n) { return (n instanceof tree.Dimension) && n.unit === 'px' ? tree.True : tree.False; }, ispercentage: function (n) { return (n instanceof tree.Dimension) && n.unit === '%' ? tree.True : tree.False; }, isem: function (n) { return (n instanceof tree.Dimension) && n.unit === 'em' ? tree.True : tree.False; }, _isa: function (n, Type) { return (n instanceof Type) ? tree.True : tree.False; }, /* Blending modes */ multiply: function(color1, color2) { var r = color1.rgb[0] * color2.rgb[0] / 255; var g = color1.rgb[1] * color2.rgb[1] / 255; var b = color1.rgb[2] * color2.rgb[2] / 255; return this.rgb(r, g, b); }, screen: function(color1, color2) { var r = 255 - (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255; var g = 255 - (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255; var b = 255 - (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255; return this.rgb(r, g, b); }, overlay: function(color1, color2) { var r = color1.rgb[0] < 128 ? 2 * color1.rgb[0] * color2.rgb[0] / 255 : 255 - 2 * (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255; var g = color1.rgb[1] < 128 ? 2 * color1.rgb[1] * color2.rgb[1] / 255 : 255 - 2 * (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255; var b = color1.rgb[2] < 128 ? 2 * color1.rgb[2] * color2.rgb[2] / 255 : 255 - 2 * (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255; return this.rgb(r, g, b); }, softlight: function(color1, color2) { var t = color2.rgb[0] * color1.rgb[0] / 255; var r = t + color1.rgb[0] * (255 - (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255 - t) / 255; t = color2.rgb[1] * color1.rgb[1] / 255; var g = t + color1.rgb[1] * (255 - (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255 - t) / 255; t = color2.rgb[2] * color1.rgb[2] / 255; var b = t + color1.rgb[2] * (255 - (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255 - t) / 255; return this.rgb(r, g, b); }, hardlight: function(color1, color2) { var r = color2.rgb[0] < 128 ? 2 * color2.rgb[0] * color1.rgb[0] / 255 : 255 - 2 * (255 - color2.rgb[0]) * (255 - color1.rgb[0]) / 255; var g = color2.rgb[1] < 128 ? 2 * color2.rgb[1] * color1.rgb[1] / 255 : 255 - 2 * (255 - color2.rgb[1]) * (255 - color1.rgb[1]) / 255; var b = color2.rgb[2] < 128 ? 2 * color2.rgb[2] * color1.rgb[2] / 255 : 255 - 2 * (255 - color2.rgb[2]) * (255 - color1.rgb[2]) / 255; return this.rgb(r, g, b); }, difference: function(color1, color2) { var r = Math.abs(color1.rgb[0] - color2.rgb[0]); var g = Math.abs(color1.rgb[1] - color2.rgb[1]); var b = Math.abs(color1.rgb[2] - color2.rgb[2]); return this.rgb(r, g, b); }, exclusion: function(color1, color2) { var r = color1.rgb[0] + color2.rgb[0] * (255 - color1.rgb[0] - color1.rgb[0]) / 255; var g = color1.rgb[1] + color2.rgb[1] * (255 - color1.rgb[1] - color1.rgb[1]) / 255; var b = color1.rgb[2] + color2.rgb[2] * (255 - color1.rgb[2] - color1.rgb[2]) / 255; return this.rgb(r, g, b); }, average: function(color1, color2) { var r = (color1.rgb[0] + color2.rgb[0]) / 2; var g = (color1.rgb[1] + color2.rgb[1]) / 2; var b = (color1.rgb[2] + color2.rgb[2]) / 2; return this.rgb(r, g, b); }, negation: function(color1, color2) { var r = 255 - Math.abs(255 - color2.rgb[0] - color1.rgb[0]); var g = 255 - Math.abs(255 - color2.rgb[1] - color1.rgb[1]); var b = 255 - Math.abs(255 - color2.rgb[2] - color1.rgb[2]); return this.rgb(r, g, b); } }; function hsla(hsla) { return tree.functions.hsla(hsla.h, hsla.s, hsla.l, hsla.a); } function number(n) { if (n instanceof tree.Dimension) { return parseFloat(n.unit == '%' ? n.value / 100 : n.value); } else if (typeof(n) === 'number') { return n; } else { throw { error: "RuntimeError", message: "color functions take numbers as parameters" }; } } function clamp(val) { return Math.min(1, Math.max(0, val)); } })(require('./tree')); (function (tree) { tree.colors = { 'aliceblue':'#f0f8ff', 'antiquewhite':'#faebd7', 'aqua':'#00ffff', 'aquamarine':'#7fffd4', 'azure':'#f0ffff', 'beige':'#f5f5dc', 'bisque':'#ffe4c4', 'black':'#000000', 'blanchedalmond':'#ffebcd', 'blue':'#0000ff', 'blueviolet':'#8a2be2', 'brown':'#a52a2a', 'burlywood':'#deb887', 'cadetblue':'#5f9ea0', 'chartreuse':'#7fff00', 'chocolate':'#d2691e', 'coral':'#ff7f50', 'cornflowerblue':'#6495ed', 'cornsilk':'#fff8dc', 'crimson':'#dc143c', 'cyan':'#00ffff', 'darkblue':'#00008b', 'darkcyan':'#008b8b', 'darkgoldenrod':'#b8860b', 'darkgray':'#a9a9a9', 'darkgrey':'#a9a9a9', 'darkgreen':'#006400', 'darkkhaki':'#bdb76b', 'darkmagenta':'#8b008b', 'darkolivegreen':'#556b2f', 'darkorange':'#ff8c00', 'darkorchid':'#9932cc', 'darkred':'#8b0000', 'darksalmon':'#e9967a', 'darkseagreen':'#8fbc8f', 'darkslateblue':'#483d8b', 'darkslategray':'#2f4f4f', 'darkslategrey':'#2f4f4f', 'darkturquoise':'#00ced1', 'darkviolet':'#9400d3', 'deeppink':'#ff1493', 'deepskyblue':'#00bfff', 'dimgray':'#696969', 'dimgrey':'#696969', 'dodgerblue':'#1e90ff', 'firebrick':'#b22222', 'floralwhite':'#fffaf0', 'forestgreen':'#228b22', 'fuchsia':'#ff00ff', 'gainsboro':'#dcdcdc', 'ghostwhite':'#f8f8ff', 'gold':'#ffd700', 'goldenrod':'#daa520', 'gray':'#808080', 'grey':'#808080', 'green':'#008000', 'greenyellow':'#adff2f', 'honeydew':'#f0fff0', 'hotpink':'#ff69b4', 'indianred':'#cd5c5c', 'indigo':'#4b0082', 'ivory':'#fffff0', 'khaki':'#f0e68c', 'lavender':'#e6e6fa', 'lavenderblush':'#fff0f5', 'lawngreen':'#7cfc00', 'lemonchiffon':'#fffacd', 'lightblue':'#add8e6', 'lightcoral':'#f08080', 'lightcyan':'#e0ffff', 'lightgoldenrodyellow':'#fafad2', 'lightgray':'#d3d3d3', 'lightgrey':'#d3d3d3', 'lightgreen':'#90ee90', 'lightpink':'#ffb6c1', 'lightsalmon':'#ffa07a', 'lightseagreen':'#20b2aa', 'lightskyblue':'#87cefa', 'lightslategray':'#778899', 'lightslategrey':'#778899', 'lightsteelblue':'#b0c4de', 'lightyellow':'#ffffe0', 'lime':'#00ff00', 'limegreen':'#32cd32', 'linen':'#faf0e6', 'magenta':'#ff00ff', 'maroon':'#800000', 'mediumaquamarine':'#66cdaa', 'mediumblue':'#0000cd', 'mediumorchid':'#ba55d3', 'mediumpurple':'#9370d8', 'mediumseagreen':'#3cb371', 'mediumslateblue':'#7b68ee', 'mediumspringgreen':'#00fa9a', 'mediumturquoise':'#48d1cc', 'mediumvioletred':'#c71585', 'midnightblue':'#191970', 'mintcream':'#f5fffa', 'mistyrose':'#ffe4e1', 'moccasin':'#ffe4b5', 'navajowhite':'#ffdead', 'navy':'#000080', 'oldlace':'#fdf5e6', 'olive':'#808000', 'olivedrab':'#6b8e23', 'orange':'#ffa500', 'orangered':'#ff4500', 'orchid':'#da70d6', 'palegoldenrod':'#eee8aa', 'palegreen':'#98fb98', 'paleturquoise':'#afeeee', 'palevioletred':'#d87093', 'papayawhip':'#ffefd5', 'peachpuff':'#ffdab9', 'peru':'#cd853f', 'pink':'#ffc0cb', 'plum':'#dda0dd', 'powderblue':'#b0e0e6', 'purple':'#800080', 'red':'#ff0000', 'rosybrown':'#bc8f8f', 'royalblue':'#4169e1', 'saddlebrown':'#8b4513', 'salmon':'#fa8072', 'sandybrown':'#f4a460', 'seagreen':'#2e8b57', 'seashell':'#fff5ee', 'sienna':'#a0522d', 'silver':'#c0c0c0', 'skyblue':'#87ceeb', 'slateblue':'#6a5acd', 'slategray':'#708090', 'slategrey':'#708090', 'snow':'#fffafa', 'springgreen':'#00ff7f', 'steelblue':'#4682b4', 'tan':'#d2b48c', 'teal':'#008080', 'thistle':'#d8bfd8', 'tomato':'#ff6347', // 'transparent':'rgba(0,0,0,0)', 'turquoise':'#40e0d0', 'violet':'#ee82ee', 'wheat':'#f5deb3', 'white':'#ffffff', 'whitesmoke':'#f5f5f5', 'yellow':'#ffff00', 'yellowgreen':'#9acd32' }; })(require('./tree')); (function (tree) { tree.Alpha = function (val) { this.value = val; }; tree.Alpha.prototype = { toCSS: function () { return "alpha(opacity=" + (this.value.toCSS ? this.value.toCSS() : this.value) + ")"; }, eval: function (env) { if (this.value.eval) { this.value = this.value.eval(env) } return this; } }; })(require('../tree')); (function (tree) { tree.Anonymous = function (string) { this.value = string.value || string; }; tree.Anonymous.prototype = { toCSS: function () { return this.value; }, eval: function () { return this }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; } }; })(require('../tree')); (function (tree) { tree.Assignment = function (key, val) { this.key = key; this.value = val; }; tree.Assignment.prototype = { toCSS: function () { return this.key + '=' + (this.value.toCSS ? this.value.toCSS() : this.value); }, eval: function (env) { if (this.value.eval) { return new(tree.Assignment)(this.key, this.value.eval(env)); } return this; } }; })(require('../tree'));(function (tree) { // // A function call node. // tree.Call = function (name, args, index, filename) { this.name = name; this.args = args; this.index = index; this.filename = filename; }; tree.Call.prototype = { // // When evaluating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // or we simply print it out as it appeared originally [2]. // // The *functions.js* file contains the built-in functions. // // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. // eval: function (env) { var args = this.args.map(function (a) { return a.eval(env) }); if (this.name in tree.functions) { // 1. try { return tree.functions[this.name].apply(tree.functions, args); } catch (e) { throw { type: e.type || "Runtime", message: "error evaluating function `" + this.name + "`" + (e.message ? ': ' + e.message : ''), index: this.index, filename: this.filename }; } } else { // 2. return new(tree.Anonymous)(this.name + "(" + args.map(function (a) { return a.toCSS() }).join(', ') + ")"); } }, toCSS: function (env) { return this.eval(env).toCSS(); } }; })(require('../tree')); (function (tree) { // // RGB Colors - #ff0014, #eee // tree.Color = function (rgb, a) { // // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. // if (Array.isArray(rgb)) { this.rgb = rgb; } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } this.alpha = typeof(a) === 'number' ? a : 1; }; tree.Color.prototype = { eval: function () { return this }, // // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. // toCSS: function () { if (this.alpha < 1.0) { return "rgba(" + this.rgb.map(function (c) { return Math.round(c); }).concat(this.alpha).join(', ') + ")"; } else { return '#' + this.rgb.map(function (i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); } }, // // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. // operate: function (op, other) { var result = []; if (! (other instanceof tree.Color)) { other = other.toColor(); } for (var c = 0; c < 3; c++) { result[c] = tree.operate(op, this.rgb[c], other.rgb[c]); } return new(tree.Color)(result, this.alpha + other.alpha); }, toHSL: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; }, toARGB: function () { var argb = [Math.round(this.alpha * 255)].concat(this.rgb); return '#' + argb.map(function (i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); }, compare: function (x) { if (!x.rgb) { return -1; } return (x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha) ? 0 : -1; } }; })(require('../tree')); (function (tree) { tree.Comment = function (value, silent) { this.value = value; this.silent = !!silent; }; tree.Comment.prototype = { toCSS: function (env) { return env.compress ? '' : this.value; }, eval: function () { return this } }; })(require('../tree')); (function (tree) { tree.Condition = function (op, l, r, i, negate) { this.op = op.trim(); this.lvalue = l; this.rvalue = r; this.index = i; this.negate = negate; }; tree.Condition.prototype.eval = function (env) { var a = this.lvalue.eval(env), b = this.rvalue.eval(env); var i = this.index, result; var result = (function (op) { switch (op) { case 'and': return a && b; case 'or': return a || b; default: if (a.compare) { result = a.compare(b); } else if (b.compare) { result = b.compare(a); } else { throw { type: "Type", message: "Unable to perform comparison", index: i }; } switch (result) { case -1: return op === '<' || op === '=<'; case 0: return op === '=' || op === '>=' || op === '=<'; case 1: return op === '>' || op === '>='; } } })(this.op); return this.negate ? !result : result; }; })(require('../tree')); (function (tree) { // // A number with a unit // tree.Dimension = function (value, unit) { this.value = parseFloat(value); this.unit = unit || null; }; tree.Dimension.prototype = { eval: function () { return this }, toColor: function () { return new(tree.Color)([this.value, this.value, this.value]); }, toCSS: function () { var css = this.value + this.unit; return css; }, // In an operation between two Dimensions, // we default to the first Dimension's unit, // so `1px + 2em` will yield `3px`. // In the future, we could implement some unit // conversions such that `100cm + 10mm` would yield // `101cm`. operate: function (op, other) { return new(tree.Dimension) (tree.operate(op, this.value, other.value), this.unit || other.unit); }, // TODO: Perform unit conversion before comparing compare: function (other) { if (other instanceof tree.Dimension) { if (other.value > this.value) { return -1; } else if (other.value < this.value) { return 1; } else { return 0; } } else { return -1; } } }; })(require('../tree')); (function (tree) { tree.Directive = function (name, value) { this.name = name; if (Array.isArray(value)) { this.ruleset = new(tree.Ruleset)([], value); this.ruleset.allowImports = true; } else { this.value = value; } }; tree.Directive.prototype = { toCSS: function (ctx, env) { if (this.ruleset) { this.ruleset.root = true; return this.name + (env.compress ? '{' : ' {\n ') + this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n ') + (env.compress ? '}': '\n}\n'); } else { return this.name + ' ' + this.value.toCSS() + ';\n'; } }, eval: function (env) { var evaldDirective = this; if (this.ruleset) { env.frames.unshift(this); evaldDirective = new(tree.Directive)(this.name); evaldDirective.ruleset = this.ruleset.eval(env); env.frames.shift(); } return evaldDirective; }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) }, find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) } }; })(require('../tree')); (function (tree) { tree.Element = function (combinator, value, index) { this.combinator = combinator instanceof tree.Combinator ? combinator : new(tree.Combinator)(combinator); if (typeof(value) === 'string') { this.value = value.trim(); } else if (value) { this.value = value; } else { this.value = ""; } this.index = index; }; tree.Element.prototype.eval = function (env) { return new(tree.Element)(this.combinator, this.value.eval ? this.value.eval(env) : this.value, this.index); }; tree.Element.prototype.toCSS = function (env) { var value = (this.value.toCSS ? this.value.toCSS(env) : this.value); if (value == '' && this.combinator.value.charAt(0) == '&') { return ''; } else { return this.combinator.toCSS(env || {}) + value; } }; tree.Combinator = function (value) { if (value === ' ') { this.value = ' '; } else { this.value = value ? value.trim() : ""; } }; tree.Combinator.prototype.toCSS = function (env) { return { '' : '', ' ' : ' ', ':' : ' :', '+' : env.compress ? '+' : ' + ', '~' : env.compress ? '~' : ' ~ ', '>' : env.compress ? '>' : ' > ' }[this.value]; }; })(require('../tree')); (function (tree) { tree.Expression = function (value) { this.value = value }; tree.Expression.prototype = { eval: function (env) { if (this.value.length > 1) { return new(tree.Expression)(this.value.map(function (e) { return e.eval(env); })); } else if (this.value.length === 1) { return this.value[0].eval(env); } else { return this; } }, toCSS: function (env) { return this.value.map(function (e) { return e.toCSS ? e.toCSS(env) : ''; }).join(' '); } }; })(require('../tree')); (function (tree) { // // CSS @import node // // The general strategy here is that we don't want to wait // for the parsing to be completed, before we start importing // the file. That's because in the context of a browser, // most of the time will be spent waiting for the server to respond. // // On creation, we push the import path to our import queue, though // `import,push`, we also pass it a callback, which it'll call once // the file has been fetched, and parsed. // tree.Import = function (path, imports, features, once, index) { var that = this; this.once = once; this.index = index; this._path = path; this.features = features && new(tree.Value)(features); // The '.less' extension is optional if (path instanceof tree.Quoted) { this.path = /\.(le?|c)ss(\?.*)?$/.test(path.value) ? path.value : path.value + '.less'; } else { this.path = path.value.value || path.value; } this.css = /css(\?.*)?$/.test(this.path); // Only pre-compile .less files if (! this.css) { imports.push(this.path, function (e, root, imported) { if (e) { e.index = index } if (imported && that.once) that.skip = imported; that.root = root || new(tree.Ruleset)([], []); }); } }; // // The actual import node doesn't return anything, when converted to CSS. // The reason is that it's used at the evaluation stage, so that the rules // it imports can be treated like any other rules. // // In `eval`, we make sure all Import nodes get evaluated, recursively, so // we end up with a flat structure, which can easily be imported in the parent // ruleset. // tree.Import.prototype = { toCSS: function (env) { var features = this.features ? ' ' + this.features.toCSS(env) : ''; if (this.css) { return "@import " + this._path.toCSS() + features + ';\n'; } else { return ""; } }, eval: function (env) { var ruleset, features = this.features && this.features.eval(env); if (this.skip) return []; if (this.css) { return this; } else { ruleset = new(tree.Ruleset)([], this.root.rules.slice(0)); for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.Import) { Array.prototype .splice .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env))); } } return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules; } } }; })(require('../tree')); (function (tree) { tree.JavaScript = function (string, index, escaped) { this.escaped = escaped; this.expression = string; this.index = index; }; tree.JavaScript.prototype = { eval: function (env) { var result, that = this, context = {}; var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env)); }); try { expression = new(Function)('return (' + expression + ')'); } catch (e) { throw { message: "JavaScript evaluation error: `" + expression + "`" , index: this.index }; } for (var k in env.frames[0].variables()) { context[k.slice(1)] = { value: env.frames[0].variables()[k].value, toJS: function () { return this.value.eval(env).toCSS(); } }; } try { result = expression.call(context); } catch (e) { throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message + "'" , index: this.index }; } if (typeof(result) === 'string') { return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index); } else if (Array.isArray(result)) { return new(tree.Anonymous)(result.join(', ')); } else { return new(tree.Anonymous)(result); } } }; })(require('../tree')); (function (tree) { tree.Keyword = function (value) { this.value = value }; tree.Keyword.prototype = { eval: function () { return this }, toCSS: function () { return this.value }, compare: function (other) { if (other instanceof tree.Keyword) { return other.value === this.value ? 0 : 1; } else { return -1; } } }; tree.True = new(tree.Keyword)('true'); tree.False = new(tree.Keyword)('false'); })(require('../tree')); (function (tree) { tree.Media = function (value, features) { var selectors = this.emptySelectors(); this.features = new(tree.Value)(features); this.ruleset = new(tree.Ruleset)(selectors, value); this.ruleset.allowImports = true; }; tree.Media.prototype = { toCSS: function (ctx, env) { var features = this.features.toCSS(env); this.ruleset.root = (ctx.length === 0 || ctx[0].multiMedia); return '@media ' + features + (env.compress ? '{' : ' {\n ') + this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n ') + (env.compress ? '}': '\n}\n'); }, eval: function (env) { if (!env.mediaBlocks) { env.mediaBlocks = []; env.mediaPath = []; } var blockIndex = env.mediaBlocks.length; env.mediaPath.push(this); env.mediaBlocks.push(this); var media = new(tree.Media)([], []); media.features = this.features.eval(env); env.frames.unshift(this.ruleset); media.ruleset = this.ruleset.eval(env); env.frames.shift(); env.mediaBlocks[blockIndex] = media; env.mediaPath.pop(); return env.mediaPath.length === 0 ? media.evalTop(env) : media.evalNested(env) }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) }, find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) }, emptySelectors: function() { var el = new(tree.Element)('', '&', 0); return [new(tree.Selector)([el])]; }, evalTop: function (env) { var result = this; // Render all dependent Media blocks. if (env.mediaBlocks.length > 1) { var selectors = this.emptySelectors(); result = new(tree.Ruleset)(selectors, env.mediaBlocks); result.multiMedia = true; } delete env.mediaBlocks; delete env.mediaPath; return result; }, evalNested: function (env) { var i, value, path = env.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR). for (i = 0; i < path.length; i++) { value = path[i].features instanceof tree.Value ? path[i].features.value : path[i].features; path[i] = Array.isArray(value) ? value : [value]; } // Trace all permutations to generate the resulting media-query. // // (a, b and c) with nested (d, e) -> // a and d // a and e // b and c and d // b and c and e this.features = new(tree.Value)(this.permute(path).map(function (path) { path = path.map(function (fragment) { return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment); }); for(i = path.length - 1; i > 0; i--) { path.splice(i, 0, new(tree.Anonymous)("and")); } return new(tree.Expression)(path); })); // Fake a tree-node that doesn't output anything. return new(tree.Ruleset)([], []); }, permute: function (arr) { if (arr.length === 0) { return []; } else if (arr.length === 1) { return arr[0]; } else { var result = []; var rest = this.permute(arr.slice(1)); for (var i = 0; i < rest.length; i++) { for (var j = 0; j < arr[0].length; j++) { result.push([arr[0][j]].concat(rest[i])); } } return result; } }, bubbleSelectors: function (selectors) { this.ruleset = new(tree.Ruleset)(selectors.slice(0), [this.ruleset]); } }; })(require('../tree')); (function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index, filename, important) { this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; this.filename = filename; this.important = important; }; tree.mixin.Call.prototype = { eval: function (env) { var mixins, args, rules = [], match = false; for (var i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { args = this.arguments && this.arguments.map(function (a) { return { name: a.name, value: a.value.eval(env) }; }); for (var m = 0; m < mixins.length; m++) { if (mixins[m].match(args, env)) { try { Array.prototype.push.apply( rules, mixins[m].eval(env, this.arguments, this.important).rules); match = true; } catch (e) { throw { message: e.message, index: this.index, filename: this.filename, stack: e.stack }; } } } if (match) { return rules; } else { throw { type: 'Runtime', message: 'No matching definition was found for `' + this.selector.toCSS().trim() + '(' + this.arguments.map(function (a) { return a.toCSS(); }).join(', ') + ")`", index: this.index, filename: this.filename }; } } } throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.index, filename: this.filename }; } }; tree.mixin.Definition = function (name, params, rules, condition, variadic) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; this.condition = condition; this.variadic = variadic; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (!p.name || (p.name && !p.value)) { return count + 1 } else { return count } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { toCSS: function () { return "" }, variable: function (name) { return this.parent.variable.call(this, name) }, variables: function () { return this.parent.variables.call(this) }, find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, evalParams: function (env, args) { var frame = new(tree.Ruleset)(null, []), varargs, arg; for (var i = 0, val, name; i < this.params.length; i++) { arg = args && args[i] if (arg && arg.name) { frame.rules.unshift(new(tree.Rule)(arg.name, arg.value.eval(env))); args.splice(i, 1); i--; continue; } if (name = this.params[i].name) { if (this.params[i].variadic && args) { varargs = []; for (var j = i; j < args.length; j++) { varargs.push(args[j].value.eval(env)); } frame.rules.unshift(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env))); } else if (val = (arg && arg.value) || this.params[i].value) { frame.rules.unshift(new(tree.Rule)(name, val.eval(env))); } else { throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } } } return frame; }, eval: function (env, args, important) { var frame = this.evalParams(env, args), context, _arguments = [], rules, start; for (var i = 0; i < Math.max(this.params.length, args && args.length); i++) { _arguments.push((args[i] && args[i].value) || this.params[i].value); } frame.rules.unshift(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env))); rules = important ? this.rules.map(function (r) { return new(tree.Rule)(r.name, r.value, '!important', r.index); }) : this.rules.slice(0); return new(tree.Ruleset)(null, rules).eval({ frames: [this, frame].concat(this.frames, env.frames) }); }, match: function (args, env) { var argsLength = (args && args.length) || 0, len, frame; if (! this.variadic) { if (argsLength < this.required) { return false } if (argsLength > this.params.length) { return false } if ((this.required > 0) && (argsLength > this.params.length)) { return false } } if (this.condition && !this.condition.eval({ frames: [this.evalParams(env, args)].concat(env.frames) })) { return false } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name) { if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('../tree')); (function (tree) { tree.Operation = function (op, operands) { this.op = op.trim(); this.operands = operands; }; tree.Operation.prototype.eval = function (env) { var a = this.operands[0].eval(env), b = this.operands[1].eval(env), temp; if (a instanceof tree.Dimension && b instanceof tree.Color) { if (this.op === '*' || this.op === '+') { temp = b, b = a, a = temp; } else { throw { name: "OperationError", message: "Can't substract or divide a color from a number" }; } } return a.operate(this.op, b); }; tree.operate = function (op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } }; })(require('../tree')); (function (tree) { tree.Paren = function (node) { this.value = node; }; tree.Paren.prototype = { toCSS: function (env) { return '(' + this.value.toCSS(env) + ')'; }, eval: function (env) { return new(tree.Paren)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Quoted = function (str, content, escaped, i) { this.escaped = escaped; this.value = content || ''; this.quote = str.charAt(0); this.index = i; }; tree.Quoted.prototype = { toCSS: function () { if (this.escaped) { return this.value; } else { return this.quote + this.value + this.quote; } }, eval: function (env) { var that = this; var value = this.value.replace(/`([^`]+)`/g, function (_, exp) { return new(tree.JavaScript)(exp, that.index, true).eval(env).value; }).replace(/@\{([\w-]+)\}/g, function (_, name) { var v = new(tree.Variable)('@' + name, that.index).eval(env); return ('value' in v) ? v.value : v.toCSS(); }); return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; } }; })(require('../tree')); (function (tree) { tree.Ratio = function (value) { this.value = value; }; tree.Ratio.prototype = { toCSS: function (env) { return this.value; }, eval: function () { return this } }; })(require('../tree')); (function (tree) { tree.Rule = function (name, value, important, index, inline) { this.name = name; this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]); this.important = important ? ' ' + important.trim() : ''; this.index = index; this.inline = inline || false; if (name.charAt(0) === '@') { this.variable = true; } else { this.variable = false } }; tree.Rule.prototype.toCSS = function (env) { if (this.variable) { return "" } else { return this.name + (env.compress ? ':' : ': ') + this.value.toCSS(env) + this.important + (this.inline ? "" : ";"); } }; tree.Rule.prototype.eval = function (context) { return new(tree.Rule)(this.name, this.value.eval(context), this.important, this.index, this.inline); }; tree.Shorthand = function (a, b) { this.a = a; this.b = b; }; tree.Shorthand.prototype = { toCSS: function (env) { return this.a.toCSS(env) + "/" + this.b.toCSS(env); }, eval: function () { return this } }; })(require('../tree')); (function (tree) { tree.Ruleset = function (selectors, rules, strictImports) { this.selectors = selectors; this.rules = rules; this._lookups = {}; this.strictImports = strictImports; }; tree.Ruleset.prototype = { eval: function (env) { var selectors = this.selectors && this.selectors.map(function (s) { return s.eval(env) }); var ruleset = new(tree.Ruleset)(selectors, this.rules.slice(0), this.strictImports); var rules = []; ruleset.root = this.root; ruleset.allowImports = this.allowImports; // push the current ruleset to the frames stack env.frames.unshift(ruleset); // Evaluate imports if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.Import) { rules = rules.concat(ruleset.rules[i].eval(env)); } else { rules.push(ruleset.rules[i]); } } ruleset.rules = rules; rules = []; } // Store the frames around mixin definitions, // so they can be evaluated like closures when the time comes. for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.mixin.Definition) { ruleset.rules[i].frames = env.frames.slice(0); } } var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0; // Evaluate mixin calls. for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.mixin.Call) { rules = rules.concat(ruleset.rules[i].eval(env)); } else { rules.push(ruleset.rules[i]); } } ruleset.rules = rules; // Evaluate everything else for (var i = 0, rule; i < ruleset.rules.length; i++) { rule = ruleset.rules[i]; if (! (rule instanceof tree.mixin.Definition)) { ruleset.rules[i] = rule.eval ? rule.eval(env) : rule; } } // Pop the stack env.frames.shift(); if (env.mediaBlocks) { for(var i = mediaBlockCount; i < env.mediaBlocks.length; i++) { env.mediaBlocks[i].bubbleSelectors(selectors); } } return ruleset; }, match: function (args) { return !args || args.length === 0; }, variables: function () { if (this._variables) { return this._variables } else { return this._variables = this.rules.reduce(function (hash, r) { if (r instanceof tree.Rule && r.variable === true) { hash[r.name] = r; } return hash; }, {}); } }, variable: function (name) { return this.variables()[name]; }, rulesets: function () { if (this._rulesets) { return this._rulesets } else { return this._rulesets = this.rules.filter(function (r) { return (r instanceof tree.Ruleset) || (r instanceof tree.mixin.Definition); }); } }, find: function (selector, self) { self = self || this; var rules = [], rule, match, key = selector.toCSS(); if (key in this._lookups) { return this._lookups[key] } this.rulesets().forEach(function (rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { if (match = selector.match(rule.selectors[j])) { if (selector.elements.length > rule.selectors[j].elements.length) { Array.prototype.push.apply(rules, rule.find( new(tree.Selector)(selector.elements.slice(1)), self)); } else { rules.push(rule); } break; } } } }); return this._lookups[key] = rules; }, // // Entry point for code generation // // `context` holds an array of arrays. // toCSS: function (context, env) { var css = [], // The CSS output rules = [], // node.Rule instances _rules = [], // rulesets = [], // node.Ruleset instances paths = [], // Current selectors selector, // The fully rendered selector rule; if (! this.root) { this.joinSelectors(paths, context, this.selectors); } // Compile rules and rulesets for (var i = 0; i < this.rules.length; i++) { rule = this.rules[i]; if (rule.rules || (rule instanceof tree.Directive) || (rule instanceof tree.Media)) { rulesets.push(rule.toCSS(paths, env)); } else if (rule instanceof tree.Comment) { if (!rule.silent) { if (this.root) { rulesets.push(rule.toCSS(env)); } else { rules.push(rule.toCSS(env)); } } } else { if (rule.toCSS && !rule.variable) { rules.push(rule.toCSS(env)); } else if (rule.value && !rule.variable) { rules.push(rule.value.toString()); } } } rulesets = rulesets.join(''); // If this is the root node, we don't render // a selector, or {}. // Otherwise, only output if this ruleset has rules. if (this.root) { css.push(rules.join(env.compress ? '' : '\n')); } else { if (rules.length > 0) { selector = paths.map(function (p) { return p.map(function (s) { return s.toCSS(env); }).join('').trim(); }).join(env.compress ? ',' : ',\n'); // Remove duplicates for (var i = rules.length - 1; i >= 0; i--) { if (_rules.indexOf(rules[i]) === -1) { _rules.unshift(rules[i]); } } rules = _rules; css.push(selector, (env.compress ? '{' : ' {\n ') + rules.join(env.compress ? '' : '\n ') + (env.compress ? '}' : '\n}\n')); } } css.push(rulesets); return css.join('') + (env.compress ? '\n' : ''); }, joinSelectors: function (paths, context, selectors) { for (var s = 0; s < selectors.length; s++) { this.joinSelector(paths, context, selectors[s]); } }, joinSelector: function (paths, context, selector) { var i, j, k, hasParentSelector, newSelectors, el, sel, parentSel, newSelectorPath, afterParentJoin, newJoinedSelector, newJoinedSelectorEmpty, lastSelector, currentElements, selectorsMultiplied; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; if (el.value === '&') { hasParentSelector = true; } } if (!hasParentSelector) { if (context.length > 0) { for(i = 0; i < context.length; i++) { paths.push(context[i].concat(selector)); } } else { paths.push([selector]); } return; } // The paths are [[Selector]] // The first list is a list of comma seperated selectors // The inner list is a list of inheritance seperated selectors // e.g. // .a, .b { // .c { // } // } // == [[.a] [.c]] [[.b] [.c]] // // the elements from the current selector so far currentElements = []; // the current list of new selectors to add to the path. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors // by the parents newSelectors = [[]]; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; // non parent reference elements just get added if (el.value !== "&") { currentElements.push(el); } else { // the new list of selectors to add selectorsMultiplied = []; // merge the current list of non parent selector elements // on to the current list of selectors to add if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } // loop through our current selectors for(j = 0; j < newSelectors.length; j++) { sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used // whether there are parents or not if (context.length == 0) { // the combinator used on el should now be applied to the next element instead so that // it is not lost if (sel.length > 0) { sel[0].elements = sel[0].elements.slice(0); sel[0].elements.push(new(tree.Element)(el.combinator, '', 0)); //new Element(el.Combinator, "")); } selectorsMultiplied.push(sel); } else { // and the parent selectors for(k = 0; k < context.length; k++) { parentSel = context[k]; // We need to put the current selectors // then join the last selector's elements on to the parents selectors // our new selector path newSelectorPath = []; // selectors from the parent after the join afterParentJoin = []; newJoinedSelectorEmpty = true; //construct the joined selector - if & is the first thing this will be empty, // if not newJoinedSelector will be the last set of elements in the selector if (sel.length > 0) { newSelectorPath = sel.slice(0); lastSelector = newSelectorPath.pop(); newJoinedSelector = new(tree.Selector)(lastSelector.elements.slice(0)); newJoinedSelectorEmpty = false; } else { newJoinedSelector = new(tree.Selector)([]); } //put together the parent selectors after the join if (parentSel.length > 1) { afterParentJoin = afterParentJoin.concat(parentSel.slice(1)); } if (parentSel.length > 0) { newJoinedSelectorEmpty = false; // join the elements so far with the first part of the parent newJoinedSelector.elements.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, 0)); newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1)); } if (!newJoinedSelectorEmpty) { // now add the joined selector newSelectorPath.push(newJoinedSelector); } // and the rest of the parent newSelectorPath = newSelectorPath.concat(afterParentJoin); // add that to our new set of selectors selectorsMultiplied.push(newSelectorPath); } } } // our new selectors has been multiplied, so reset the state newSelectors = selectorsMultiplied; currentElements = []; } } // if we have any elements left over (e.g. .a& .b == .b) // add them on to all the current selectors if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } for(i = 0; i < newSelectors.length; i++) { paths.push(newSelectors[i]); } }, mergeElementsOnToSelectors: function(elements, selectors) { var i, sel; if (selectors.length == 0) { selectors.push([ new(tree.Selector)(elements) ]); return; } for(i = 0; i < selectors.length; i++) { sel = selectors[i]; // if the previous thing in sel is a parent this needs to join on to it if (sel.length > 0) { sel[sel.length - 1] = new(tree.Selector)(sel[sel.length - 1].elements.concat(elements)); } else { sel.push(new(tree.Selector)(elements)); } } } }; })(require('../tree')); (function (tree) { tree.Selector = function (elements) { this.elements = elements; }; tree.Selector.prototype.match = function (other) { var len = this.elements.length, olen = other.elements.length, max = Math.min(len, olen); if (len < olen) { return false; } else { for (var i = 0; i < max; i++) { if (this.elements[i].value !== other.elements[i].value) { return false; } } } return true; }; tree.Selector.prototype.eval = function (env) { return new(tree.Selector)(this.elements.map(function (e) { return e.eval(env); })); }; tree.Selector.prototype.toCSS = function (env) { if (this._css) { return this._css } if (this.elements[0].combinator.value === "") { this._css = ' '; } else { this._css = ''; } this._css += this.elements.map(function (e) { if (typeof(e) === 'string') { return ' ' + e.trim(); } else { return e.toCSS(env); } }).join(''); return this._css; }; })(require('../tree')); (function (tree) { tree.URL = function (val, paths) { this.value = val; this.paths = paths; }; tree.URL.prototype = { toCSS: function () { return "url(" + this.value.toCSS() + ")"; }, eval: function (ctx) { var val = this.value.eval(ctx); // Add the base path if the URL is relative and we are in the browser if (typeof window !== 'undefined' && typeof val.value === "string" && !/^(?:[a-z-]+:|\/)/.test(val.value) && this.paths.length > 0) { val.value = this.paths[0] + (val.value.charAt(0) === '/' ? val.value.slice(1) : val.value); } return new(tree.URL)(val, this.paths); } }; })(require('../tree')); (function (tree) { tree.Value = function (value) { this.value = value; this.is = 'value'; }; tree.Value.prototype = { eval: function (env) { if (this.value.length === 1) { return this.value[0].eval(env); } else { return new(tree.Value)(this.value.map(function (v) { return v.eval(env); })); } }, toCSS: function (env) { return this.value.map(function (e) { return e.toCSS(env); }).join(env.compress ? ',' : ', '); } }; })(require('../tree')); (function (tree) { tree.Variable = function (name, index, file) { this.name = name, this.index = index, this.file = file }; tree.Variable.prototype = { eval: function (env) { var variable, v, name = this.name; if (name.indexOf('@@') == 0) { name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value; } if (variable = tree.find(env.frames, function (frame) { if (v = frame.variable(name)) { return v.value.eval(env); } })) { return variable } else { throw { type: 'Name', message: "variable " + name + " is undefined", filename: this.file, index: this.index }; } } }; })(require('../tree')); (function (tree) { tree.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { if (r = fun.call(obj, obj[i])) { return r } } return null; }; tree.jsify = function (obj) { if (Array.isArray(obj.value) && (obj.value.length > 1)) { return '[' + obj.value.map(function (v) { return v.toCSS(false) }).join(', ') + ']'; } else { return obj.toCSS(false); } }; })(require('./tree')); var name; function loadStyleSheet(sheet, callback, reload, remaining) { var endOfPath = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')), sheetName = name.slice(0, endOfPath + 1) + sheet.href, contents = sheet.contents || {}, input = readFile(sheetName); contents[sheetName] = input; var parser = new less.Parser({ paths: [sheet.href.replace(/[\w\.-]+$/, '')], contents: contents }); parser.parse(input, function (e, root) { if (e) { return error(e, sheetName); } try { callback(e, root, sheet, { local: false, lastModified: 0, remaining: remaining }); } catch(e) { error(e, sheetName); } }); } function writeFile(filename, content) { var fstream = new java.io.FileWriter(filename); var out = new java.io.BufferedWriter(fstream); out.write(content); out.close(); } // Command line integration via Rhino (function (args) { var output, compress = false, i; for(i = 0; i < args.length; i++) { switch(args[i]) { case "-x": compress = true; break; default: if (!name) { name = args[i]; } else if (!output) { output = args[i]; } else { print("unrecognised parameters"); print("input_file [output_file] [-x]"); } } } if (!name) { print('No files present in the fileset; Check your pattern match in build.xml'); quit(1); } path = name.split("/");path.pop();path=path.join("/") var input = readFile(name); if (!input) { print('lesscss: couldn\'t open file ' + name); quit(1); } var result; try { var parser = new less.Parser(); parser.parse(input, function (e, root) { if (e) { error(e, name); quit(1); } else { result = root.toCSS({compress: compress || false}); if (output) { writeFile(output, result); print("Written to " + output); } else { print(result); } quit(0); } }); } catch(e) { error(e, name); quit(1); } print("done"); }(arguments)); function error(e, filename) { var content = "Error : " + filename + "\n"; filename = e.filename || filename; if (e.message) { content += e.message + "\n"; } var errorline = function (e, i, classname) { if (e.extract[i]) { content += String(parseInt(e.line) + (i - 1)) + ":" + e.extract[i] + "\n"; } }; if (e.stack) { content += e.stack; } else if (e.extract) { content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n'; errorline(e, 0); errorline(e, 1); errorline(e, 2); } print(content); }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S7.8.4_A7.2_T4; * @section: 7.8.4; * @assertion: UnicodeEscapeSequence :: u HexDigit (one, two or three time) is incorrect; * @description: :: HexDigit :: A; * @negative */ //CHECK#1 "\uAA"
/* * @author Niklas von Hertzen <niklas at hertzen.com> * @created 11.7.2012 * @website http://hertzen.com */ ( function( MODULES ){ MODULES.set_time_limit = function( newvalue ) { var COMPILER = PHP.Compiler.prototype; this.$ini.max_execution_time = newvalue[ COMPILER.VARIABLE_VALUE ]; }; })( PHP.Modules.prototype );
'use strict'; export class VersionDirective { constructor(value) { this.value = value; } link(scope, element) { element.text(this.value); } }
import React from 'react' import { storiesOf } from '@kadira/storybook' import Checkbox from '.' storiesOf('ui.Form.Checkbox', module) .add('Default', () => ( <Checkbox label="Check it!" /> ))
module.exports = function(config) { config.set({ basePath: '', files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'node_modules/quill/dist/quill.js', './src/ng-quill.js', './tests/ng-quill.spec.js', ], preprocessors: { './src/ng-quill.js': 'coverage' }, autoWatch: true, frameworks: ['jasmine'], reporters: ['mocha', 'coverage'], browsers: ['PhantomJS'], singleRun: true, coverageReporter: { reporters: [{ type : 'html', dir : 'coverage/' }, { type: 'text-summary' }] } }); };
'use strict'; //Used for audio var recording = false; var audioRecord =""; var noImageURL = "/images/no-image.jpg"; var current_data = { "memo": "", "date": {"month": "", "day": "", "year": ""}, "time": {"hour": "", "minute": ""}, "imageURL": "", "emoji": "", "emojiImageURL": "", "audioURL": "" }; // Call this function when the page loads (the "ready" event) $(document).ready(function() { initializePage(); }) function initializePage() { console.log("entry connected!"); $("#edit-text").height( $("#edit-text")[0].scrollHeight ); $("#edit-button").click( edit ); $("#delete-button").hide(); $("#no-delete-button").click( function() { $("#warning-modal").modal("hide"); } ); $("#yes-delete-button").click( delete_entry ); $("#cancel-button").hide(); $("#cancel-button").click( close_edit ); $("#save-button").hide(); $("#save-button").click( save ); $(".emojis").click( choose_emoji ); $("#emoji-modal").modal("hide"); // $("#entry-image").attr("data-target", "#image-modal"); $("#gallery").click( readImageFile ); $("#snap").click( snapImage ); $('#datetime24').hide(); $('.rm-element-button').hide(); $('.edit-audio-control').hide(); $('#playButton').click(audioToggle); $('#askForRecordButton').click(overwrite_warning); $('#audio-ok-button').hide(); $(".rm-element-button").click(removeElement); var player = document.getElementById('player'); player.onended = function(){ // console.log("Music ended"); $('#playButton').removeClass("on"); $('#playButton').attr("src", "../images/play.png"); } console.log($("#entry-container").data("entryid")); // save initial data current_data.memo = $("#edit-text").val(); current_data.time.hour = parseInt($("#entry-time").text().substr(0, 2)); current_data.time.minute = parseInt($("#entry-time").text().substr(3, 2)); current_data.date.month = parseInt($("#entry-time").data("month")); current_data.date.day = parseInt($("#entry-time").text().substr(15, 2)); current_data.date.year = parseInt($("#entry-time").text().substr(19, 4)); current_data.imageURL = $("#entry-image").attr("src"); current_data.emoji = $("#entry-emoji").data("emojiid"); current_data.emojiImageURL = $("#entry-emoji").attr("src"); current_data.audioURL = $('#player').attr("src"); console.log(current_data.memo); console.log(current_data.time); console.log(current_data.date); console.log(current_data.imageURL); console.log(current_data.emoji); console.log(current_data.audioURL); if(!current_data.audioURL){ $(".audioButton").hide() } } function audioToggle(e){ if($(this).hasClass("on")){ $(this).removeClass("on"); document.getElementById('player').pause() $(this).attr("src", "../images/play.png") }else{ $(this).addClass("on"); document.getElementById('player').play() $(this).attr("src", "../images/pause.png") } } function edit(e) { e.preventDefault(); console.log("edit!!"); $("#edit-text").attr("disabled", false); $("#edit-text").addClass("inputShadow"); $("#entry-time").addClass("inputShadow"); $("#entry-emoji").addClass("inputShadow"); $("#entry-image").addClass("inputShadow"); $("#entry-emoji").attr("data-target", "#emoji-modal"); $("#entry-image").attr("data-target", "#camera-modal"); $("#edit-button").hide(); $("#delete-button").show(); $("#cancel-button").show(); $("#save-button").show(); $("#back-button").hide(); $('#datetime24').show(); $('#datetime24').combodate(); $('#entry-time').hide(); $("#playButton").hide(); $("#stopButton").hide(); $("#askForRecordButton").show(); $(".rm-element-button").show(); $(".edit-audio-control").show(); if(current_data.audioURL==""){ $("#audio-rm-button").hide(); $("#audio-record-icon").hide(); }else{ $("#audio-rm-button").show(); $("#audio-record-icon").show(); } if(current_data.imageURL == noImageURL){ $("#img-rm-button").hide(); // $('#entry-image').attr('src','/images/add-image.jpg'); }else{ } previewCamera(); } function delete_entry(e) { e.preventDefault(); console.log("delete!!" + $("#entry-container").data("entryid")); $.post("/deleteMemory", {"id": $("#entry-container").data("entryid")}) .done(function( data ) { window.location.href = "/index"; }) .fail(function() { alert( "error" ); }); } function close_edit(e) { e.preventDefault(); $("#edit-text").attr("disabled", true); $("#edit-text").removeClass("inputShadow"); $("#entry-time").removeClass("inputShadow"); $("#entry-emoji").removeClass("inputShadow"); $("#entry-image").removeClass("inputShadow"); $("#edit-text").height( "auto" ); $("#edit-text").height( $("#edit-text")[0].scrollHeight ); $("#entry-emoji").attr("data-target", ""); $("#entry-image").attr("data-target", "#image-modal"); $("#edit-button").show(); $("#delete-button").hide(); $("#cancel-button").hide(); $("#save-button").hide(); $("#back-button").show(); $('#datetime24').combodate('destroy'); $('#datetime24').hide(); $('#entry-time').show(); // $("#askForRecordButton").hide(); $(".rm-element-button").hide(); $(".edit-audio-control").hide(); show_content(); //The code should be placed below show_contect; if( $('#player').attr("src")!=""){ $("#playButton").show(); $("#stopButton").show(); } } function save(e) { e.preventDefault(); console.log("save!!"); var data = {"id": "", "time": {"hour": "", "minute": ""}, "date": {"day": "", "month": "", "year": ""}, "emoji": "", "imageData": "", "audioData": ""}; data.id = $("#entry-container").data("entryid"); current_data.memo = $("#edit-text").val(); data.memo = $("#edit-text").val(); current_data.time.hour = parseInt($('#datetime24').val().substr(0, 2)); current_data.time.minute = parseInt($('#datetime24').val().substr(3, 2)); current_data.date.month = parseInt($('#datetime24').val().substr(6, 2)); current_data.date.day = parseInt($('#datetime24').val().substr(9, 2)); current_data.date.year = parseInt($('#datetime24').val().substr(12, 4)); data.time.hour = parseInt($('#datetime24').val().substr(0, 2)); data.time.minute = parseInt($('#datetime24').val().substr(3, 2)); data.date.month = parseInt($('#datetime24').val().substr(6, 2)); data.date.day = parseInt($('#datetime24').val().substr(9, 2)); data.date.year = parseInt($('#datetime24').val().substr(12, 4)); current_data.emoji = $("#entry-emoji").data("emojiid"); current_data.emojiImageURL = $("#entry-emoji").attr("src"); data.emoji = $("#entry-emoji").data("emojiid"); current_data.imageURL = $("#entry-image").attr("src"); if ($("#entry-image").attr("src") == noImageURL) data.imageData = ""; else data.imageData = $("#entry-image").attr("src"); if ($('#player').attr("src") == current_data.audioURL) data.audioData = current_data.audioURL; else data.audioData = audioRecord; current_data.audioURL = $('#player').attr("src"); console.log(current_data.memo); console.log(current_data.time); console.log(current_data.date); console.log(current_data.imageURL); console.log(current_data.emoji); console.log(current_data.emojiImageURL); console.log(current_data.audioURL); close_edit(e); $.post('/updateMemory', data); } function choose_emoji(e) { e.preventDefault(); $("#emoji-modal").modal("toggle"); $("#entry-emoji").data("emojiid", $(this).attr("id")); $("#entry-emoji").attr("src", $(this).attr("src")); } function show_content() { $("#edit-text").val(current_data.memo); $("#edit-text").height( $("#edit-text")[0].scrollHeight ); $("#datetime24").val(numToString(current_data.time.hour) + ":" + numToString(current_data.time.minute) + " " + numToString(current_data.date.month) + "-" + numToString(current_data.date.day) + "-" + current_data.date.year); $("#entry-time").text(numToString(current_data.time.hour) + ":" + numToString(current_data.time.minute) + " " + getWeekday(current_data.date) + " " + monthToString(current_data.date.month) + " " + numToString(current_data.date.day) + ", " + current_data.date.year); $("#entry-image").attr("src", current_data.imageURL); $("#entry-emoji").attr("src", current_data.emojiImageURL); $("#player").attr("src", current_data.audioURL); } function previewCamera() { var video = document.getElementById('video'); // Get access to the camera! if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { // Not adding `{ audio: true }` since we only want video now navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { video.src = window.URL.createObjectURL(stream); }); } video.play(); } function snapImage() { console.log("snap clicked"); $('#camera-modal').modal('toggle'); var canvas = document.createElement('canvas'); canvas.setAttribute("width", $("#entry-image").width); var context = canvas.getContext('2d'); var video = document.getElementById('video'); canvas.setAttribute("height", canvas.width / video.videoWidth * video.videoHeight); context.translate(canvas.width, 0); context.scale(-1, 1); context.drawImage(video, 0, 0, canvas.width, canvas.height); $("#entry-image").attr("src", canvas.toDataURL("")); $("#img-rm-button").show(); } function readImageFile() { console.log("gallery clicked"); var x = document.createElement("INPUT"); x.setAttribute("type", "file"); x.setAttribute("accept", "image/*"); x.click(); x.onchange = function() { readImage(this); }; $("#img-rm-button").show(); } function readImage(input) { console.log("change image!!"); if (input.files && input.files[0]) { console.log("draw image!!"); var reader = new FileReader(); reader.onload = function (e) { var img = document.getElementById('entry-image'); img.src = e.target.result; }; reader.readAsDataURL(input.files[0]); } $('#camera-modal').modal('toggle'); } function monthToString(month) { month = parseInt(month); switch(month) { case 1: return "Mon"; case 2: return "Feb"; case 3: return "Mar"; case 4: return "Apr"; case 5: return "May"; case 6: return "Jun"; case 7: return "Jul"; case 8: return "Aug"; case 9: return "Sep"; case 10: return "Oct"; case 11: return "Nov"; case 12: return "Dec"; } } function getWeekday(date) { console.log(date); var day = new Date(date.year, date.month - 1, date.day); console.log(day.getDay()); switch(day.getDay()) { case 1: return "Mon."; case 2: return "Tue."; case 3: return "Wed."; case 4: return "Thu."; case 5: return "Fri."; case 6: return "Sat."; case 0: return "Sun."; } } function removeElement(e){ if(e.target.id == "audio-rm-button"){ console.log("remove audio"); $('#playButton').hide(); $('#stopButton').hide(); $('#audio-record-icon').hide(); $('#audio-rm-button').hide(); var player = document.getElementById('player'); player.src = ''; audioRecord = ""; //TO-DO: Change the audioURL of the entry to ""; }else if(e.target.id == "img-rm-button"){ console.log("remove image"); var img = document.getElementById('entry-image'); $('#img-rm-button').hide(); img.src = noImageURL; //TO-DO: Change the imgURL of the entry to ""; }else if(e.target.id == "text-rm-button"){ console.log("remove text"); $('#edit-text').val(''); //TO-DO: Change the text of the entry to ""; } } function overwrite_warning(e){ if(!audioRecord && !$('#player').attr('src')){ $('#audio-ok-button').hide(); recordAudio(e); }else{ $("#audio-warning-modal").modal("show"); } var okButton = document.getElementById('ok-overwrite-button'); okButton.onclick = function(e){ $("#audio-warning-modal").modal("hide"); recordAudio(e); } } function recordAudio(e){ // if(!audioRecord){ // $('#audio-ok-button').hide(); // }else{ // $("#warning-modal").modal("show"); // } $("#recorder-modal").modal("toggle"); navigator.getUserMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); if (navigator.getUserMedia){ console.log('getUserMedia supported.'); var chunks = []; // The container for the audio var soundClips = document.querySelector('.sound-clips'); var record = document.getElementById('recordButton'); var okButton = document.getElementById('audio-ok-button'); var onSuccess = function(stream) { var mediaRecorder = new MediaRecorder(stream); visualize(stream); record.onclick = function() { console.log("clicked"); if(soundClips.childElementCount != 0){ soundClips.removeChild(soundClips.childNodes[0]); } if(recording==false){ mediaRecorder.start(); console.log(mediaRecorder.state); console.log("recorder started"); record.style.background = "red"; record.textContent = "Stop" }else{ mediaRecorder.stop(); console.log(mediaRecorder.state); console.log("recorder stopped"); record.style.background = ""; record.style.color = ""; record.textContent = "Record" } recording =!recording; } mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); $('#audio-ok-button').show(); var clipContainer = document.createElement('article'); var clipLabel = document.createElement('p'); var audio = document.createElement('audio'); var deleteButton = document.createElement('button'); var modelExit = document.getElementById('recorder-modal-exit-button'); clipContainer.classList.add('clip'); audio.setAttribute('controls', ''); deleteButton.textContent = 'Delete'; deleteButton.className = 'delete'; clipContainer.appendChild(audio); // clipContainer.appendChild(clipLabel); clipContainer.appendChild(deleteButton); soundClips.appendChild(clipContainer); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; //Save to global var. // audioRecord = blob; modelExit.onclick = function(e){ deleteButton.click(); } deleteButton.onclick = function(e) { audioRecord = ""; $('#audio-ok-button').hide(); if(e.target.parentNode.parentNode!=null){ e.target.parentNode.parentNode.removeChild(e.target.parentNode); } } okButton.onclick = function(e){ deleteButton.click(); var player= document.getElementById('player'); player.src = audioURL; var reader = new window.FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { audioRecord = reader.result; }; $('#audio-rm-button').show(); $('#audio-record-icon').show(); $("#recorder-modal").modal("toggle"); } } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } } var onError = function(err) { console.log('The following error occured: ' + err); } navigator.getUserMedia({ audio: true }, onSuccess, onError); } else { console.log('getUserMedia not supported!'); alert('getUserMedia not supported!'); } } function visualize(stream) { var canvas = document.querySelector('.visualizer'); var audioCtx = new (window.AudioContext || webkitAudioContext)(); var canvasCtx = canvas.getContext("2d"); var source = audioCtx.createMediaStreamSource(stream); var analyser = audioCtx.createAnalyser(); analyser.fftSize = 2048; var bufferLength = analyser.frequencyBinCount; var dataArray = new Uint8Array(bufferLength); source.connect(analyser); draw() function draw() { requestAnimationFrame(draw); analyser.getByteTimeDomainData(dataArray); canvasCtx.fillStyle = 'rgb(200, 200, 200)'; canvasCtx.fillRect(0, 0, canvas.width, canvas.height); canvasCtx.lineWidth = 2; canvasCtx.strokeStyle = 'rgb(0, 0, 0)'; canvasCtx.beginPath(); var sliceWidth = canvas.width * 1.0 / bufferLength; var x = 0; for(var i = 0; i < bufferLength; i++) { var v = dataArray[i] / 128.0; var y = v * canvas.height/2; if(i === 0) { canvasCtx.moveTo(x, y); } else { canvasCtx.lineTo(x, y); } x += sliceWidth; } canvasCtx.lineTo(canvas.width, canvas.height/2); canvasCtx.stroke(); } } function numToString(num) { if (num / 10 < 1) num = ("0" + num).slice(-2); return num; }
// flow-typed signature: 2a07b38ecca1c060715dfb1221390650 // flow-typed version: <<STUB>>/babel-loader_v^6.2.7/flow_v0.37.0 /** * This is an autogenerated libdef stub for: * * 'babel-loader' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-loader' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-loader/lib/fs-cache' { declare module.exports: any; } declare module 'babel-loader/lib/index' { declare module.exports: any; } declare module 'babel-loader/lib/resolve-rc' { declare module.exports: any; } declare module 'babel-loader/lib/utils/exists' { declare module.exports: any; } declare module 'babel-loader/lib/utils/read' { declare module.exports: any; } declare module 'babel-loader/lib/utils/relative' { declare module.exports: any; } // Filename aliases declare module 'babel-loader/lib/fs-cache.js' { declare module.exports: $Exports<'babel-loader/lib/fs-cache'>; } declare module 'babel-loader/lib/index.js' { declare module.exports: $Exports<'babel-loader/lib/index'>; } declare module 'babel-loader/lib/resolve-rc.js' { declare module.exports: $Exports<'babel-loader/lib/resolve-rc'>; } declare module 'babel-loader/lib/utils/exists.js' { declare module.exports: $Exports<'babel-loader/lib/utils/exists'>; } declare module 'babel-loader/lib/utils/read.js' { declare module.exports: $Exports<'babel-loader/lib/utils/read'>; } declare module 'babel-loader/lib/utils/relative.js' { declare module.exports: $Exports<'babel-loader/lib/utils/relative'>; }
const Lab = require('@hapi/lab'); // the test framework const Hapi = require('@hapi/hapi'); const Vision = require('@hapi/vision'); const Inert = require('@hapi/inert'); const Swagger = require('hapi-swagger'); const Docs = require('plugins/docs'); const Logger = require('test/fixtures/logger-plugin'); const Sinon = require('sinon'); const Config = require('config'); const { describe, expect, it } = (exports.lab = Lab.script()); describe('Plugin: docs', () => { it('handles vision plugin registration failures', async flags => { // cleanup const visionRegister = Vision.plugin.register; flags.onCleanup = function() { Vision.plugin.register = visionRegister; }; // setup const PLUGIN_ERROR = 'plugin error'; Vision.plugin.register = async function() { throw new Error(PLUGIN_ERROR); }; const server = Hapi.server(); // exercise and validate await expect(server.register(Docs)).to.reject(PLUGIN_ERROR); }); it('handles inert plugin registration failures', async flags => { // cleanup const inertRegister = Inert.plugin.register; flags.onCleanup = function() { Inert.plugin.register = inertRegister; }; // setup const PLUGIN_ERROR = 'plugin error'; Inert.plugin.register = async function() { throw new Error(PLUGIN_ERROR); }; const server = Hapi.server(); // exercise and validate await expect(server.register(Docs)).to.reject(PLUGIN_ERROR); }); it('handles inert plugin registration failures', async flags => { // cleanup const swaggerRegister = Swagger.plugin.register; flags.onCleanup = function() { Swagger.plugin.register = swaggerRegister; }; // setup const PLUGIN_ERROR = 'plugin error'; Swagger.plugin.register = async function() { throw new Error(PLUGIN_ERROR); }; const server = Hapi.server(); // exercise and validate await expect(server.register(Docs)).to.reject(PLUGIN_ERROR); }); it('returns the docs view', async () => { // setup const server = Hapi.server(); server.register(Logger); await server.register(Docs); await server.initialize(); server.route({ method: 'GET', path: '/', handler: () => {} }); // exercise const response = await server.inject({ method: 'GET', url: '/docs' }); // validate expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); expect(response.payload).to.be.a.string(); }); it('does not return the docs view in production', async flags => { let configStub; // cleanup flags.onCleanup = function() { configStub.restore(); }; //setup configStub = Sinon.stub(Config, 'environment').value('production'); const server = Hapi.server(); server.register(Logger); await server.register(Docs); await server.initialize(); server.route({ method: 'GET', path: '/', handler: () => {} }); // exercise and validate const response = await server.inject({ method: 'GET', url: '/docs' }); // validate expect(response.statusCode).to.equal(404); expect(response.statusMessage).to.equal('Not Found'); }); });
/** * Taking care of events * - Simulating 'change' event on contentEditable element * - Handling drag & drop logic * - Catch paste events * - Dispatch proprietary newword:composer event * - Keyboard shortcuts */ import { Composer } from "./composer"; import dom from "../dom"; import { redraw } from "../quirks/redraw" import { browser } from "../browser"; import { Constants } from "../constants"; import quirks from "../quirks"; import lang from "wysihtml5/lang"; import { removeEmptyTextNodes } from "../dom/remove_empty_text_nodes"; import { fromPlainText } from "../helpers/from_plain_text"; import ClipboardIntegrator from "../helpers/clipboard_integrator"; var newLineRegExp = /\n/g; Composer.prototype.handlePastedHTML = function(html) { try { var integrator = new ClipboardIntegrator(this) integrator.set(html, "text/html"); integrator.integrate(); } catch(e) { window.superError = e; console.log("error: ", e); throw e; } }; Composer.prototype.handlePastedPlainText = function(text) { try { var integrator = new ClipboardIntegrator(this) integrator.set(text, "text/plain"); integrator.integrate(); } catch(e) { window.superError = e; console.log("error: ", e); throw e; } }; Composer.prototype.observe = function() { var that = this, state = this.getValue(), element = this.element, pasteEvents = ["drop", "paste"], interactionEvents = ["drop", "paste", "mouseup", "focus", "keyup"]; // --------- User interaction tracking -- dom.observe(this.element, interactionEvents, function() { setTimeout(function() { that.parent.fire("interaction").fire("interaction:composer"); }, 0); }); // --------- Focus & blur logic --------- dom.observe(this.element, "focus", function() { that.parent.fire("focus").fire("focus:composer"); // Delay storing of state until all focus handler are fired // especially the one which resets the placeholder setTimeout(function() { state = that.getValue(); }, 0); }); dom.observe(this.element, "blur", function() { if (state !== that.getValue()) { that.parent.fire("change").fire("change:composer"); } that.parent.fire("blur").fire("blur:composer"); that._checkForValueAndUpdateClass(); }); // --------- Drag & Drop logic --------- dom.observe(element, ["cut", "copy"], function(e) { var clipboardData = e.clipboardData; if (clipboardData) { var range = that.selection.getRange(); var plainText = range.toString(); var content = range.cloneContents(); var node = document.createElement("div"); node.appendChild(content); clipboardData.setData("text/plain", node.innerText || node.textContent); clipboardData.setData("text/html", node.innerHTML); if (e.type == "cut") { range.deleteContents(); this.ensureParagraph({force: true}); } e.preventDefault(); that._checkForValueAndUpdateClass(); } }.bind(this)); dom.observe(element, pasteEvents, function(e) { var clipboardData = e.clipboardData; if (clipboardData) { var range = that.selection.getRange(); var data = clipboardData.getData("text/html"); if (data) { this.handlePastedHTML(data); } else if (data = clipboardData.getData("Text")) { this.handlePastedPlainText(data); } var textNodes = that._textNodes(that.element); that._processNodesForBlockTextSubstitution(textNodes); e.preventDefault(); } else { var keepScrollPosition = true; setTimeout(function() { that.selection.executeAndRestore(function() { quirks.cleanPastedHTML(that.element); that.parent.parse(that.element); }, keepScrollPosition); }, 0) } }.bind(this)); // --------- neword event --------- dom.observe(element, "keyup", function(event) { var keyCode = event.keyCode; that._checkForValueAndUpdateClass(); if (keyCode === Constants.SPACE_KEY || keyCode === Constants.ENTER_KEY) { that.parent.fire("newword:composer"); } }); dom.observe(element, "keydown", function(event) { var keyCode = event.keyCode; that._checkForPendingValueChangeAndUpdateClass(keyCode); }); this.parent.on("paste:composer", function() { setTimeout(function() { that.parent.fire("newword:composer"); that._updateHasValueClass(); }, 0); }); // --------- Make sure that images are selected when clicking on them --------- if (!browser.canSelectImagesInContentEditable()) { dom.observe(element, "mousedown", function(event) { var target = event.target; if (target.nodeName === "IMG") { that.selection.selectNode(target); } }); } if (!browser.canSelectImagesInContentEditable()) { dom.observe(element, "drop", function(event) { // TODO: if I knew how to get dropped elements list from event I could limit it to only IMG element case setTimeout(function() { that.selection.getSelection().removeAllRanges(); }, 0); }); } // TODO write failing implementation test for this if (browser.hasHistoryIssue() && browser.supportsSelectionModify()) { dom.observe(element, "keydown", function(event) { if (!event.metaKey && !event.ctrlKey) { return; } var keyCode = event.keyCode, win = element.ownerDocument.defaultView, selection = win.getSelection(); if (keyCode === 37 || keyCode === 39) { if (keyCode === 37) { selection.modify("extend", "left", "lineboundary"); if (!event.shiftKey) { selection.collapseToStart(); } } if (keyCode === 39) { selection.modify("extend", "right", "lineboundary"); if (!event.shiftKey) { selection.collapseToEnd(); } } event.preventDefault(); } }); } };
document.getElementById('note').innerHTML="<font class='ajax'><input type='hidden' name='star' id='star' value='" + id + "'></font>"; for (var i = 0; i < id; i++) { document.getElementById(i + 1).src = "../img/star1_48x48.png"; } var textos = ["Detestei", "Não gostei", "Razoável", "Gostei", "Adorei"]; var user = document.getElementById('idLogged').value; if (user != "") { document.getElementById('voto').value = id; document.getElementById('msg').innerHTML="<div class='alert alert-danger' style='height:48px;text-align:center;'>" + texxtos[id - 1] + "</div>"; } else { document.getElementById('msg').innerHTML="<div class='alert alert-danger' style='height:48px;text-align:center;'><strong>Erro ao avaliar!</strong> É necessário realizar o login para enviar um comentário.</div>"; } //https://pt.stackoverflow.com/q/104100/101
const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = { entry: path.resolve(__dirname, 'lib/index'), output: { path: path.resolve(__dirname, 'dist'), filename: 'react-simple-chatbot.js', publicPath: 'dist/', library: 'ReactSimpleChatbot', libraryTarget: 'umd', }, resolve: { extensions: ['.js', '.jsx'], }, plugins: [ new CleanWebpackPlugin(['dist']), new UglifyJsPlugin({ comments: false, }), ], module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, use: ['babel-loader'], }, ], }, };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const vscode = require("vscode"); class SolargraphWebviewProvider { constructor() { this.views = {}; } parseQuery(query) { var result = {}; var parts = query.split('&'); parts.forEach((part) => { var frag = part.split('='); result[decodeURIComponent(frag[0])] = decodeURIComponent(frag[1]); }); return result; } open(uri) { var uriString = uri.toString(); var method = '$/solargraph' + uri.path; var query = this.parseQuery(uri.query.replace(/=/g, '%3D').replace(/\%$/, '%25').replace(/query\%3D/, 'query=')); if (!this.views[uriString]) { this.views[uriString] = vscode.window.createWebviewPanel('solargraph', uriString, vscode.ViewColumn.Two, { enableCommandUris: true }); this.views[uriString].onDidDispose(() => { delete this.views[uriString]; }); this.views[uriString].webview.html = 'Loading...'; } this.languageClient.sendRequest(method, query).then((result) => { if (this.views[uriString]) { var converted = this.convertDocumentation(result.content); this.views[uriString].webview.html = converted; } }); } setLanguageClient(lc) { this.languageClient = lc; } convertDocumentation(text) { var regexp = /\"solargraph\:(.*?)\"/g; var match; var adjusted = text; while (match = regexp.exec(text)) { var commandUri = "\"command:solargraph._openDocumentUrl?" + encodeURI(JSON.stringify("solargraph:" + match[1])) + "\""; adjusted = adjusted.replace(match[0], commandUri); } return adjusted; } ; } exports.default = SolargraphWebviewProvider; //# sourceMappingURL=SolargraphWebviewProvider.js.map
import React, {PropTypes, Component} from 'react'; import { Text, View, StyleSheet } from 'react-native'; const color = () => Math.floor(255 * Math.random()); /** * Sample view to demonstrate navigation patterns. * @TODO remove this module in a live application. */ class ColorView extends Component { static displayName = 'ColorView'; static propTypes = { index: PropTypes.number.isRequired, navigationStateActions: PropTypes.shape({ pushRoute: PropTypes.func.isRequired }) }; constructor(props) { super(props); this.state = { background: `rgba(${color()},${color()},${color()}, 1)` }; } onNextPress = () => { const index = this.props.index; this.props.navigationStateActions.pushRoute({ key: `Color_${index + 1}`, title: `Color Screen #${index + 1}` }); }; render() { const index = this.props.index; const text = `View #${index}`; return ( <View style={[styles.container, {backgroundColor: this.state.background}]}> <Text onPress={this.onNextPress}> {text} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center' } }); export default ColorView;
const User = require('../db/mongo/models/User'); /** * Authenticate a user from one of its email and password * * @param {String} email * @param {String} password * @param {Function} done */ function auth(email, password, done) { User.loadFromEmail(email, (err, user) => { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Email ' + email + ' not found'}); } user.comparePassword(password, (err, isMatch) => { if (err) { return done(err); } if (isMatch) { return done(null, user); } return done(null, false, { message: 'Invalid email or password.' }); }); }); } module.exports.auth = auth;
import $ from 'dom7'; import Utils from '../../utils/utils'; import Framework7Class from '../../utils/class'; class Messagebar extends Framework7Class { constructor(app, params = {}) { super(params, [app]); const messagebar = this; const defaults = { top: false, topOffset: 0, bottomOffset: 0, attachments: [], renderAttachments: undefined, renderAttachment: undefined, maxHeight: null, resizePage: true, }; // Extend defaults with modules params messagebar.useModulesParams(defaults); messagebar.params = Utils.extend(defaults, params); // El const $el = $(messagebar.params.el); if ($el.length === 0) return messagebar; if ($el[0].f7Messagebar) return $el[0].f7Messagebar; $el[0].f7Messagebar = messagebar; // Page and PageContent const $pageEl = $el.parents('.page').eq(0); const $pageContentEl = $pageEl.find('.page-content').eq(0); // Area const $areaEl = $el.find('.messagebar-area'); // Textarea let $textareaEl; if (messagebar.params.textareaEl) { $textareaEl = $(messagebar.params.textareaEl); } else { $textareaEl = $el.find('textarea'); } // Attachments & Library const $attachmentsEl = $el.find('.messagebar-attachments'); const $sheetEl = $el.find('.messagebar-sheet'); if (messagebar.params.top) { $el.addClass('messagebar-top'); } Utils.extend(messagebar, { $el, el: $el[0], $areaEl, areaEl: $areaEl[0], $textareaEl, textareaEl: $textareaEl[0], $attachmentsEl, attachmentsEl: $attachmentsEl[0], attachmentsVisible: $attachmentsEl.hasClass('messagebar-attachments-visible'), $sheetEl, sheetEl: $sheetEl[0], sheetVisible: $sheetEl.hasClass('messagebar-sheet-visible'), $pageEl, pageEl: $pageEl[0], $pageContentEl, pageContentEl: $pageContentEl, top: $el.hasClass('messagebar-top') || messagebar.params.top, attachments: [], }); // Events function onAppResize() { if (messagebar.params.resizePage) { messagebar.resizePage(); } } function onSubmit(e) { e.preventDefault(); } function onAttachmentClick(e) { const index = $(this).index(); if ($(e.target).closest('.messagebar-attachment-delete').length) { $(this).trigger('messagebar:attachmentdelete', index); messagebar.emit('local::attachmentDelete messagebarAttachmentDelete', messagebar, this, index); } else { $(this).trigger('messagebar:attachmentclick', index); messagebar.emit('local::attachmentClick messagebarAttachmentClick', messagebar, this, index); } } function onTextareaChange() { messagebar.checkEmptyState(); messagebar.$el.trigger('messagebar:change'); messagebar.emit('local::change messagebarChange', messagebar); } function onTextareaFocus() { messagebar.sheetHide(); messagebar.$el.addClass('messagebar-focused'); messagebar.$el.trigger('messagebar:focus'); messagebar.emit('local::focus messagebarFocus', messagebar); } function onTextareaBlur() { messagebar.$el.removeClass('messagebar-focused'); messagebar.$el.trigger('messagebar:blur'); messagebar.emit('local::blur messagebarBlur', messagebar); } messagebar.attachEvents = function attachEvents() { $el.on('textarea:resize', onAppResize); $el.on('submit', onSubmit); $el.on('click', '.messagebar-attachment', onAttachmentClick); $textareaEl.on('change input', onTextareaChange); $textareaEl.on('focus', onTextareaFocus); $textareaEl.on('blur', onTextareaBlur); app.on('resize', onAppResize); }; messagebar.detachEvents = function detachEvents() { $el.off('textarea:resize', onAppResize); $el.off('submit', onSubmit); $el.off('click', '.messagebar-attachment', onAttachmentClick); $textareaEl.off('change input', onTextareaChange); $textareaEl.off('focus', onTextareaFocus); $textareaEl.off('blur', onTextareaBlur); app.off('resize', onAppResize); }; // Install Modules messagebar.useModules(); // Init messagebar.init(); return messagebar; } focus() { const messagebar = this; messagebar.$textareaEl.focus(); return messagebar; } blur() { const messagebar = this; messagebar.$textareaEl.blur(); return messagebar; } clear() { const messagebar = this; messagebar.$textareaEl.val('').trigger('change'); return messagebar; } getValue() { const messagebar = this; return messagebar.$textareaEl.val().trim(); } setValue(value) { const messagebar = this; messagebar.$textareaEl.val(value).trigger('change'); return messagebar; } setPlaceholder(placeholder) { const messagebar = this; messagebar.$textareaEl.attr('placeholder', placeholder); return messagebar; } resizePage() { const messagebar = this; const { params, $el, top, $pageEl, $pageContentEl, $areaEl, $textareaEl, $sheetEl, $attachmentsEl, } = messagebar; const elHeight = $el[0].offsetHeight; let maxHeight = params.maxHeight; if (top) { /* Disable at the moment const requiredPaddingTop = elHeight + params.topOffset; const currentPaddingTop = parseInt($pageContentEl.css('padding-top'), 10); if (requiredPaddingTop !== currentPaddingTop) { if (!maxHeight) { maxHeight = $pageEl[0].offsetHeight - currentPaddingTop - $sheetEl.outerHeight() - $attachmentsEl.outerHeight() - parseInt($areaEl.css('margin-top'), 10) - parseInt($areaEl.css('margin-bottom'), 10); } $textareaEl.css('max-height', `${maxHeight}px`); $pageContentEl.css('padding-top', `${requiredPaddingTop}px`); $el.trigger('messagebar:resizePage'); messagebar.emit('local::resizepage messagebarResizePage'); } */ } else { const currentPaddingBottom = parseInt($pageContentEl.css('padding-bottom'), 10); const requiredPaddingBottom = elHeight + params.bottomOffset; if (requiredPaddingBottom !== currentPaddingBottom && $pageContentEl.length) { const currentPaddingTop = parseInt($pageContentEl.css('padding-top'), 10); const pageScrollHeight = $pageContentEl[0].scrollHeight; const pageOffsetHeight = $pageContentEl[0].offsetHeight; const pageScrollTop = $pageContentEl[0].scrollTop; const scrollOnBottom = (pageScrollTop === pageScrollHeight - pageOffsetHeight); if (!maxHeight) { maxHeight = $pageEl[0].offsetHeight - currentPaddingTop - $sheetEl.outerHeight() - $attachmentsEl.outerHeight() - parseInt($areaEl.css('margin-top'), 10) - parseInt($areaEl.css('margin-bottom'), 10); } $textareaEl.css('max-height', `${maxHeight}px`); $pageContentEl.css('padding-bottom', `${requiredPaddingBottom}px`); if (scrollOnBottom) { $pageContentEl.scrollTop($pageContentEl[0].scrollHeight - pageOffsetHeight); } $el.trigger('messagebar:resizepage'); messagebar.emit('local::resizePage messagebarResizePage', messagebar); } } } checkEmptyState() { const messagebar = this; const { $el, $textareaEl } = messagebar; const value = $textareaEl.val().trim(); if (value && value.length) { $el.addClass('messagebar-with-value'); } else { $el.removeClass('messagebar-with-value'); } } attachmentsCreate(innerHTML = '') { const messagebar = this; const $attachmentsEl = $(`<div class="messagebar-attachments">${innerHTML}</div>`); $attachmentsEl.insertBefore(messagebar.$textareaEl); Utils.extend(messagebar, { $attachmentsEl, attachmentsEl: $attachmentsEl[0], }); return messagebar; } attachmentsShow(innerHTML = '') { const messagebar = this; messagebar.$attachmentsEl = messagebar.$el.find('.messagebar-attachments'); if (messagebar.$attachmentsEl.length === 0) { messagebar.attachmentsCreate(innerHTML); } messagebar.$el.addClass('messagebar-attachments-visible'); messagebar.attachmentsVisible = true; if (messagebar.params.resizePage) { messagebar.resizePage(); } return messagebar; } attachmentsHide() { const messagebar = this; messagebar.$el.removeClass('messagebar-attachments-visible'); messagebar.attachmentsVisible = false; if (messagebar.params.resizePage) { messagebar.resizePage(); } return messagebar; } attachmentsToggle() { const messagebar = this; if (messagebar.attachmentsVisible) { messagebar.attachmentsHide(); } else { messagebar.attachmentsShow(); } return messagebar; } renderAttachment(attachment) { const messagebar = this; if (messagebar.params.renderAttachment) { return messagebar.params.renderAttachment.call(messagebar, attachment); } return ` <div class="messagebar-attachment"> <img src="${attachment}"> <span class="messagebar-attachment-delete"></span> </div> `; } renderAttachments() { const messagebar = this; let html; if (messagebar.params.renderAttachments) { html = messagebar.params.renderAttachments.call(messagebar, messagebar.attachments); } else { html = `${messagebar.attachments.map(attachment => messagebar.renderAttachment(attachment)).join('')}`; } if (messagebar.$attachmentsEl.length === 0) { messagebar.attachmentsCreate(html); } else { messagebar.$attachmentsEl.html(html); } } sheetCreate(innerHTML = '') { const messagebar = this; const $sheetEl = $(`<div class="messagebar-sheet">${innerHTML}</div>`); messagebar.$el.append($sheetEl); Utils.extend(messagebar, { $sheetEl, sheetEl: $sheetEl[0], }); return messagebar; } sheetShow(innerHTML = '') { const messagebar = this; messagebar.$sheetEl = messagebar.$el.find('.messagebar-sheet'); if (messagebar.$sheetEl.length === 0) { messagebar.sheetCreate(innerHTML); } messagebar.$el.addClass('messagebar-sheet-visible'); messagebar.sheetVisible = true; if (messagebar.params.resizePage) { messagebar.resizePage(); } return messagebar; } sheetHide() { const messagebar = this; messagebar.$el.removeClass('messagebar-sheet-visible'); messagebar.sheetVisible = false; if (messagebar.params.resizePage) { messagebar.resizePage(); } return messagebar; } sheetToggle() { const messagebar = this; if (messagebar.sheetVisible) { messagebar.sheetHide(); } else { messagebar.sheetShow(); } return messagebar; } init() { const messagebar = this; messagebar.attachEvents(); messagebar.checkEmptyState(); return messagebar; } destroy() { const messagebar = this; messagebar.emit('local::beforeDestroy messagebarBeforeDestroy', messagebar); messagebar.$el.trigger('messagebar:beforedestroy'); messagebar.detachEvents(); if (messagebar.$el[0]) { messagebar.$el[0].f7Messagebar = null; delete messagebar.$el[0].f7Messagebar; } Utils.deleteProps(messagebar); } } export default Messagebar;
t = [10, 6, 6]; root = document.getElementById("sympla-widget-169502"); cw = root.clientWidth - 95; h = 258; for (i = 0; i < 3; i++) { l = Math.floor(t[i] / (cw / 9)) + 1; h += 49; if (cw <= 154) h += 20; h += (l * 15) + ((l - 1) * 5); } console.log(h); root.setAttribute("style", "max-width: 600px;"); ifrm = document.createElement("IFRAME"); ifrm.setAttribute("src", "https://www.sympla.com.br/tickets-grid-widget?eid=169502&lang=pt"); ifrm.setAttribute("id", "symplaw"); ifrm.setAttribute("frameborder", "0"); ifrm.setAttribute("vspace", "0"); ifrm.setAttribute("hspace", "0"); ifrm.setAttribute("marginheight", "0"); ifrm.setAttribute("marginwidth", "5"); if (root.getAttribute("height") == "auto" || root.getAttribute("height") == null) { ifrm.style.width = "100%"; ifrm.style.height = h + "px"; } else { if (root.getAttribute("height") != null) { ifrm.style.width = "100%"; ifrm.style.height = root.getAttribute("height") + "px"; } } while (root.firstChild) { root.removeChild(root.firstChild); } root.appendChild(ifrm);
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- Object.defineProperty(RegExp, "fakeProp", { value: 101, writable: true, enumerable: true, configurable: true }); var propertyConstructorArray = ["fakeProp","$_","$*","$&","$+","$`","$'","input", "lastMatch","lastParen","leftContext","rightContext", "index","length","prototype","constructor" ]; var propertyInstanceArray = ["global","ignoreCase","lastIndex","multiline","source","sticky","dotAll"]; function RegexTests(i,propertyArray) { WScript.Echo("starting Property[",i,"]: ",propertyArray[i]); //Does the property exist var doesPropExist = RegExp.hasOwnProperty(propertyArray[i]); WScript.Echo("Does Property exist: ",doesPropExist); if(!doesPropExist) return; //Is the property configurable var isPropConfig = Object.getOwnPropertyDescriptor(RegExp, propertyArray[i]).configurable; WScript.Echo("Is the Property configurable: ",isPropConfig); var canRedefine = false; var canDelete = false; if(isPropConfig) { canRedefine = true; canDelete = true; } var propValueBefore = RegExp[propertyArray[i]]; try { Object.defineProperty(RegExp, propertyArray[i], { get : function () { return 'OVERRIDE' } }); } catch(err) { if(isPropConfig) WScript.Echo("Fail"); else WScript.Echo("PASS, Not Configurable and will not allow redefinition"); } var deleteProp = false; if(isPropConfig) { if(RegExp[propertyArray[i]] =="OVERRIDE") WScript.Echo("PASS"); else WScript.Echo("FAIL, currently equals: ",RegExp[propertyArray[i]]); } else { if(RegExp[propertyArray[i]] ==propValueBefore) WScript.Echo("PASS"); else WScript.Echo("FAIL, currently equals: ",RegExp[propertyArray[i]]); } deleteProp = delete RegExp[propertyArray[i]]; WScript.Echo("can you delete the property: ",canDelete, "did it actually delete?",deleteProp); if(deleteProp ==canDelete) WScript.Echo("Pass Delete Test"); else WScript.Echo("Fail Delete Test"); } function RegexInstanceTests(i,propertyArray) { var pattern1=new RegExp("e"); WScript.Echo("starting Property[",i,"]: ",propertyArray[i]); //Does the property exist var doesPropExist = pattern1.hasOwnProperty(propertyArray[i]); WScript.Echo("Does Property exist: ",doesPropExist); if(!doesPropExist) return; var isPropConfig = Object.getOwnPropertyDescriptor(pattern1, propertyArray[i]).configurable; WScript.Echo("Is the Property configurable: ",isPropConfig); var canRedefine = false; var canDelete = false; if(isPropConfig) { canRedefine = true; canDelete = true; } var propValueBefore = pattern1[propertyArray[i]]; try { Object.defineProperty(pattern1, propertyArray[i], { get : function () { return 'OVERRIDE' } }); } catch(err) { if(isPropConfig) WScript.Echo("Fail"); else WScript.Echo("PASS, Not Configurable and will not allow redefinition"); } var deleteProp = false; if(isPropConfig) { if(pattern1[propertyArray[i]] =="OVERRIDE") WScript.Echo("PASS"); else WScript.Echo("FAIL, currently equals: ",pattern1[propertyArray[i]]); } else { if(pattern1[propertyArray[i]] ==propValueBefore) WScript.Echo("PASS"); else WScript.Echo("FAIL, currently equals: ",pattern1[propertyArray[i]]); } deleteProp = delete pattern1[propertyArray[i]]; WScript.Echo("can you delete the property: ",canDelete, "did it actually delete?",deleteProp); if(deleteProp ==canDelete) WScript.Echo("Pass Delete Test"); else WScript.Echo("Fail Delete Test"); } for(var i = 0; i < propertyConstructorArray.length;i++) { RegexTests(i,propertyConstructorArray); WScript.Echo("\n"); } for(var i = 0; i < propertyInstanceArray.length;i++) { RegexTests(i,propertyInstanceArray); WScript.Echo("\n"); } for(var i = 0; i < propertyInstanceArray.length;i++) { RegexInstanceTests(i,propertyInstanceArray); WScript.Echo("\n"); }
#!/usr/bin/env node /* eslint global-require: 0 */ /* eslint no-console: 0 */ 'use strict'; const Err = require('../lib/common/cli/error'); const pkg = require('../package.json'); const err = new Err(); const displayError = (error) => { console.log(err.get(error, true)); process.exit(1); }; process.on('uncaughtException', e => displayError(e)); process.on('unhandledRejection', e => displayError(e)); try { const sqz = require('./Squeezer'); sqz.init(); const CLI = require('./cli'); const updateNotifier = require('update-notifier'); updateNotifier({ pkg }).notify(); CLI.run(); } catch (e) { displayError(e); }
// Copyright 2016 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var _ = { map: require( "lodash.map" ), flattenDeep: require( "lodash.flattendeep" ), uniq: require( "lodash.uniq" ), without: require( "lodash.without" ) }; var fs = require( "fs" ); var path = require( "path" ); var repoPaths = require( "./helpers/repo-paths" ); function getMethods( topPath ) { return _.uniq( _.flattenDeep( _.map( fs.readdirSync( topPath ), function( item ) { item = path.join( topPath, item ); return fs.statSync( item ).isDirectory() ? getMethods( item ) : _.without( _.map( fs.readFileSync( item, { encoding: "utf8" } ) .replace( /\r/g, "" ) .split( "\n" ), function( line ) { var match = line.match( /^napi_value\s+bind_([^(]+)/ ); if ( match && match.length > 1 ) { return match[ 1 ].replace( /\s/g, "" ); } } ), undefined ); } ) ) ); } var methods; var functionsCC = path.join( repoPaths.generated, "functions.cc" ); var protosH = path.join( repoPaths.generated, "function-prototypes.h" ); methods = getMethods( repoPaths.src ); fs.writeFileSync( protosH, [ "#ifndef __IOTIVITY_NODE_FUNCTION_PROTOTYPES_H__", "#define __IOTIVITY_NODE_FUNCTION_PROTOTYPES_H__", "" ] .concat( _.map( methods, function( item ) { return "napi_value bind_" + item + "(napi_env env, napi_callback_info info);"; } ) ) .concat( [ "", "#endif /* ndef __IOTIVITY_NODE_FUNCTION_PROTOTYPES_H__ */" ] ) .join( "\n" ) ); fs.writeFileSync( functionsCC, [ "#include \"../src/functions.h\"", "#include \"function-prototypes.h\"", "", "std::string InitFunctions(napi_env env, napi_value exports) {" ] .concat( _.map( methods, function( item ) { return " SET_FUNCTION(env, exports, " + item + ");"; } ) ) .concat( [ " return std::string();", "}\n" ] ) .join( "\n" ) );
/** * XadillaX created at 2016-02-02 15:12:29 With ♥ * * Copyright (c) 2016 Souche.com, all rights * reserved. */ "use strict"; const gulp = require("gulp"); const plugins = require("gulp-load-plugins")(); const config = require("../../config"); gulp.task("bootstrap_js_dev", () => { return gulp.src(`${config.srcBowerPath}/bootstrap/dist/js/*.js`) .pipe(gulp.dest(`${config.devAssetsPath}/js`)) .pipe(plugins.size()); }); gulp.task("bootstrap_css_dev", () => { return gulp.src(`${config.srcBowerPath}/bootstrap/dist/css/*.css`) .pipe(gulp.dest(`${config.devAssetsPath}/css`)) .pipe(plugins.size()); }); gulp.task("bootstrap_font_dev", () => { return gulp.src(`${config.srcBowerPath}/bootstrap/dist/fonts/*`) .pipe(gulp.dest(`${config.devAssetsPath}/fonts`)) .pipe(plugins.size()); }); gulp.task("bootstrap_dev", [ "bootstrap_js_dev", "bootstrap_css_dev", "bootstrap_font_dev" ]);
import TestResolverApplicationTestCase from './test-resolver-application'; import { Application } from 'ember-application'; import { assign } from 'ember-utils'; import { Router } from 'ember-routing'; export default class AutobootApplicationTestCase extends TestResolverApplicationTestCase { createApplication(options, MyApplication = Application) { let myOptions = assign(this.applicationOptions, options); let application = (this.application = MyApplication.create(myOptions)); this.resolver = myOptions.Resolver.lastInstance; if (this.resolver) { this.resolver.add('router:main', Router.extend(this.routerOptions)); } return application; } visit(url) { return this.application.boot().then(() => { return this.applicationInstance.visit(url); }); } get applicationInstance() { let { application } = this; if (!application) { return undefined; } return application.__deprecatedInstance__; } }
var sass = require('node-sass'); var Processor = require('./processor'); module.exports = function(options) { var opts = options || {}; var processor = new Processor(opts); return { 'image-url($filename, $only_path: false)': function(filename, only_path, done) { processor.image_url(filename.getValue(), function(url) { if(!only_path.getValue()) url = 'url(\'' + url + '\')'; done(new sass.types.String(url)); }); }, 'inline-image($filename, $mime_type: null)': function(filename, mime_type, done) { mime_type = mime_type instanceof sass.types.Null ? null : mime_type.getValue(); processor.inline_image(filename.getValue(), mime_type, function(dataUrl) { done(new sass.types.String('url(\'' + dataUrl + '\')')); }); }, 'image-width($filename)': function(filename, done) { processor.image_width(filename.getValue(), function(image_width) { done(new sass.types.Number(image_width, 'px')); }); }, 'image-height($filename)': function(filename, done) { processor.image_height(filename.getValue(), function(image_height) { done(new sass.types.Number(image_height, 'px')); }); } }; };
// @flow import { visibleTodosSelector } from '../../selectors'; describe('visibleTodosSelector', () => { let state; beforeEach(() => { state = { todos: [ { id: 0, text: 'Test Todo 1', completed: false }, { id: 1, text: 'Test Todo 2', completed: true } ], visibilityFilter: 'SHOW_ALL' }; }); test('should handle SHOW_ALL', () => { expect(visibleTodosSelector(state)).toEqual([ { id: 0, text: 'Test Todo 1', completed: false }, { id: 1, text: 'Test Todo 2', completed: true } ]); }); test('should handle SHOW_ACTIVE', () => { state.visibilityFilter = 'SHOW_ACTIVE'; expect(visibleTodosSelector(state)).toEqual([ { id: 0, text: 'Test Todo 1', completed: false } ]); }); test('should handle SHOW_COMPLETED', () => { state.visibilityFilter = 'SHOW_COMPLETED'; expect(visibleTodosSelector(state)).toEqual([ { id: 1, text: 'Test Todo 2', completed: true } ]); }); });
//# sourceMappingURL=IView.js.map
'use strict'; /* Copyright (c) 2014, Ismaël Héry 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. */ /* * Spec for the French Porter Stemmer can be found at: * http://snowball.tartarus.org/algorithms/french/stemmer.html */ var Stemmer = require('./stemmer_fr'); var PorterStemmer = new Stemmer(); module.exports = PorterStemmer; // Export PorterStemmer.stem = stem; // Exports for test purpose PorterStemmer.prelude = prelude; PorterStemmer.regions = regions; PorterStemmer.endsinArr = endsinArr; /** * Stem a word thanks to Porter Stemmer rules * @param {String} token Word to be stemmed * @return {String} Stemmed word */ function stem(token) { token = prelude(token.toLowerCase()); if (token.length == 1) return token; var regs = regions(token); var r1_txt, r2_txt, rv_txt; r1_txt = token.substring(regs.r1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); // Step 1 var beforeStep1 = token; var suf, pref2, pref3, letterBefore, letter2Before, i; var doStep2a = false; if ((suf = endsinArr(r2_txt, ['ance', 'iqUe', 'isme', 'able', 'iste', 'eux', 'ances', 'iqUes', 'ismes', 'ables', 'istes'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(token, ['icatrice', 'icateur', 'ication', 'icatrices', 'icateurs', 'ications'])) != '') { if (endsinArr(r2_txt, ['icatrice', 'icateur', 'ication', 'icatrices', 'icateurs', 'ications']) != '') { token = token.slice(0, -suf.length); // delete } else { token = token.slice(0, -suf.length) + 'iqU'; // replace by iqU } } else if ((suf = endsinArr(r2_txt, ['atrice', 'ateur', 'ation', 'atrices', 'ateurs', 'ations'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(r2_txt, ['logie', 'logies'])) != '') { token = token.slice(0, -suf.length) + 'log'; // replace with log } else if ((suf = endsinArr(r2_txt, ['usion', 'ution', 'usions', 'utions'])) != '') { token = token.slice(0, -suf.length) + 'u'; // replace with u } else if ((suf = endsinArr(r2_txt, ['ence', 'ences'])) != '') { token = token.slice(0, -suf.length) + 'ent'; // replace with ent } // ement(s) else if ((suf = endsinArr(r1_txt, ['issement', 'issements'])) != '') { if (!isVowel(token[token.length - suf.length - 1])) { token = token.slice(0, -suf.length); // delete r1_txt = token.substring(regs.r1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } } else if ((suf = endsinArr(r2_txt, ['ativement', 'ativements'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(r2_txt, ['ivement', 'ivements'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(token, ['eusement', 'eusements'])) != '') { if ((suf = endsinArr(r2_txt, ['eusement', 'eusements'])) != '') token = token.slice(0, -suf.length); // delete else if ((suf = endsinArr(r1_txt, ['eusement', 'eusements'])) != '') token = token.slice(0, -suf.length) + 'eux'; // replace by eux else if ((suf = endsinArr(rv_txt, ['ement', 'ements'])) != '') token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(r2_txt, ['ablement', 'ablements', 'iqUement', 'iqUements'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(rv_txt, ['ièrement', 'ièrements', 'Ièrement', 'Ièrements'])) != '') { token = token.slice(0, -suf.length) + 'i'; // replace by i } else if ((suf = endsinArr(rv_txt, ['ement', 'ements'])) != '') { token = token.slice(0, -suf.length); // delete } // ité(s) else if ((suf = endsinArr(token, ['icité', 'icités'])) != '') { if (endsinArr(r2_txt, ['icité', 'icités']) != '') token = token.slice(0, -suf.length); // delete else token = token.slice(0, -suf.length) + 'iqU'; // replace by iqU } else if ((suf = endsinArr(token, ['abilité', 'abilités'])) != '') { if (endsinArr(r2_txt, ['abilité', 'abilités']) != '') token = token.slice(0, -suf.length); // delete else token = token.slice(0, -suf.length) + 'abl'; // replace by abl } else if ((suf = endsinArr(r2_txt, ['ité', 'ités'])) != '') { token = token.slice(0, -suf.length); // delete if in R2 } else if ((suf = endsinArr(token, ['icatif', 'icative', 'icatifs', 'icatives'])) != '') { if ((suf = endsinArr(r2_txt, ['icatif', 'icative', 'icatifs', 'icatives'])) != '') { token = token.slice(0, -suf.length); // delete r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } if ((suf = endsinArr(r2_txt, ['atif', 'ative', 'atifs', 'atives'])) != '') { token = token.slice(0, -suf.length - 2) + 'iqU'; // replace with iqU r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } } else if ((suf = endsinArr(r2_txt, ['atif', 'ative', 'atifs', 'atives'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(r2_txt, ['if', 'ive', 'ifs', 'ives'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(token, ['eaux'])) != '') { token = token.slice(0, -suf.length) + 'eau'; // replace by eau } else if ((suf = endsinArr(r1_txt, ['aux'])) != '') { token = token.slice(0, -suf.length) + 'al'; // replace by al } else if ((suf = endsinArr(r2_txt, ['euse', 'euses'])) != '') { token = token.slice(0, -suf.length); // delete } else if ((suf = endsinArr(r1_txt, ['euse', 'euses'])) != '') { token = token.slice(0, -suf.length) + 'eux'; // replace by eux } else if ((suf = endsinArr(rv_txt, ['amment'])) != '') { token = token.slice(0, -suf.length) + 'ant'; // replace by ant doStep2a = true; } else if ((suf = endsinArr(rv_txt, ['emment'])) != '') { token = token.slice(0, -suf.length) + 'ent'; // replace by ent doStep2a = true; } else if ((suf = endsinArr(rv_txt, ['ment', 'ments'])) != '') { // letter before must be a vowel in RV letterBefore = token[token.length - suf.length - 1]; if (isVowel(letterBefore) && endsin(rv_txt, letterBefore + suf)) { token = token.slice(0, -suf.length); // delete doStep2a = true; } } // re compute regions r1_txt = token.substring(regs.r1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); // Step 2a var beforeStep2a = token; var step2aDone = false; if (beforeStep1 === token || doStep2a) { step2aDone = true; if ((suf = endsinArr(rv_txt, ['îmes', 'ît', 'îtes', 'i', 'ie', 'Ie', 'ies', 'ir', 'ira', 'irai', 'iraIent', 'irais', 'irait', 'iras', 'irent', 'irez', 'iriez', 'irions', 'irons', 'iront', 'is', 'issaIent', 'issais', 'issait', 'issant', 'issante', 'issantes', 'issants', 'isse', 'issent', 'isses', 'issez', 'issiez', 'issions', 'issons', 'it'])) != '') { letterBefore = token[token.length - suf.length - 1]; if (!isVowel(letterBefore) && endsin(rv_txt, letterBefore + suf)) token = token.slice(0, -suf.length); // delete } } // Step 2b if (step2aDone && token === beforeStep2a) { if ((suf = endsinArr(rv_txt, ['é', 'ée', 'ées', 'és', 'èrent', 'er', 'era', 'erai', 'eraIent', 'erais', 'erait', 'eras', 'erez', 'eriez', 'erions', 'erons', 'eront', 'ez', 'iez', 'Iez'])) != '') { token = token.slice(0, -suf.length); // delete r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } else if ((suf = endsinArr(rv_txt, ['ions'])) != '' && endsinArr(r2_txt, ['ions'])) { token = token.slice(0, -suf.length); // delete r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } // add 'Ie' suffix to pass test for 'évanouie' else if ((suf = endsinArr(rv_txt, ['âmes', 'ât', 'âtes', 'a', 'ai', 'aIent', 'ais', 'ait', 'ant', 'ante', 'antes', 'ants', 'as', 'asse', 'assent', 'asses', 'assiez', 'assions'])) != '') { token = token.slice(0, -suf.length); // delete letterBefore = token[token.length - 1]; if (letterBefore === 'e' && endsin(rv_txt, 'e' + suf)) token = token.slice(0, -1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } } // Step 3 if (!(token === beforeStep1)) { if (token[token.length - 1] === 'Y') token = token.slice(0, -1) + 'i'; if (token[token.length - 1] === 'ç') token = token.slice(0, -1) + 'c'; } // Step 4 else { letterBefore = token[token.length - 1]; letter2Before = token[token.length - 2]; if (letterBefore === 's' && ['a', 'i', 'o', 'u', 'è', 's'].indexOf(letter2Before) == -1) { token = token.slice(0, -1); r1_txt = token.substring(regs.r1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } if ((suf = endsinArr(r2_txt, ['ion'])) != '') { letterBefore = token[token.length - suf.length - 1]; if (letterBefore === 's' || letterBefore === 't') { token = token.slice(0, -suf.length); // delete r1_txt = token.substring(regs.r1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } } if ((suf = endsinArr(rv_txt, ['ier', 'ière', 'Ier', 'Ière'])) != '') { token = token.slice(0, -suf.length) + 'i'; // replace by i r1_txt = token.substring(regs.r1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } if ((suf = endsinArr(rv_txt, 'e')) != '') { token = token.slice(0, -suf.length); // delete r1_txt = token.substring(regs.r1); r2_txt = token.substring(regs.r2); rv_txt = token.substring(regs.rv); } if ((suf = endsinArr(rv_txt, 'ë')) != '') { if (token.slice(token.length - 3, -1) === 'gu') token = token.slice(0, -suf.length); // delete } } // Step 5 if ((suf = endsinArr(token, ['enn', 'onn', 'ett', 'ell', 'eill'])) != '') { token = token.slice(0, -1); // delete last letter } // Step 6 i = token.length - 1; while (i > 0) { if (!isVowel(token[i])) { i--; } else if (i !== token.length - 1 && (token[i] === 'é' || token[i] === 'è')) { token = token.substring(0, i) + 'e' + token.substring(i + 1, token.length); break; } else { break; } } return token.toLowerCase(); }; /** * Compute r1, r2, rv regions as required by french porter stemmer algorithm * @param {String} token Word to compute regions on * @return {Object} Regions r1, r2, rv as offsets from the begining of the word */ function regions(token) { var r1, r2, rv, len; var i; r1 = r2 = rv = len = token.length; // R1 is the region after the first non-vowel following a vowel, for (var i = 0; i < len - 1 && r1 == len; i++) { if (isVowel(token[i]) && !isVowel(token[i + 1])) { r1 = i + 2; } } // Or is the null region at the end of the word if there is no such non-vowel. // R2 is the region after the first non-vowel following a vowel in R1 for (i = r1; i < len - 1 && r2 == len; i++) { if (isVowel(token[i]) && !isVowel(token[i + 1])) { r2 = i + 2; } } // Or is the null region at the end of the word if there is no such non-vowel. // RV region var three = token.slice(0, 3); if (isVowel(token[0]) && isVowel(token[1])) { rv = 3; } if (three === 'par' || three == 'col' || three === 'tap') rv = 3; // the region after the first vowel not at the beginning of the word or null else { for (i = 1; i < len - 1 && rv == len; i++) { if (isVowel(token[i])) { rv = i + 1; } } } return { r1: r1, r2: r2, rv: rv }; }; /** * Pre-process/prepare words as required by french porter stemmer algorithm * @param {String} token Word to be prepared * @return {String} Prepared word */ function prelude(token) { token = token.toLowerCase(); var result = ''; var i = 0; // special case for i = 0 to avoid '-1' index if (token[i] === 'y' && isVowel(token[i + 1])) { result += token[i].toUpperCase(); } else { result += token[i]; } for (i = 1; i < token.length; i++) { if ((token[i] === 'u' || token[i] === 'i') && isVowel(token[i - 1]) && isVowel(token[i + 1])) { result += token[i].toUpperCase(); } else if (token[i] === 'y' && (isVowel(token[i - 1]) || isVowel(token[i + 1]))) { result += token[i].toUpperCase(); } else if (token[i] === 'u' && token[i - 1] === 'q') { result += token[i].toUpperCase(); } else { result += token[i]; } } return result; }; /** * Return longest matching suffixes for a token or '' if no suffix match * @param {String} token Word to find matching suffix * @param {Array} suffixes Array of suffixes to test matching * @return {String} Longest found matching suffix or '' */ function endsinArr(token, suffixes) { var i, longest = ''; for (i = 0; i < suffixes.length; i++) { if (endsin(token, suffixes[i]) && suffixes[i].length > longest.length) longest = suffixes[i]; } return longest; }; function isVowel(letter) { return (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u' || letter == 'y' || letter == 'â' || letter == 'à' || letter == 'ë' || letter == 'é' || letter == 'ê' || letter == 'è' || letter == 'ï' || letter == 'î' || letter == 'ô' || letter == 'û' || letter == 'ù'); }; function endsin(token, suffix) { if (token.length < suffix.length) return false; return (token.slice(-suffix.length) == suffix); };
version https://git-lfs.github.com/spec/v1 oid sha256:e961bba7ca604871f5a24ac42a19593820bdb3163d6c9b921aca5d58ad66baf2 size 195155
// Zepto.cookie plugin // // Copyright (c) 2010, 2012 // @author Klaus Hartl (stilbuero.de) // @author Daniel Lacy (daniellacy.com) // // Dual licensed under the MIT and GPL licenses: // http://www.opensource.org/licenses/mit-license.php // http://www.gnu.org/licenses/gpl.html (function (a) { a.extend(a.fn, {cookie:function (b, c, d) { var e, f, g, h; if (arguments.length > 1 && String(c) !== "[object Object]") { d = a.extend({}, d); if (c === null || c === undefined)d.expires = -1; return typeof d.expires == "number" && (e = d.expires * 24 * 60 * 60 * 1e3, f = d.expires = new Date, f.setTime(f.getTime() + e)), c = String(c), document.cookie = [encodeURIComponent(b), "=", d.raw ? c : encodeURIComponent(c), d.expires ? "; expires=" + d.expires.toUTCString() : "", d.path ? "; path=" + d.path : "", d.domain ? "; domain=" + d.domain : "", d.secure ? "; secure" : ""].join("") } return d = c || {}, h = d.raw ? function (a) { return a } : decodeURIComponent, (g = (new RegExp("(?:^|; )" + encodeURIComponent(b) + "=([^;]*)")).exec(document.cookie)) ? h(g[1]) : null }}) })(Zepto);
module.exports = Cmds.addCommand({ cmds: [";username "], requires: { guild: false, loud: false }, desc: "Set VaeBot's username", args: "[username]", example: "VaeBot9000", /////////////////////////////////////////////////////////////////////////////////////////// func: (cmd, args, msgObj, speaker, channel, guild) => { client.user.setUsername(args) .catch(console.error); Util.print(channel, "Set username to " + args); } });
//userinfo jQuery('.user-info').click(function(){ if(!jQuery(this).hasClass('user-active')) { var $userInfo = jQuery(this); var $userDrop = jQuery('.user-dropbox'); $userDrop.slideDown('fast'); $userInfo.addClass('user-active'); //add class to change color and background } else { console.log('has class'); jQuery(this).removeClass('user-active'); jQuery('.user-dropbox').hide(); } //remove notification box if visible jQuery('.notification-counter').removeClass('notification-active'); jQuery('.notification-box').hide(); jQuery('#triangle-down').show(); return false; }); //notification onclick jQuery('.notification-counter').click(function(){ var $counter = jQuery(this); if(!$counter.hasClass('notification-active')) { $counter.addClass('notification-active'); jQuery('#triangle-down').hide(); jQuery('.notification-box').slideDown('fast'); //show notification box } else { $counter.removeClass('notification-active'); jQuery('#triangle-down').show(); jQuery('.notification-box').hide(); } //this will hide user info drop down when visible jQuery('.user-info').removeClass('user-active'); jQuery('.user-dropbox').hide(); return false; }); $(document).mouseup(function(e) { if(jQuery(e.target).parents().index() < 4 || jQuery(e.target).parents().index() > 11){ jQuery('.notification-counter').removeClass('notification-active'); jQuery('.notification-box').hide(); jQuery('.user-info').removeClass('user-active'); jQuery('.user-dropbox').hide(); jQuery('#triangle-down').show(); } }); // Widget hover event // show arrow image in the right side of the title upon hover jQuery('.utopia-widget-title').hover(function(){ jQuery(this).after().append('<span class="collapse-widget">&nbsp;&nbsp;</span>'); }, function(){ jQuery(this).children('.collapse-widget').remove() }); //show/hide widget content when widget title is clicked jQuery('.utopia-widget-title').click(function(){ if(jQuery(this).next().is(':visible')) { console.log(this); jQuery(this).next().slideUp('fast'); jQuery(this).addClass('utopia-widget-title-toggle'); } else { jQuery(this).next().slideDown('fast'); jQuery(this).removeClass('utopia-widget-title-toggle'); } }); jQuery('.search-panel').hover(function(){ jQuery('.search-box img').hide(); jQuery('.search-box form').show(); }, function(){ jQuery('.search-box form').hide(); jQuery('.search-box img').show(); });
/* outputPath: dist */ /* global $ */ /* global hasher */ /* global crossroads */ var controllers = []; var Controller = function (name, config) { //console.log('Initializing New Controller', name); config.init(); var me = this; me.name = name; me.listeners = config.listeners; for (var item in me.listeners) { for (var event in config.listeners[item]) { $(document).on(event, item, config.listeners[item][event]); } } for (var func in config) { if (func !== 'listeners') { me[func] = config[func]; } } if (me.hashes !== undefined) { for (var hashMap in me.hashes) { crossroads.addRoute(hashMap, me.hashes[hashMap].bind(me)); } var parseHash = function (newHash, oldHash) { crossroads.parse(newHash); }; if (config.prependHash !== undefined) { hasher.prependHash = config.prependHash; } else { hasher.prependHash = '!'; } hasher.initialized.add(parseHash); hasher.changed.add(parseHash); if (config.hasherInit !== false) { hasher.init(); } } controllers.push(me); };
/** * @license * Lodash <https://lodash.com/> * Copyright JS Foundation and other contributors <https://js.foundation/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.1'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array of at least `200` elements * and any iteratees accept only one argument. The heuristic for whether a * section qualifies for shortcut fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB). Change the following template settings to use * alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * Used by `_.defaults` to customize its `_.assignIn` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function assignInDefaults(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } value = Object(value); return (symToStringTag && symToStringTag in value) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { object = Object(object); return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, path, value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { var path = castPath(index, array), object = parent(array, path); if (object != null) { delete object[toKey(last(path))]; } } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array == null ? 0 : array.length, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); var key = toKey(last(path)); return !(object != null && hasOwnProperty.call(object, key)) || delete object[key]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = nativeMin(toInteger(precision), 292); if (precision) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] == null ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function mergeDefaults(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, mergeDefaults, stack); stack['delete'](srcValue); } return objValue; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @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, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @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, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false}, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * 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 _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], lastIndex = args.length - 1, otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } if (start != lastIndex) { arrayPush(otherArgs, castSlice(args, start + 1)); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are **not** supported. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @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 == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, assignInDefaults); return apply(assignInWith, undefined, args); }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, mergeDefaults); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var bitmask = CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG; paths = arrayMap(paths, function(path) { path = castPath(path, object); bitmask |= (path.length > 1 ? CLONE_DEEP_FLAG : 0); return path; }); copyObject(object, getAllKeysIn(object), result); result = baseClone(result, bitmask); var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { object = undefined; length = 1; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, assignInDefaults); var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] 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 mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.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); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { var filtered = this.__filtered__; if (filtered && !index) { return new LazyWrapper(this); } n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = this.clone(); if (filtered) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = (lodashFunc.name + ''), names = realNames[key] || (realNames[key] = []); names.push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }); /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. define(function() { return _; }); } // Check for `exports` after `define` in case a build optimizer adds it. else if (freeModule) { // Export for Node.js. (freeModule.exports = _)._ = _; // Export for CommonJS support. freeExports._ = _; } else { // Export to the global object. root._ = _; } }.call(this));
"use babel"; // @flow import * as React from "react"; import Radium from "radium"; import QuestionMessage from "./QuestionMessage"; import type { ComplexChoice, Step } from "../Types/types"; export default Radium( ({ message, decline = { value: false, description: "No" }, accept = { value: true, description: "Yes" }, onNext, step, ...props }: { message: string, decline: ComplexChoice, accept: ComplexChoice, onNext: (answer: any) => void, step: Step, }) => ( <div style={{ display: "flex", flex: "1", flexDirection: "column", justifyContent: "center", alignItems: "strech", }} > <div style={{ display: "flex", justifyContent: "center" }}> <QuestionMessage>{message}</QuestionMessage> </div> <div style={{ display: "flex", justifyContent: "center" }}> {step == "validation" ? ( <span className="loading loading-spinner-small inline-block" /> ) : ( <span> <button className="btn btn-info inline-block-tight native-key-bindings" onKeyPress={e => e.key == "Enter" && onNext(false)} onClick={() => onNext(decline.value)} autoFocus={props.default && props.default.value == decline.value} > {decline.description} </button> <button className="btn btn-success inline-block-tight native-key-bindings" onClick={() => onNext(accept.value)} autoFocus={ (props.default && props.default.value == accept.value) || (props.default && props.default.value === undefined) } > {accept.description} </button> </span> )} </div> </div> ), );
// @flow import uuid from "uuid"; import v1 from "uuid/v1"; import v3 from "uuid/v3"; import v4 from "uuid/v4"; import v5 from "uuid/v5"; (uuid.v1(): string); (uuid.v4(): string); (uuid(): string); (v1(): string); (v4(): string); (v3(): string); (v5(): string); uuid.v1({ node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], clockseq: 0x1234, msecs: new Date("2011-11-01").getTime(), nsecs: 5678 }); v1({ node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], clockseq: 0x1234, msecs: new Date("2011-11-01").getTime(), nsecs: 5678 }); // $FlowExpectedError uuid.v1({ yolo: true }); // $FlowExpectedError v1({ yolo: true }); // $FlowExpectedError uuid.v4({ yolo: true }); // $FlowExpectedError v4({ yolo: true }); // $FlowExpectedError v3({ yolo: true }); // $FlowExpectedError v5({ yolo: true }); const arr = new Array(32); uuid.v4({ random: [ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 ] }); v4({ random: [ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 ] }); uuid.v4({ // Fake random number generator rng: () => [ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 ] }); v4({ // Fake random number generator rng: () => [ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 ] }); uuid.v4({ // Fake random number generator rng: () => Buffer.alloc(16) }); v4({ // Fake random number generator rng: () => Buffer.alloc(16) }); // $FlowExpectedError uuid.v4({ rng: () => "bla" }); // $FlowExpectedError v4({ rng: () => "bla" }); v3.name; v3("bla"); v3("bla", "bla"); v3("bla", v3.DNS); v3("bla", v3.URL); v3([0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea]); v3( [0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea], [0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36] ); // $FlowExpectedError v3("bla", { yolo: true }); v5.name; v5("bla"); v5("bla", "bla"); v5("bla", v5.DNS); v5("bla", v5.URL); v5([0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea]); v5( [0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea], [0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36] ); // $FlowExpectedError v5("bla", { yolo: true });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z" }), 'PresentToAllOutlined'); exports.default = _default;
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M12 18c3.31 0 6-2.69 6-6s-2.69-6-6-6-6 2.69-6 6 2.69 6 6 6z", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "M12 20c4.42 0 8-3.58 8-8s-3.58-8-8-8-8 3.58-8 8 3.58 8 8 8zm0-14c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6 2.69-6 6-6z" }, "1")], 'FiberManualRecordTwoTone');
/** @jsx React.DOM */ // https://github.com/rogerwang/node-webkit/issues/1188#issuecomment-26002789 // https://github.com/substack/node-browserify/issues/481 // https://github.com/greypants/gulp-starter/issues/17 // http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/ // https://github.com/joyent/node/issues/2479 var React = require("react/addons"); var Header = require("ui/components/app/header.react"); var Main = require("ui/components/app/main.react"); var Popups = require("ui/components/app/popups.react"); var $ = require("jquery"); var _ = require("lodash"); var LayoutEngine = require("ui/core/layout/layoutengine"); var LayoutDefinitions = require("ui/core/layout/layoutdefinitions"); var AppContext = require("ui/core/appcontext"); var ChartActions = require("ui/core/actions/chartactions"); // TODO: move to unit tests /*function testAtom () { console.log(AppContext.stores.chartStore.getTicker()); console.log(AppContext.stores.chartStore.getTimeframe()); console.log(AppContext.stores.chartStore.getDuration()); AppContext.publishCommand(new AtomCommand( AtomCommand.commands.CHART_UPDATE_TICKER, {ticker: "GOOGL"} )); console.log(AppContext.stores.chartStore.getTicker()); AppContext.publishBatchCommands([ new AtomCommand( AtomCommand.commands.CHART_UPDATE_TICKER, {ticker: "IBM"} ), new AtomCommand( AtomCommand.commands.CHART_UPDATE_TIMEFRAME, {timeframe: {from: new Date(), to: new Date()}} ), new AtomCommand( AtomCommand.commands.CHART_UPDATE_DURATION, {duration: "weekly"} ) ]); console.log(AppContext.stores.chartStore.getTicker()); console.log(AppContext.stores.chartStore.getTimeframe()); console.log(AppContext.stores.chartStore.getDuration()); AppContext.publishCommand(new AtomCommand( AtomCommand.commands.APP_TOGGLE_TIMEFRAME_OPTIONS, {show: true, rect: {top: 50, left: 100}} )); AppContext.publishCommand(new AtomCommand( AtomCommand.commands.APP_TOGGLE_DURATION_OPTIONS, {show: true, rect: {top: 150, left: 400}} )); }*/ /*function testActions() { ChartActions.updateTicker("ibm"); }*/ var AppRoot = React.createClass({ render: function() { var windowRect = AppContext.getWindowRect(); var appStyle = { position: 'absolute', width: windowRect.width + "px", height: windowRect.height + "px", top: windowRect.top + "px", left: windowRect.left + "px", overflow: 'hidden' }; return ( <section id="application" style={appStyle}> <Header/> <Main/> <Popups/> </section> ); } }); module.exports = { init: function() { LayoutDefinitions.init(); AppContext.init(AppRoot, $("#root")[0]); this.attachEvents(); this.renderApp(); ChartActions.updateTicker("spy"); //testAtom(); //testActions(); }, renderApp: function () { LayoutEngine.resolveLayouts(); AppContext.renderAtomState(); }, attachEvents: function () { var self = this; $(window).bind("resize", _.debounce(function() { self.renderApp(); }, 200)); } };
class MyRouter { constructor() { //we use array to push all url that we have this._routes = []; } on(url, callback) { //push the url and the callback in the array; //return this gives the ability to chain this._routes.push({ targetUrl: url, callback: callback }); return this; } navigate() { //this removes the # from the url const currentUrl = location.hash.slice(2); for (const { targetUrl, callback } of this._routes) { const params = MyRouter.matchUrls(currentUrl, targetUrl); if (params) { callback(params); break; } } } //check if onUrl and the current url match static matchUrls(currentUrl, targetUrl) { //split currentUrl on / const currentUrlWords = currentUrl.split(/\//g); //split targetUrl on / const targetUrlWord = targetUrl.split(/\//g); //if target and current are with differen length return false -> no match if (targetUrlWord.length !== currentUrlWords.length) { return false; } //params wich we need const params = {}; const len = currentUrlWords.length; //we need to check every word from both target and current url for match //if all match we will return params if any else will return empty object for (let i = 0; i < len; i += 1) { if (targetUrlWord[i][0] !== ':') { if (currentUrlWords[i] !== targetUrlWord[i]) { return false; } } else { const paramName = targetUrlWord[i].slice(1); params[paramName] = decodeURIComponent(currentUrlWords[i]); } } return params; } } export { MyRouter };
module.exports = { name: 'Firefox', DEFAULT_CMD: { linux: ['firefox'], darwin: ['/Applications/Firefox.app/Contents/MacOS/firefox-bin'], win32: [ process.env.LOCALAPPDATA + '\\Mozilla Firefox\\firefox.exe', process.env.ProgramW6432 + '\\Mozilla Firefox\\firefox.exe', process.env.ProgramFiles + '\\Mozilla Firefox\\firefox.exe', process.env['ProgramFiles(x86)'] + '\\Mozilla Firefox\\firefox.exe' ] }, ENV_CMD: 'FIREFOX_BIN' };
var b = "hello b" ;
'use strict'; define( function ( require ) { var UsersAdminCtrl = require( 'users/UsersAdminCtrl' ); var UsersBaseCtrl = require( 'users/UsersBaseCtrl' ); var UsersCreateCtrl = require( 'users/UsersCreateCtrl' ); var UsersDetailsCtrl = require( 'users/UsersDetailsCtrl' ); var UsersRouter = require( 'users/UsersRouter' ); var UsersService = require( 'users/UsersService' ); var UsersModule = angular.module( 'UsersModule', []); UsersModule.config([ '$stateProvider', UsersRouter ]); UsersModule.controller( 'UsersAdminCtrl', [ '$scope', 'UsersService', UsersAdminCtrl ]); UsersModule.controller( 'UsersBaseCtrl', [ '$scope', UsersBaseCtrl ]); UsersModule.controller( 'UsersCreateCtrl', [ '$scope', 'UsersService', UsersCreateCtrl ]); UsersModule.controller( 'UsersDetailsCtrl', [ '$scope', '$stateParams', 'UsersService', UsersDetailsCtrl ]); UsersModule.factory( 'UsersService', [ 'BaseService', UsersService ]); });
/*jshint newcap:false*/ import CollectionView from "ember-views/views/collection_view"; import EmberObject from "ember-runtime/system/object"; import EmberView from "ember-views/views/view"; import ArrayProxy from "ember-runtime/system/array_proxy"; import Namespace from "ember-runtime/system/namespace"; import { Registry } from "ember-runtime/system/container"; import { A } from "ember-runtime/system/native_array"; import run from "ember-metal/run_loop"; import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import jQuery from "ember-views/system/jquery"; import { computed } from "ember-metal/computed"; import { runAppend, runDestroy } from "ember-runtime/tests/utils"; import compile from "ember-template-compiler/system/compile"; var trim = jQuery.trim; var view; var originalLookup = Ember.lookup; var TemplateTests, registry, container, lookup; function nthChild(view, nth) { return get(view, 'childViews').objectAt(nth || 0); } var firstChild = nthChild; function firstGrandchild(view) { return get(get(view, 'childViews').objectAt(0), 'childViews').objectAt(0); } QUnit.module("collection helper", { setup() { Ember.lookup = lookup = {}; lookup.TemplateTests = TemplateTests = Namespace.create(); registry = new Registry(); container = registry.container(); registry.optionsForType('template', { instantiate: false }); // registry.register('view:default', _MetamorphView); registry.register('view:toplevel', EmberView.extend()); }, teardown() { runDestroy(container); runDestroy(view); registry = container = view = null; Ember.lookup = lookup = originalLookup; TemplateTests = null; } }); QUnit.test("Collection views that specify an example view class have their children be of that class", function() { var ExampleViewCollection = CollectionView.extend({ itemViewClass: EmberView.extend({ isCustom: true }), content: A(['foo']) }); view = EmberView.create({ exampleViewCollection: ExampleViewCollection, template: compile('{{#collection view.exampleViewCollection}}OHAI{{/collection}}') }); runAppend(view); ok(firstGrandchild(view).isCustom, "uses the example view class"); }); QUnit.test("itemViewClass works in the #collection helper with a global (DEPRECATED)", function() { TemplateTests.ExampleItemView = EmberView.extend({ isAlsoCustom: true }); view = EmberView.create({ exampleController: ArrayProxy.create({ content: A(['alpha']) }), template: compile('{{#collection content=view.exampleController itemViewClass=TemplateTests.ExampleItemView}}beta{{/collection}}') }); var deprecation = /Global lookup of TemplateTests.ExampleItemView from a Handlebars template is deprecated/; expectDeprecation(function() { runAppend(view); }, deprecation); ok(firstGrandchild(view).isAlsoCustom, "uses the example view class specified in the #collection helper"); }); QUnit.test("itemViewClass works in the #collection helper with a property", function() { var ExampleItemView = EmberView.extend({ isAlsoCustom: true }); var ExampleCollectionView = CollectionView; view = EmberView.create({ possibleItemView: ExampleItemView, exampleCollectionView: ExampleCollectionView, exampleController: ArrayProxy.create({ content: A(['alpha']) }), template: compile('{{#collection view.exampleCollectionView content=view.exampleController itemViewClass=view.possibleItemView}}beta{{/collection}}') }); runAppend(view); ok(firstGrandchild(view).isAlsoCustom, "uses the example view class specified in the #collection helper"); }); QUnit.test("itemViewClass works in the #collection via container", function() { registry.register('view:example-item', EmberView.extend({ isAlsoCustom: true })); view = EmberView.create({ container: container, exampleCollectionView: CollectionView.extend(), exampleController: ArrayProxy.create({ content: A(['alpha']) }), template: compile('{{#collection view.exampleCollectionView content=view.exampleController itemViewClass="example-item"}}beta{{/collection}}') }); runAppend(view); ok(firstGrandchild(view).isAlsoCustom, "uses the example view class specified in the #collection helper"); }); QUnit.test("passing a block to the collection helper sets it as the template for example views", function() { var CollectionTestView = CollectionView.extend({ tagName: 'ul', content: A(['foo', 'bar', 'baz']) }); view = EmberView.create({ collectionTestView: CollectionTestView, template: compile('{{#collection view.collectionTestView}} <label></label> {{/collection}}') }); runAppend(view); equal(view.$('label').length, 3, 'one label element is created for each content item'); }); QUnit.test("collection helper should try to use container to resolve view", function() { var registry = new Registry(); var container = registry.container(); var ACollectionView = CollectionView.extend({ tagName: 'ul', content: A(['foo', 'bar', 'baz']) }); registry.register('view:collectionTest', ACollectionView); var controller = { container: container }; view = EmberView.create({ controller: controller, template: compile('{{#collection "collectionTest"}} <label></label> {{/collection}}') }); runAppend(view); equal(view.$('label').length, 3, 'one label element is created for each content item'); }); QUnit.test("collection helper should accept relative paths", function() { view = EmberView.create({ template: compile('{{#collection view.collection}} <label></label> {{/collection}}'), collection: CollectionView.extend({ tagName: 'ul', content: A(['foo', 'bar', 'baz']) }) }); runAppend(view); equal(view.$('label').length, 3, 'one label element is created for each content item'); }); QUnit.test("empty views should be removed when content is added to the collection (regression, ht: msofaer)", function() { var EmptyView = EmberView.extend({ template : compile("<td>No Rows Yet</td>") }); var ListView = CollectionView.extend({ emptyView: EmptyView }); var listController = ArrayProxy.create({ content : A() }); view = EmberView.create({ listView: ListView, listController: listController, template: compile('{{#collection view.listView content=view.listController tagName="table"}} <td>{{view.content.title}}</td> {{/collection}}') }); runAppend(view); equal(view.$('tr').length, 1, 'Make sure the empty view is there (regression)'); run(function() { listController.pushObject({ title : "Go Away, Placeholder Row!" }); }); equal(view.$('tr').length, 1, 'has one row'); equal(view.$('tr:nth-child(1) td').text(), 'Go Away, Placeholder Row!', 'The content is the updated data.'); }); QUnit.test("should be able to specify which class should be used for the empty view", function() { var App; run(function() { lookup.App = App = Namespace.create(); }); var EmptyView = EmberView.extend({ template: compile('This is an empty view') }); view = EmberView.create({ container: { lookupFactory() { return EmptyView; } }, template: compile('{{collection emptyViewClass="empty-view"}}') }); runAppend(view); equal(view.$().text(), 'This is an empty view', "Empty view should be rendered."); runDestroy(App); }); QUnit.test("if no content is passed, and no 'else' is specified, nothing is rendered", function() { var CollectionTestView = CollectionView.extend({ tagName: 'ul', content: A() }); view = EmberView.create({ collectionTestView: CollectionTestView, template: compile('{{#collection view.collectionTestView}} <aside></aside> {{/collection}}') }); runAppend(view); equal(view.$('li').length, 0, 'if no "else" is specified, nothing is rendered'); }); QUnit.test("if no content is passed, and 'else' is specified, the else block is rendered", function() { var CollectionTestView = CollectionView.extend({ tagName: 'ul', content: A() }); view = EmberView.create({ collectionTestView: CollectionTestView, template: compile('{{#collection view.collectionTestView}} <aside></aside> {{ else }} <del></del> {{/collection}}') }); runAppend(view); equal(view.$('li:has(del)').length, 1, 'the else block is rendered'); }); QUnit.test("a block passed to a collection helper defaults to the content property of the context", function() { var CollectionTestView = CollectionView.extend({ tagName: 'ul', content: A(['foo', 'bar', 'baz']) }); view = EmberView.create({ collectionTestView: CollectionTestView, template: compile('{{#collection view.collectionTestView}} <label>{{view.content}}</label> {{/collection}}') }); runAppend(view); equal(view.$('li:nth-child(1) label').length, 1); equal(view.$('li:nth-child(1) label').text(), 'foo'); equal(view.$('li:nth-child(2) label').length, 1); equal(view.$('li:nth-child(2) label').text(), 'bar'); equal(view.$('li:nth-child(3) label').length, 1); equal(view.$('li:nth-child(3) label').text(), 'baz'); }); QUnit.test("a block passed to a collection helper defaults to the view", function() { var CollectionTestView = CollectionView.extend({ tagName: 'ul', content: A(['foo', 'bar', 'baz']) }); view = EmberView.create({ collectionTestView: CollectionTestView, template: compile('{{#collection view.collectionTestView}} <label>{{view.content}}</label> {{/collection}}') }); runAppend(view); // Preconds equal(view.$('li:nth-child(1) label').length, 1); equal(view.$('li:nth-child(1) label').text(), 'foo'); equal(view.$('li:nth-child(2) label').length, 1); equal(view.$('li:nth-child(2) label').text(), 'bar'); equal(view.$('li:nth-child(3) label').length, 1); equal(view.$('li:nth-child(3) label').text(), 'baz'); run(function() { set(firstChild(view), 'content', A()); }); equal(view.$('label').length, 0, "all list item views should be removed from DOM"); }); QUnit.test("should include an id attribute if id is set in the options hash", function() { var CollectionTestView = CollectionView.extend({ tagName: 'ul', content: A(['foo', 'bar', 'baz']) }); view = EmberView.create({ collectionTestView: CollectionTestView, template: compile('{{#collection view.collectionTestView id="baz"}}foo{{/collection}}') }); runAppend(view); equal(view.$('ul#baz').length, 1, "adds an id attribute"); }); QUnit.test("should give its item views the class specified by itemClass", function() { var ItemClassTestCollectionView = CollectionView.extend({ tagName: 'ul', content: A(['foo', 'bar', 'baz']) }); view = EmberView.create({ itemClassTestCollectionView: ItemClassTestCollectionView, template: compile('{{#collection view.itemClassTestCollectionView itemClass="baz"}}foo{{/collection}}') }); runAppend(view); equal(view.$('ul li.baz').length, 3, "adds class attribute"); }); QUnit.test("should give its item views the class specified by itemClass", function() { var ItemClassBindingTestCollectionView = CollectionView.extend({ tagName: 'ul', content: A([EmberObject.create({ isBaz: false }), EmberObject.create({ isBaz: true }), EmberObject.create({ isBaz: true })]) }); view = EmberView.create({ itemClassBindingTestCollectionView: ItemClassBindingTestCollectionView, isBar: true, template: compile('{{#collection view.itemClassBindingTestCollectionView itemClass=view.isBar}}foo{{/collection}}') }); runAppend(view); equal(view.$('ul li.is-bar').length, 3, "adds class on initial rendering"); // NOTE: in order to bind an item's class to a property of the item itself (e.g. `isBaz` above), it will be necessary // to introduce a new keyword that could be used from within `itemClassBinding`. For instance, `itemClassBinding="item.isBaz"`. }); QUnit.test("should give its item views the property specified by itemProperty", function() { var ItemPropertyBindingTestItemView = EmberView.extend({ tagName: 'li' }); // Use preserveContext=false so the itemView handlebars context is the view context // Set itemView bindings using item* view = EmberView.create({ baz: "baz", content: A([EmberObject.create(), EmberObject.create(), EmberObject.create()]), container: { lookupFactory() { return ItemPropertyBindingTestItemView; } }, template: compile('{{#collection content=view.content tagName="ul" itemViewClass="item-property-binding-test-item-view" itemProperty=view.baz preserveContext=false}}{{view.property}}{{/collection}}') }); runAppend(view); equal(view.$('ul li').length, 3, "adds 3 itemView"); view.$('ul li').each(function(i, li) { equal(jQuery(li).text(), "baz", "creates the li with the property = baz"); }); run(function() { set(view, 'baz', "yobaz"); }); equal(view.$('ul li:first').text(), "yobaz", "change property of sub view"); }); QUnit.test("should unsubscribe stream bindings", function() { view = EmberView.create({ baz: "baz", content: A([EmberObject.create(), EmberObject.create(), EmberObject.create()]), template: compile('{{#collection content=view.content itemProperty=view.baz}}{{view.property}}{{/collection}}') }); runAppend(view); var barStreamBinding = view._streamBindings['view.baz']; equal(countSubscribers(barStreamBinding), 3, "adds 3 subscribers"); run(function() { view.get('content').popObject(); }); equal(countSubscribers(barStreamBinding), 2, "removes 1 subscriber"); }); function countSubscribers(stream) { var count = 0; var subscriber = stream.subscriberHead; while (subscriber) { count++; subscriber = subscriber.next; } return count; } QUnit.test("should work inside a bound {{#if}}", function() { var testData = A([EmberObject.create({ isBaz: false }), EmberObject.create({ isBaz: true }), EmberObject.create({ isBaz: true })]); var IfTestCollectionView = CollectionView.extend({ tagName: 'ul', content: testData }); view = EmberView.create({ ifTestCollectionView: IfTestCollectionView, template: compile('{{#if view.shouldDisplay}}{{#collection view.ifTestCollectionView}}{{content.isBaz}}{{/collection}}{{/if}}'), shouldDisplay: true }); runAppend(view); equal(view.$('ul li').length, 3, "renders collection when conditional is true"); run(function() { set(view, 'shouldDisplay', false); }); equal(view.$('ul li').length, 0, "removes collection when conditional changes to false"); run(function() { set(view, 'shouldDisplay', true); }); equal(view.$('ul li').length, 3, "collection renders when conditional changes to true"); }); QUnit.test("should pass content as context when using {{#each}} helper [DEPRECATED]", function() { view = EmberView.create({ template: compile('{{#each view.releases}}Mac OS X {{version}}: {{name}} {{/each}}'), releases: A([ { version: '10.7', name: 'Lion' }, { version: '10.6', name: 'Snow Leopard' }, { version: '10.5', name: 'Leopard' } ]) }); expectDeprecation(function() { runAppend(view); }, 'Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each foo in bar}}`) instead.'); equal(view.$().text(), "Mac OS X 10.7: Lion Mac OS X 10.6: Snow Leopard Mac OS X 10.5: Leopard ", "prints each item in sequence"); }); QUnit.test("should re-render when the content object changes", function() { var RerenderTest = CollectionView.extend({ tagName: 'ul', content: A() }); view = EmberView.create({ rerenderTestView: RerenderTest, template: compile('{{#collection view.rerenderTestView}}{{view.content}}{{/collection}}') }); runAppend(view); run(function() { set(firstChild(view), 'content', A(['bing', 'bat', 'bang'])); }); run(function() { set(firstChild(view), 'content', A(['ramalamadingdong'])); }); equal(view.$('li').length, 1, "rerenders with correct number of items"); equal(trim(view.$('li:eq(0)').text()), "ramalamadingdong"); }); QUnit.test("select tagName on collection helper automatically sets child tagName to option", function() { var RerenderTest = CollectionView.extend({ content: A(['foo']) }); view = EmberView.create({ rerenderTestView: RerenderTest, template: compile('{{#collection view.rerenderTestView tagName="select"}}{{view.content}}{{/collection}}') }); runAppend(view); equal(view.$('option').length, 1, "renders the correct child tag name"); }); QUnit.test("tagName works in the #collection helper", function() { var RerenderTest = CollectionView.extend({ content: A(['foo', 'bar']) }); view = EmberView.create({ rerenderTestView: RerenderTest, template: compile('{{#collection view.rerenderTestView tagName="ol"}}{{view.content}}{{/collection}}') }); runAppend(view); equal(view.$('ol').length, 1, "renders the correct tag name"); equal(view.$('li').length, 2, "rerenders with correct number of items"); run(function() { set(firstChild(view), 'content', A(['bing', 'bat', 'bang'])); }); equal(view.$('li').length, 3, "rerenders with correct number of items"); equal(trim(view.$('li:eq(0)').text()), "bing"); }); QUnit.test("should render nested collections", function() { var registry = new Registry(); var container = registry.container(); registry.register('view:inner-list', CollectionView.extend({ tagName: 'ul', content: A(['one','two','three']) })); registry.register('view:outer-list', CollectionView.extend({ tagName: 'ul', content: A(['foo']) })); view = EmberView.create({ container: container, template: compile('{{#collection "outer-list" class="outer"}}{{content}}{{#collection "inner-list" class="inner"}}{{content}}{{/collection}}{{/collection}}') }); runAppend(view); equal(view.$('ul.outer > li').length, 1, "renders the outer list with correct number of items"); equal(view.$('ul.inner').length, 1, "the inner list exsits"); equal(view.$('ul.inner > li').length, 3, "renders the inner list with correct number of items"); }); QUnit.test("should render multiple, bound nested collections (#68)", function() { var view; run(function() { TemplateTests.contentController = ArrayProxy.create({ content: A(['foo','bar']) }); var InnerList = CollectionView.extend({ tagName: 'ul', contentBinding: 'parentView.innerListContent' }); var OuterListItem = EmberView.extend({ innerListView: InnerList, template: compile('{{#collection view.innerListView class="inner"}}{{content}}{{/collection}}{{content}}'), innerListContent: computed(function() { return A([1,2,3]); }) }); var OuterList = CollectionView.extend({ tagName: 'ul', contentBinding: 'TemplateTests.contentController', itemViewClass: OuterListItem }); view = EmberView.create({ outerListView: OuterList, template: compile('{{collection view.outerListView class="outer"}}') }); }); runAppend(view); equal(view.$('ul.outer > li').length, 2, "renders the outer list with correct number of items"); equal(view.$('ul.inner').length, 2, "renders the correct number of inner lists"); equal(view.$('ul.inner:first > li').length, 3, "renders the first inner list with correct number of items"); equal(view.$('ul.inner:last > li').length, 3, "renders the second list with correct number of items"); runDestroy(view); }); QUnit.test("should allow view objects to be swapped out without throwing an error (#78)", function() { var view, dataset, secondDataset; run(function() { TemplateTests.datasetController = EmberObject.create(); var ExampleCollectionView = CollectionView.extend({ contentBinding: 'parentView.items', tagName: 'ul', template: compile("{{view.content}}") }); var ReportingView = EmberView.extend({ exampleCollectionView: ExampleCollectionView, datasetBinding: 'TemplateTests.datasetController.dataset', readyBinding: 'dataset.ready', itemsBinding: 'dataset.items', template: compile("{{#if view.ready}}{{collection view.exampleCollectionView}}{{else}}Loading{{/if}}") }); view = ReportingView.create(); }); runAppend(view); equal(view.$().text(), "Loading", "renders the loading text when the dataset is not ready"); run(function() { dataset = EmberObject.create({ ready: true, items: A([1,2,3]) }); TemplateTests.datasetController.set('dataset', dataset); }); equal(view.$('ul > li').length, 3, "renders the collection with the correct number of items when the dataset is ready"); run(function() { secondDataset = EmberObject.create({ ready: false }); TemplateTests.datasetController.set('dataset', secondDataset); }); equal(view.$().text(), "Loading", "renders the loading text when the second dataset is not ready"); runDestroy(view); }); QUnit.test("context should be content", function() { var view; registry = new Registry(); container = registry.container(); var items = A([ EmberObject.create({ name: 'Dave' }), EmberObject.create({ name: 'Mary' }), EmberObject.create({ name: 'Sara' }) ]); registry.register('view:an-item', EmberView.extend({ template: compile("Greetings {{name}}") })); view = EmberView.create({ container: container, controller: { items: items }, template: compile('{{collection content=items itemViewClass="an-item"}}') }); runAppend(view); equal(view.$().text(), "Greetings DaveGreetings MaryGreetings Sara"); runDestroy(view); });
//>>built define({add:"\ucd94\uac00",addAuthor:"\uc791\uc131\uc790 \ucd94\uac00",addContributor:"\uc81c\uacf5\uc790 \ucd94\uac00"});
/** @jsx React.DOM */ var React = require('react'); var classSet = require('./utils/classSet'); var cloneWithProps = require('./utils/cloneWithProps'); var BootstrapMixin = require('./BootstrapMixin'); var ValidComponentChildren = require('./utils/ValidComponentChildren'); var PanelGroup = React.createClass({displayName: 'PanelGroup', mixins: [BootstrapMixin], propTypes: { collapsable: React.PropTypes.bool, activeKey: React.PropTypes.any, defaultActiveKey: React.PropTypes.any, onSelect: React.PropTypes.func }, getDefaultProps: function () { return { bsClass: 'panel-group' }; }, getInitialState: function () { var defaultActiveKey = this.props.defaultActiveKey; return { activeKey: defaultActiveKey }; }, render: function () { return this.transferPropsTo( React.DOM.div( {className:classSet(this.getBsClassSet()), onSelect:null}, ValidComponentChildren.map(this.props.children, this.renderPanel) ) ); }, renderPanel: function (child) { var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey; var props = { bsStyle: child.props.bsStyle || this.props.bsStyle, key: child.props.key, ref: child.props.ref }; if (this.props.accordion) { props.collapsable = true; props.expanded = (child.props.key === activeKey); props.onSelect = this.handleSelect; } return cloneWithProps( child, props ); }, shouldComponentUpdate: function() { // Defer any updates to this component during the `onSelect` handler. return !this._isChanging; }, handleSelect: function (key) { if (this.props.onSelect) { this._isChanging = true; this.props.onSelect(key); this._isChanging = false; } if (this.state.activeKey === key) { key = null; } this.setState({ activeKey: key }); } }); module.exports = PanelGroup;