diff --git a/requirements.txt b/requirements.txt index 96f943c..4da8573 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,8 +11,14 @@ XStatic-Angular>=1.5.8.0 # MIT License XStatic-Angular-Bootstrap>=2.2.0.0 # MIT License XStatic-Bootstrap-Datepicker>=1.3.1.0 # Apache 2.0 License XStatic-Bootstrap-SCSS>=3.3.7.1 # Apache 2.0 License +XStatic-Dagre>=0.6.4.0 # MIT License +XStatic-Dagre-D3>=0.4.17.0 # MIT License XStatic-D3>=3.5.17.0 # BSD License (3 clause) XStatic-Font-Awesome>=4.7.0.0 # SIL OFL 1.1 License, MIT License +XStatic-Graphlib>=1.0.7.0 # MIT License XStatic-jQuery>=1.8.2.1 # MIT License +XStatic-lodash>=4.16.4.1 # MIT License +XStatic-moment>=2.8.4.1 # MIT License +XStatic-Moment-Timezone>=0.5.22.0 # MIT License XStatic-smart-table>=1.4.13.2 # MIT License python-vitrageclient>=2.5.0 # Apache-2. diff --git a/vitrage_dashboard/admin_alarms/templates/adminalarms/index.html b/vitrage_dashboard/admin_alarms/templates/adminalarms/index.html index 1c73440..de49ab2 100644 --- a/vitrage_dashboard/admin_alarms/templates/adminalarms/index.html +++ b/vitrage_dashboard/admin_alarms/templates/adminalarms/index.html @@ -12,10 +12,5 @@ - - - - - {% endblock %} diff --git a/vitrage_dashboard/admin_dashboard/templates/admintopology/index.html b/vitrage_dashboard/admin_dashboard/templates/admintopology/index.html index 5a97a0d..66eaad2 100644 --- a/vitrage_dashboard/admin_dashboard/templates/admintopology/index.html +++ b/vitrage_dashboard/admin_dashboard/templates/admintopology/index.html @@ -14,10 +14,5 @@ - - - - - {% endblock %} diff --git a/vitrage_dashboard/admin_entities/templates/adminentities/index.html b/vitrage_dashboard/admin_entities/templates/adminentities/index.html index 3a43a71..d9d0047 100644 --- a/vitrage_dashboard/admin_entities/templates/adminentities/index.html +++ b/vitrage_dashboard/admin_entities/templates/adminentities/index.html @@ -12,11 +12,6 @@ - - - - - diff --git a/vitrage_dashboard/admin_templates/templates/admintemplates/index.html b/vitrage_dashboard/admin_templates/templates/admintemplates/index.html index 2b8e02c..c7ca3cb 100644 --- a/vitrage_dashboard/admin_templates/templates/admintemplates/index.html +++ b/vitrage_dashboard/admin_templates/templates/admintemplates/index.html @@ -12,8 +12,5 @@ - - - {% endblock %} diff --git a/vitrage_dashboard/alarms/templates/alarms/index.html b/vitrage_dashboard/alarms/templates/alarms/index.html index 02e2d69..6f9e993 100644 --- a/vitrage_dashboard/alarms/templates/alarms/index.html +++ b/vitrage_dashboard/alarms/templates/alarms/index.html @@ -12,10 +12,5 @@ - - - - - {% endblock %} diff --git a/vitrage_dashboard/dashboard/static/vendor/dagre-d3/dagre-d3.core.js b/vitrage_dashboard/dashboard/static/vendor/dagre-d3/dagre-d3.core.js deleted file mode 100644 index 27c0ab9..0000000 --- a/vitrage_dashboard/dashboard/static/vendor/dagre-d3/dagre-d3.core.js +++ /dev/null @@ -1,1192 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.dagreD3 = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0; - } - -},{}],14:[function(require,module,exports){ - module.exports = intersectNode; - - function intersectNode(node, point) { - return node.intersect(point); - } - -},{}],15:[function(require,module,exports){ - var intersectLine = require("./intersect-line"); - - module.exports = intersectPolygon; - - /* - * Returns the point ({x, y}) at which the point argument intersects with the - * node argument assuming that it has the shape specified by polygon. - */ - function intersectPolygon(node, polyPoints, point) { - var x1 = node.x; - var y1 = node.y; - - var intersections = []; - - var minX = Number.POSITIVE_INFINITY, - minY = Number.POSITIVE_INFINITY; - polyPoints.forEach(function(entry) { - minX = Math.min(minX, entry.x); - minY = Math.min(minY, entry.y); - }); - - var left = x1 - node.width / 2 - minX; - var top = y1 - node.height / 2 - minY; - - for (var i = 0; i < polyPoints.length; i++) { - var p1 = polyPoints[i]; - var p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0]; - var intersect = intersectLine(node, point, - {x: left + p1.x, y: top + p1.y}, {x: left + p2.x, y: top + p2.y}); - if (intersect) { - intersections.push(intersect); - } - } - - if (!intersections.length) { - console.log("NO INTERSECTION FOUND, RETURN NODE CENTER", node); - return node; - } - - if (intersections.length > 1) { - // More intersections, find the one nearest to edge end point - intersections.sort(function(p, q) { - var pdx = p.x - point.x, - pdy = p.y - point.y, - distp = Math.sqrt(pdx * pdx + pdy * pdy), - - qdx = q.x - point.x, - qdy = q.y - point.y, - distq = Math.sqrt(qdx * qdx + qdy * qdy); - - return (distp < distq) ? -1 : (distp === distq ? 0 : 1); - }); - } - return intersections[0]; - } - -},{"./intersect-line":13}],16:[function(require,module,exports){ - module.exports = intersectRect; - - function intersectRect(node, point) { - var x = node.x; - var y = node.y; - - // Rectangle intersection algorithm from: - // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes - var dx = point.x - x; - var dy = point.y - y; - var w = node.width / 2; - var h = node.height / 2; - - var sx, sy; - if (Math.abs(dy) * w > Math.abs(dx) * h) { - // Intersection is top or bottom of rect. - if (dy < 0) { - h = -h; - } - sx = dy === 0 ? 0 : h * dx / dy; - sy = h; - } else { - // Intersection is left or right of rect. - if (dx < 0) { - w = -w; - } - sx = w; - sy = dx === 0 ? 0 : w * dy / dx; - } - - return {x: x + sx, y: y + sy}; - } - -},{}],17:[function(require,module,exports){ - var util = require("../util"); - - module.exports = addHtmlLabel; - - function addHtmlLabel(root, node) { - var fo = root - .append("foreignObject") - .attr("width", "100000"); - - var div = fo - .append("xhtml:div"); - div.attr("xmlns", "http://www.w3.org/1999/xhtml"); - - var label = node.label; - switch(typeof label) { - case "function": - div.insert(label); - break; - case "object": - // Currently we assume this is a DOM object. - div.insert(function() { return label; }); - break; - default: div.html(label); - } - - util.applyStyle(div, node.labelStyle); - div.style("display", "inline-block"); - // Fix for firefox - div.style("white-space", "nowrap"); - - var client = div[0][0].getBoundingClientRect(); - fo - .attr("width", client.width) - .attr("height", client.height); - - return fo; - } - -},{"../util":27}],18:[function(require,module,exports){ - var addTextLabel = require("./add-text-label"), - addHtmlLabel = require("./add-html-label"), - addSVGLabel = require("./add-svg-label"); - - module.exports = addLabel; - - function addLabel(root, node, location) { - var label = node.label; - var labelSvg = root.append("g"); - - // Allow the label to be a string, a function that returns a DOM element, or - // a DOM element itself. - if (node.labelType === "svg") { - addSVGLabel(labelSvg, node); - } else if (typeof label !== "string" || node.labelType === "html") { - addHtmlLabel(labelSvg, node); - } else { - addTextLabel(labelSvg, node); - } - - var labelBBox = labelSvg.node().getBBox(); - var y; - switch(location) { - case "top": - y = (-node.height / 2); - break; - case "bottom": - y = (node.height / 2) - labelBBox.height; - break; - default: - y = (-labelBBox.height / 2); - } - labelSvg.attr("transform", - "translate(" + (-labelBBox.width / 2) + "," + y + ")"); - - return labelSvg; - } - -},{"./add-html-label":17,"./add-svg-label":19,"./add-text-label":20}],19:[function(require,module,exports){ - var util = require("../util"); - - module.exports = addSVGLabel; - - function addSVGLabel(root, node) { - var domNode = root; - - domNode.node().appendChild(node.label); - - util.applyStyle(domNode, node.labelStyle); - - return domNode; - } - -},{"../util":27}],20:[function(require,module,exports){ - var util = require("../util"); - - module.exports = addTextLabel; - - /* - * Attaches a text label to the specified root. Handles escape sequences. - */ - function addTextLabel(root, node) { - var domNode = root.append("text"); - - var lines = processEscapeSequences(node.label).split("\n"); - for (var i = 0; i < lines.length; i++) { - domNode - .append("tspan") - .attr("xml:space", "preserve") - .attr("dy", "1em") - .attr("x", "1") - .text(lines[i]); - } - - util.applyStyle(domNode, node.labelStyle); - - return domNode; - } - - function processEscapeSequences(text) { - var newText = "", - escaped = false, - ch; - for (var i = 0; i < text.length; ++i) { - ch = text[i]; - if (escaped) { - switch(ch) { - case "n": newText += "\n"; break; - default: newText += ch; - } - escaped = false; - } else if (ch === "\\") { - escaped = true; - } else { - newText += ch; - } - } - return newText; - } - -},{"../util":27}],21:[function(require,module,exports){ - /* global window */ - - var lodash; - - if (require) { - try { - lodash = require("lodash"); - } catch (e) {} - } - - if (!lodash) { - lodash = window._; - } - - module.exports = lodash; - -},{"lodash":undefined}],22:[function(require,module,exports){ - "use strict"; - - var util = require("./util"), - d3 = require("./d3"); - - module.exports = positionClusters; - - function positionClusters(selection, g) { - var created = selection.filter(function() { return !d3.select(this).classed("update"); }); - - function translate(v) { - var node = g.node(v); - return "translate(" + node.x + "," + node.y + ")"; - } - - created.attr("transform", translate); - - util.applyTransition(selection, g) - .style("opacity", 1) - .attr("transform", translate); - - util.applyTransition(created.selectAll("rect"), g) - .attr("width", function(v) { return g.node(v).width; }) - .attr("height", function(v) { return g.node(v).height; }) - .attr("x", function(v) { - var node = g.node(v); - return -node.width / 2; - }) - .attr("y", function(v) { - var node = g.node(v); - return -node.height / 2; - }); - - } - -},{"./d3":7,"./util":27}],23:[function(require,module,exports){ - "use strict"; - - var util = require("./util"), - d3 = require("./d3"), - _ = require("./lodash"); - - module.exports = positionEdgeLabels; - - function positionEdgeLabels(selection, g) { - var created = selection.filter(function() { return !d3.select(this).classed("update"); }); - - function translate(e) { - var edge = g.edge(e); - return _.has(edge, "x") ? "translate(" + edge.x + "," + edge.y + ")" : ""; - } - - created.attr("transform", translate); - - util.applyTransition(selection, g) - .style("opacity", 1) - .attr("transform", translate); - } - -},{"./d3":7,"./lodash":21,"./util":27}],24:[function(require,module,exports){ - "use strict"; - - var util = require("./util"), - d3 = require("./d3"); - - module.exports = positionNodes; - - function positionNodes(selection, g) { - var created = selection.filter(function() { return !d3.select(this).classed("update"); }); - - function translate(v) { - var node = g.node(v); - return "translate(" + node.x + "," + node.y + ")"; - } - - created.attr("transform", translate); - - util.applyTransition(selection, g) - .style("opacity", 1) - .attr("transform", translate); - } - -},{"./d3":7,"./util":27}],25:[function(require,module,exports){ - var _ = require("./lodash"), - layout = require("./dagre").layout; - - module.exports = render; - -// This design is based on http://bost.ocks.org/mike/chart/. - function render() { - var createNodes = require("./create-nodes"), - createClusters = require("./create-clusters"), - createEdgeLabels = require("./create-edge-labels"), - createEdgePaths = require("./create-edge-paths"), - positionNodes = require("./position-nodes"), - positionEdgeLabels = require("./position-edge-labels"), - positionClusters = require("./position-clusters"), - shapes = require("./shapes"), - arrows = require("./arrows"); - - var fn = function(svg, g) { - preProcessGraph(g); - - var outputGroup = createOrSelectGroup(svg, "output"), - clustersGroup = createOrSelectGroup(outputGroup, "clusters"), - edgePathsGroup = createOrSelectGroup(outputGroup, "edgePaths"), - edgeLabels = createEdgeLabels(createOrSelectGroup(outputGroup, "edgeLabels"), g), - nodes = createNodes(createOrSelectGroup(outputGroup, "nodes"), g, shapes); - - layout(g); - - positionNodes(nodes, g); - positionEdgeLabels(edgeLabels, g); - createEdgePaths(edgePathsGroup, g, arrows); - - var clusters = createClusters(clustersGroup, g); - positionClusters(clusters, g); - - postProcessGraph(g); - }; - - fn.createNodes = function(value) { - if (!arguments.length) return createNodes; - createNodes = value; - return fn; - }; - - fn.createClusters = function(value) { - if (!arguments.length) return createClusters; - createClusters = value; - return fn; - }; - - fn.createEdgeLabels = function(value) { - if (!arguments.length) return createEdgeLabels; - createEdgeLabels = value; - return fn; - }; - - fn.createEdgePaths = function(value) { - if (!arguments.length) return createEdgePaths; - createEdgePaths = value; - return fn; - }; - - fn.shapes = function(value) { - if (!arguments.length) return shapes; - shapes = value; - return fn; - }; - - fn.arrows = function(value) { - if (!arguments.length) return arrows; - arrows = value; - return fn; - }; - - return fn; - } - - var NODE_DEFAULT_ATTRS = { - paddingLeft: 10, - paddingRight: 10, - paddingTop: 10, - paddingBottom: 10, - rx: 0, - ry: 0, - shape: "rect" - }; - - var EDGE_DEFAULT_ATTRS = { - arrowhead: "normal", - lineInterpolate: "linear" - }; - - function preProcessGraph(g) { - g.nodes().forEach(function(v) { - var node = g.node(v); - if (!_.has(node, "label") && !g.children(v).length) { node.label = v; } - - if (_.has(node, "paddingX")) { - _.defaults(node, { - paddingLeft: node.paddingX, - paddingRight: node.paddingX - }); - } - - if (_.has(node, "paddingY")) { - _.defaults(node, { - paddingTop: node.paddingY, - paddingBottom: node.paddingY - }); - } - - if (_.has(node, "padding")) { - _.defaults(node, { - paddingLeft: node.padding, - paddingRight: node.padding, - paddingTop: node.padding, - paddingBottom: node.padding - }); - } - - _.defaults(node, NODE_DEFAULT_ATTRS); - - _.each(["paddingLeft", "paddingRight", "paddingTop", "paddingBottom"], function(k) { - node[k] = Number(node[k]); - }); - - // Save dimensions for restore during post-processing - if (_.has(node, "width")) { node._prevWidth = node.width; } - if (_.has(node, "height")) { node._prevHeight = node.height; } - }); - - g.edges().forEach(function(e) { - var edge = g.edge(e); - if (!_.has(edge, "label")) { edge.label = ""; } - _.defaults(edge, EDGE_DEFAULT_ATTRS); - }); - } - - function postProcessGraph(g) { - _.each(g.nodes(), function(v) { - var node = g.node(v); - - // Restore original dimensions - if (_.has(node, "_prevWidth")) { - node.width = node._prevWidth; - } else { - delete node.width; - } - - if (_.has(node, "_prevHeight")) { - node.height = node._prevHeight; - } else { - delete node.height; - } - - delete node._prevWidth; - delete node._prevHeight; - }); - } - - function createOrSelectGroup(root, name) { - var selection = root.select("g." + name); - if (selection.empty()) { - selection = root.append("g").attr("class", name); - } - return selection; - } - -},{"./arrows":2,"./create-clusters":3,"./create-edge-labels":4,"./create-edge-paths":5,"./create-nodes":6,"./dagre":8,"./lodash":21,"./position-clusters":22,"./position-edge-labels":23,"./position-nodes":24,"./shapes":26}],26:[function(require,module,exports){ - "use strict"; - - var intersectRect = require("./intersect/intersect-rect"), - intersectEllipse = require("./intersect/intersect-ellipse"), - intersectCircle = require("./intersect/intersect-circle"), - intersectPolygon = require("./intersect/intersect-polygon"); - - module.exports = { - rect: rect, - ellipse: ellipse, - circle: circle, - diamond: diamond - }; - - function rect(parent, bbox, node) { - var shapeSvg = parent.insert("rect", ":first-child") - .attr("rx", node.rx) - .attr("ry", node.ry) - .attr("x", -bbox.width / 2) - .attr("y", -bbox.height / 2) - .attr("width", bbox.width) - .attr("height", bbox.height); - - node.intersect = function(point) { - return intersectRect(node, point); - }; - - return shapeSvg; - } - - function ellipse(parent, bbox, node) { - var rx = bbox.width / 2, - ry = bbox.height / 2, - shapeSvg = parent.insert("ellipse", ":first-child") - .attr("x", -bbox.width / 2) - .attr("y", -bbox.height / 2) - .attr("rx", rx) - .attr("ry", ry); - - node.intersect = function(point) { - return intersectEllipse(node, rx, ry, point); - }; - - return shapeSvg; - } - - function circle(parent, bbox, node) { - var r = Math.max(bbox.width, bbox.height) / 2, - shapeSvg = parent.insert("circle", ":first-child") - .attr("x", -bbox.width / 2) - .attr("y", -bbox.height / 2) - .attr("r", r); - - node.intersect = function(point) { - return intersectCircle(node, r, point); - }; - - return shapeSvg; - } - -// Circumscribe an ellipse for the bounding box with a diamond shape. I derived -// the function to calculate the diamond shape from: -// http://mathforum.org/kb/message.jspa?messageID=3750236 - function diamond(parent, bbox, node) { - var w = (bbox.width * Math.SQRT2) / 2, - h = (bbox.height * Math.SQRT2) / 2, - points = [ - { x: 0, y: -h }, - { x: -w, y: 0 }, - { x: 0, y: h }, - { x: w, y: 0 } - ], - shapeSvg = parent.insert("polygon", ":first-child") - .attr("points", points.map(function(p) { return p.x + "," + p.y; }).join(" ")); - - node.intersect = function(p) { - return intersectPolygon(node, points, p); - }; - - return shapeSvg; - } - -},{"./intersect/intersect-circle":11,"./intersect/intersect-ellipse":12,"./intersect/intersect-polygon":15,"./intersect/intersect-rect":16}],27:[function(require,module,exports){ - var _ = require("./lodash"); - -// Public utility functions - module.exports = { - isSubgraph: isSubgraph, - edgeToId: edgeToId, - applyStyle: applyStyle, - applyClass: applyClass, - applyTransition: applyTransition - }; - - /* - * Returns true if the specified node in the graph is a subgraph node. A - * subgraph node is one that contains other nodes. - */ - function isSubgraph(g, v) { - return !!g.children(v).length; - } - - function edgeToId(e) { - return escapeId(e.v) + ":" + escapeId(e.w) + ":" + escapeId(e.name); - } - - var ID_DELIM = /:/g; - function escapeId(str) { - return str ? String(str).replace(ID_DELIM, "\\:") : ""; - } - - function applyStyle(dom, styleFn) { - if (styleFn) { - dom.attr("style", styleFn); - } - } - - function applyClass(dom, classFn, otherClasses) { - if (classFn) { - dom - .attr("class", classFn) - .attr("class", otherClasses + " " + dom.attr("class")); - } - } - - function applyTransition(selection, g) { - var graph = g.graph(); - - if (_.isPlainObject(graph)) { - var transition = graph.transition; - if (_.isFunction(transition)) { - return transition(selection); - } - } - - return selection; - } - -},{"./lodash":21}],28:[function(require,module,exports){ - module.exports = "0.4.17"; - -},{}]},{},[1])(1) -}); -//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyaWZ5L25vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJpbmRleC5qcyIsImxpYi9hcnJvd3MuanMiLCJsaWIvY3JlYXRlLWNsdXN0ZXJzLmpzIiwibGliL2NyZWF0ZS1lZGdlLWxhYmVscy5qcyIsImxpYi9jcmVhdGUtZWRnZS1wYXRocy5qcyIsImxpYi9jcmVhdGUtbm9kZXMuanMiLCJsaWIvZDMuanMiLCJsaWIvZGFncmUuanMiLCJsaWIvZ3JhcGhsaWIuanMiLCJsaWIvaW50ZXJzZWN0L2luZGV4LmpzIiwibGliL2ludGVyc2VjdC9pbnRlcnNlY3QtY2lyY2xlLmpzIiwibGliL2ludGVyc2VjdC9pbnRlcnNlY3QtZWxsaXBzZS5qcyIsImxpYi9pbnRlcnNlY3QvaW50ZX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dW5jdGlvbiBhcHBseUNsYXNzKGRvbSwgY2xhc3NGbiwgb3RoZXJDbGFzc2VzKSB7XG4gIGlmIChjbGFzc0ZuKSB7XG4gICAgZG9tXG4gICAgICAuYXR0cihcImNsYXNzXCIsIGNsYXNzRm4pXG4gICAgICAuYXR0cihcImNsYXNzXCIsIG90aGVyQ2xhc3NlcyArIFwiIFwiICsgZG9tLmF0dHIoXCJjbGFzc1wiKSk7XG4gIH1cbn1cblxuZnVuY3Rpb24gYXBwbHlUcmFuc2l0aW9uKHNlbGVjdGlvbiwgZykge1xuICB2YXIgZ3JhcGggPSBnLmdyYXBoKCk7XG5cbiAgaWYgKF8uaXNQbGFpbk9iamVjdChncmFwaCkpIHtcbiAgICB2YXIgdHJhbnNpdGlvbiA9IGdyYXBoLnRyYW5zaXRpb247XG4gICAgaWYgKF8uaXNGdW5jdGlvbih0cmFuc2l0aW9uKSkge1xuICAgICAgcmV0dXJuIHRyYW5zaXRpb24oc2VsZWN0aW9uKTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gc2VsZWN0aW9uO1xufVxuIiwibW9kdWxlLmV4cG9ydHMgPSBcIjAuNC4xN1wiO1xuIl19 \ No newline at end of file diff --git a/vitrage_dashboard/dashboard/static/vendor/dagre/dagre.core.js b/vitrage_dashboard/dashboard/static/vendor/dagre/dagre.core.js deleted file mode 100644 index 4816be6..0000000 --- a/vitrage_dashboard/dashboard/static/vendor/dagre/dagre.core.js +++ /dev/null @@ -1,2905 +0,0 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.dagre=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0; --i) { - entry = buckets[i].dequeue(); - if (entry) { - results = results.concat(removeNode(g, buckets, zeroIdx, entry, true)); - break; - } - } - } - } - - return results; -} - -function removeNode(g, buckets, zeroIdx, entry, collectPredecessors) { - var results = collectPredecessors ? [] : undefined; - - _.each(g.inEdges(entry.v), function(edge) { - var weight = g.edge(edge), - uEntry = g.node(edge.v); - - if (collectPredecessors) { - results.push({ v: edge.v, w: edge.w }); - } - - uEntry.out -= weight; - assignBucket(buckets, zeroIdx, uEntry); - }); - - _.each(g.outEdges(entry.v), function(edge) { - var weight = g.edge(edge), - w = edge.w, - wEntry = g.node(w); - wEntry.in -= weight; - assignBucket(buckets, zeroIdx, wEntry); - }); - - g.removeNode(entry.v); - - return results; -} - -function buildState(g, weightFn) { - var fasGraph = new Graph(), - maxIn = 0, - maxOut = 0; - - _.each(g.nodes(), function(v) { - fasGraph.setNode(v, { v: v, in: 0, out: 0 }); - }); - - // Aggregate weights on nodes, but also sum the weights across multi-edges - // into a single edge for the fasGraph. - _.each(g.edges(), function(e) { - var prevWeight = fasGraph.edge(e.v, e.w) || 0, - weight = weightFn(e), - edgeWeight = prevWeight + weight; - fasGraph.setEdge(e.v, e.w, edgeWeight); - maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight); - maxIn = Math.max(maxIn, fasGraph.node(e.w).in += weight); - }); - - var buckets = _.range(maxOut + maxIn + 3).map(function() { return new List(); }); - var zeroIdx = maxIn + 1; - - _.each(fasGraph.nodes(), function(v) { - assignBucket(buckets, zeroIdx, fasGraph.node(v)); - }); - - return { graph: fasGraph, buckets: buckets, zeroIdx: zeroIdx }; -} - -function assignBucket(buckets, zeroIdx, entry) { - if (!entry.out) { - buckets[0].enqueue(entry); - } else if (!entry.in) { - buckets[buckets.length - 1].enqueue(entry); - } else { - buckets[entry.out - entry.in + zeroIdx].enqueue(entry); - } -} - -},{"./data/list":5,"./graphlib":7,"./lodash":10}],9:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"), - acyclic = require("./acyclic"), - normalize = require("./normalize"), - rank = require("./rank"), - normalizeRanks = require("./util").normalizeRanks, - parentDummyChains = require("./parent-dummy-chains"), - removeEmptyRanks = require("./util").removeEmptyRanks, - nestingGraph = require("./nesting-graph"), - addBorderSegments = require("./add-border-segments"), - coordinateSystem = require("./coordinate-system"), - order = require("./order"), - position = require("./position"), - util = require("./util"), - Graph = require("./graphlib").Graph; - -module.exports = layout; - -function layout(g, opts) { - var time = opts && opts.debugTiming ? util.time : util.notime; - time("layout", function() { - var layoutGraph = time(" buildLayoutGraph", - function() { return buildLayoutGraph(g); }); - time(" runLayout", function() { runLayout(layoutGraph, time); }); - time(" updateInputGraph", function() { updateInputGraph(g, layoutGraph); }); - }); -} - -function runLayout(g, time) { - time(" makeSpaceForEdgeLabels", function() { makeSpaceForEdgeLabels(g); }); - time(" removeSelfEdges", function() { removeSelfEdges(g); }); - time(" acyclic", function() { acyclic.run(g); }); - time(" nestingGraph.run", function() { nestingGraph.run(g); }); - time(" rank", function() { rank(util.asNonCompoundGraph(g)); }); - time(" injectEdgeLabelProxies", function() { injectEdgeLabelProxies(g); }); - time(" removeEmptyRanks", function() { removeEmptyRanks(g); }); - time(" nestingGraph.cleanup", function() { nestingGraph.cleanup(g); }); - time(" normalizeRanks", function() { normalizeRanks(g); }); - time(" assignRankMinMax", function() { assignRankMinMax(g); }); - time(" removeEdgeLabelProxies", function() { removeEdgeLabelProxies(g); }); - time(" normalize.run", function() { normalize.run(g); }); - time(" parentDummyChains", function() { parentDummyChains(g); }); - time(" addBorderSegments", function() { addBorderSegments(g); }); - time(" order", function() { order(g); }); - time(" insertSelfEdges", function() { insertSelfEdges(g); }); - time(" adjustCoordinateSystem", function() { coordinateSystem.adjust(g); }); - time(" position", function() { position(g); }); - time(" positionSelfEdges", function() { positionSelfEdges(g); }); - time(" removeBorderNodes", function() { removeBorderNodes(g); }); - time(" normalize.undo", function() { normalize.undo(g); }); - time(" fixupEdgeLabelCoords", function() { fixupEdgeLabelCoords(g); }); - time(" undoCoordinateSystem", function() { coordinateSystem.undo(g); }); - time(" translateGraph", function() { translateGraph(g); }); - time(" assignNodeIntersects", function() { assignNodeIntersects(g); }); - time(" reversePoints", function() { reversePointsForReversedEdges(g); }); - time(" acyclic.undo", function() { acyclic.undo(g); }); -} - -/* - * Copies final layout information from the layout graph back to the input - * graph. This process only copies whitelisted attributes from the layout graph - * to the input graph, so it serves as a good place to determine what - * attributes can influence layout. - */ -function updateInputGraph(inputGraph, layoutGraph) { - _.each(inputGraph.nodes(), function(v) { - var inputLabel = inputGraph.node(v), - layoutLabel = layoutGraph.node(v); - - if (inputLabel) { - inputLabel.x = layoutLabel.x; - inputLabel.y = layoutLabel.y; - - if (layoutGraph.children(v).length) { - inputLabel.width = layoutLabel.width; - inputLabel.height = layoutLabel.height; - } - } - }); - - _.each(inputGraph.edges(), function(e) { - var inputLabel = inputGraph.edge(e), - layoutLabel = layoutGraph.edge(e); - - inputLabel.points = layoutLabel.points; - if (_.has(layoutLabel, "x")) { - inputLabel.x = layoutLabel.x; - inputLabel.y = layoutLabel.y; - } - }); - - inputGraph.graph().width = layoutGraph.graph().width; - inputGraph.graph().height = layoutGraph.graph().height; -} - -var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"], - graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb" }, - graphAttrs = ["acyclicer", "ranker", "rankdir", "align"], - nodeNumAttrs = ["width", "height"], - nodeDefaults = { width: 0, height: 0 }, - edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"], - edgeDefaults = { - minlen: 1, weight: 1, width: 0, height: 0, - labeloffset: 10, labelpos: "r" - }, - edgeAttrs = ["labelpos"]; - -/* - * Constructs a new graph from the input graph, which can be used for layout. - * This process copies only whitelisted attributes from the input graph to the - * layout graph. Thus this function serves as a good place to determine what - * attributes can influence layout. - */ -function buildLayoutGraph(inputGraph) { - var g = new Graph({ multigraph: true, compound: true }), - graph = canonicalize(inputGraph.graph()); - - g.setGraph(_.merge({}, - graphDefaults, - selectNumberAttrs(graph, graphNumAttrs), - _.pick(graph, graphAttrs))); - - _.each(inputGraph.nodes(), function(v) { - var node = canonicalize(inputGraph.node(v)); - g.setNode(v, _.defaults(selectNumberAttrs(node, nodeNumAttrs), nodeDefaults)); - g.setParent(v, inputGraph.parent(v)); - }); - - _.each(inputGraph.edges(), function(e) { - var edge = canonicalize(inputGraph.edge(e)); - g.setEdge(e, _.merge({}, - edgeDefaults, - selectNumberAttrs(edge, edgeNumAttrs), - _.pick(edge, edgeAttrs))); - }); - - return g; -} - -/* - * This idea comes from the Gansner paper: to account for edge labels in our - * layout we split each rank in half by doubling minlen and halving ranksep. - * Then we can place labels at these mid-points between nodes. - * - * We also add some minimal padding to the width to push the label for the edge - * away from the edge itself a bit. - */ -function makeSpaceForEdgeLabels(g) { - var graph = g.graph(); - graph.ranksep /= 2; - _.each(g.edges(), function(e) { - var edge = g.edge(e); - edge.minlen *= 2; - if (edge.labelpos.toLowerCase() !== "c") { - if (graph.rankdir === "TB" || graph.rankdir === "BT") { - edge.width += edge.labeloffset; - } else { - edge.height += edge.labeloffset; - } - } - }); -} - -/* - * Creates temporary dummy nodes that capture the rank in which each edge's - * label is going to, if it has one of non-zero width and height. We do this - * so that we can safely remove empty ranks while preserving balance for the - * label's position. - */ -function injectEdgeLabelProxies(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (edge.width && edge.height) { - var v = g.node(e.v), - w = g.node(e.w), - label = { rank: (w.rank - v.rank) / 2 + v.rank, e: e }; - util.addDummyNode(g, "edge-proxy", label, "_ep"); - } - }); -} - -function assignRankMinMax(g) { - var maxRank = 0; - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (node.borderTop) { - node.minRank = g.node(node.borderTop).rank; - node.maxRank = g.node(node.borderBottom).rank; - maxRank = _.max(maxRank, node.maxRank); - } - }); - g.graph().maxRank = maxRank; -} - -function removeEdgeLabelProxies(g) { - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (node.dummy === "edge-proxy") { - g.edge(node.e).labelRank = node.rank; - g.removeNode(v); - } - }); -} - -function translateGraph(g) { - var minX = Number.POSITIVE_INFINITY, - maxX = 0, - minY = Number.POSITIVE_INFINITY, - maxY = 0, - graphLabel = g.graph(), - marginX = graphLabel.marginx || 0, - marginY = graphLabel.marginy || 0; - - function getExtremes(attrs) { - var x = attrs.x, - y = attrs.y, - w = attrs.width, - h = attrs.height; - minX = Math.min(minX, x - w / 2); - maxX = Math.max(maxX, x + w / 2); - minY = Math.min(minY, y - h / 2); - maxY = Math.max(maxY, y + h / 2); - } - - _.each(g.nodes(), function(v) { getExtremes(g.node(v)); }); - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (_.has(edge, "x")) { - getExtremes(edge); - } - }); - - minX -= marginX; - minY -= marginY; - - _.each(g.nodes(), function(v) { - var node = g.node(v); - node.x -= minX; - node.y -= minY; - }); - - _.each(g.edges(), function(e) { - var edge = g.edge(e); - _.each(edge.points, function(p) { - p.x -= minX; - p.y -= minY; - }); - if (_.has(edge, "x")) { edge.x -= minX; } - if (_.has(edge, "y")) { edge.y -= minY; } - }); - - graphLabel.width = maxX - minX + marginX; - graphLabel.height = maxY - minY + marginY; -} - -function assignNodeIntersects(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e), - nodeV = g.node(e.v), - nodeW = g.node(e.w), - p1, p2; - if (!edge.points) { - edge.points = []; - p1 = nodeW; - p2 = nodeV; - } else { - p1 = edge.points[0]; - p2 = edge.points[edge.points.length - 1]; - } - edge.points.unshift(util.intersectRect(nodeV, p1)); - edge.points.push(util.intersectRect(nodeW, p2)); - }); -} - -function fixupEdgeLabelCoords(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (_.has(edge, "x")) { - if (edge.labelpos === "l" || edge.labelpos === "r") { - edge.width -= edge.labeloffset; - } - switch (edge.labelpos) { - case "l": edge.x -= edge.width / 2 + edge.labeloffset; break; - case "r": edge.x += edge.width / 2 + edge.labeloffset; break; - } - } - }); -} - -function reversePointsForReversedEdges(g) { - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (edge.reversed) { - edge.points.reverse(); - } - }); -} - -function removeBorderNodes(g) { - _.each(g.nodes(), function(v) { - if (g.children(v).length) { - var node = g.node(v), - t = g.node(node.borderTop), - b = g.node(node.borderBottom), - l = g.node(_.last(node.borderLeft)), - r = g.node(_.last(node.borderRight)); - - node.width = Math.abs(r.x - l.x); - node.height = Math.abs(b.y - t.y); - node.x = l.x + node.width / 2; - node.y = t.y + node.height / 2; - } - }); - - _.each(g.nodes(), function(v) { - if (g.node(v).dummy === "border") { - g.removeNode(v); - } - }); -} - -function removeSelfEdges(g) { - _.each(g.edges(), function(e) { - if (e.v === e.w) { - var node = g.node(e.v); - if (!node.selfEdges) { - node.selfEdges = []; - } - node.selfEdges.push({ e: e, label: g.edge(e) }); - g.removeEdge(e); - } - }); -} - -function insertSelfEdges(g) { - var layers = util.buildLayerMatrix(g); - _.each(layers, function(layer) { - var orderShift = 0; - _.each(layer, function(v, i) { - var node = g.node(v); - node.order = i + orderShift; - _.each(node.selfEdges, function(selfEdge) { - util.addDummyNode(g, "selfedge", { - width: selfEdge.label.width, - height: selfEdge.label.height, - rank: node.rank, - order: i + (++orderShift), - e: selfEdge.e, - label: selfEdge.label - }, "_se"); - }); - delete node.selfEdges; - }); - }); -} - -function positionSelfEdges(g) { - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (node.dummy === "selfedge") { - var selfNode = g.node(node.e.v), - x = selfNode.x + selfNode.width / 2, - y = selfNode.y, - dx = node.x - x, - dy = selfNode.height / 2; - g.setEdge(node.e, node.label); - g.removeNode(v); - node.label.points = [ - { x: x + 2 * dx / 3, y: y - dy }, - { x: x + 5 * dx / 6, y: y - dy }, - { x: x + dx , y: y }, - { x: x + 5 * dx / 6, y: y + dy }, - { x: x + 2 * dx / 3, y: y + dy }, - ]; - node.label.x = node.x; - node.label.y = node.y; - } - }); -} - -function selectNumberAttrs(obj, attrs) { - return _.mapValues(_.pick(obj, attrs), Number); -} - -function canonicalize(attrs) { - var newAttrs = {}; - _.each(attrs, function(v, k) { - newAttrs[k.toLowerCase()] = v; - }); - return newAttrs; -} - -},{"./acyclic":2,"./add-border-segments":3,"./coordinate-system":4,"./graphlib":7,"./lodash":10,"./nesting-graph":11,"./normalize":12,"./order":17,"./parent-dummy-chains":22,"./position":24,"./rank":26,"./util":29}],10:[function(require,module,exports){ -/* global window */ - -var lodash; - -if (require) { - try { - lodash = require("lodash"); - } catch (e) {} -} - -if (!lodash) { - lodash = window._; -} - -module.exports = lodash; - -},{"lodash":undefined}],11:[function(require,module,exports){ -var _ = require("./lodash"), - util = require("./util"); - -module.exports = { - run: run, - cleanup: cleanup -}; - -/* - * A nesting graph creates dummy nodes for the tops and bottoms of subgraphs, - * adds appropriate edges to ensure that all cluster nodes are placed between - * these boundries, and ensures that the graph is connected. - * - * In addition we ensure, through the use of the minlen property, that nodes - * and subgraph border nodes to not end up on the same rank. - * - * Preconditions: - * - * 1. Input graph is a DAG - * 2. Nodes in the input graph has a minlen attribute - * - * Postconditions: - * - * 1. Input graph is connected. - * 2. Dummy nodes are added for the tops and bottoms of subgraphs. - * 3. The minlen attribute for nodes is adjusted to ensure nodes do not - * get placed on the same rank as subgraph border nodes. - * - * The nesting graph idea comes from Sander, "Layout of Compound Directed - * Graphs." - */ -function run(g) { - var root = util.addDummyNode(g, "root", {}, "_root"), - depths = treeDepths(g), - height = _.max(depths) - 1, - nodeSep = 2 * height + 1; - - g.graph().nestingRoot = root; - - // Multiply minlen by nodeSep to align nodes on non-border ranks. - _.each(g.edges(), function(e) { g.edge(e).minlen *= nodeSep; }); - - // Calculate a weight that is sufficient to keep subgraphs vertically compact - var weight = sumWeights(g) + 1; - - // Create border nodes and link them up - _.each(g.children(), function(child) { - dfs(g, root, nodeSep, weight, height, depths, child); - }); - - // Save the multiplier for node layers for later removal of empty border - // layers. - g.graph().nodeRankFactor = nodeSep; -} - -function dfs(g, root, nodeSep, weight, height, depths, v) { - var children = g.children(v); - if (!children.length) { - if (v !== root) { - g.setEdge(root, v, { weight: 0, minlen: nodeSep }); - } - return; - } - - var top = util.addBorderNode(g, "_bt"), - bottom = util.addBorderNode(g, "_bb"), - label = g.node(v); - - g.setParent(top, v); - label.borderTop = top; - g.setParent(bottom, v); - label.borderBottom = bottom; - - _.each(children, function(child) { - dfs(g, root, nodeSep, weight, height, depths, child); - - var childNode = g.node(child), - childTop = childNode.borderTop ? childNode.borderTop : child, - childBottom = childNode.borderBottom ? childNode.borderBottom : child, - thisWeight = childNode.borderTop ? weight : 2 * weight, - minlen = childTop !== childBottom ? 1 : height - depths[v] + 1; - - g.setEdge(top, childTop, { - weight: thisWeight, - minlen: minlen, - nestingEdge: true - }); - - g.setEdge(childBottom, bottom, { - weight: thisWeight, - minlen: minlen, - nestingEdge: true - }); - }); - - if (!g.parent(v)) { - g.setEdge(root, top, { weight: 0, minlen: height + depths[v] }); - } -} - -function treeDepths(g) { - var depths = {}; - function dfs(v, depth) { - var children = g.children(v); - if (children && children.length) { - _.each(children, function(child) { - dfs(child, depth + 1); - }); - } - depths[v] = depth; - } - _.each(g.children(), function(v) { dfs(v, 1); }); - return depths; -} - -function sumWeights(g) { - return _.reduce(g.edges(), function(acc, e) { - return acc + g.edge(e).weight; - }, 0); -} - -function cleanup(g) { - var graphLabel = g.graph(); - g.removeNode(graphLabel.nestingRoot); - delete graphLabel.nestingRoot; - _.each(g.edges(), function(e) { - var edge = g.edge(e); - if (edge.nestingEdge) { - g.removeEdge(e); - } - }); -} - -},{"./lodash":10,"./util":29}],12:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"), - util = require("./util"); - -module.exports = { - run: run, - undo: undo -}; - -/* - * Breaks any long edges in the graph into short segments that span 1 layer - * each. This operation is undoable with the denormalize function. - * - * Pre-conditions: - * - * 1. The input graph is a DAG. - * 2. Each node in the graph has a "rank" property. - * - * Post-condition: - * - * 1. All edges in the graph have a length of 1. - * 2. Dummy nodes are added where edges have been split into segments. - * 3. The graph is augmented with a "dummyChains" attribute which contains - * the first dummy in each chain of dummy nodes produced. - */ -function run(g) { - g.graph().dummyChains = []; - _.each(g.edges(), function(edge) { normalizeEdge(g, edge); }); -} - -function normalizeEdge(g, e) { - var v = e.v, - vRank = g.node(v).rank, - w = e.w, - wRank = g.node(w).rank, - name = e.name, - edgeLabel = g.edge(e), - labelRank = edgeLabel.labelRank; - - if (wRank === vRank + 1) return; - - g.removeEdge(e); - - var dummy, attrs, i; - for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) { - edgeLabel.points = []; - attrs = { - width: 0, height: 0, - edgeLabel: edgeLabel, edgeObj: e, - rank: vRank - }; - dummy = util.addDummyNode(g, "edge", attrs, "_d"); - if (vRank === labelRank) { - attrs.width = edgeLabel.width; - attrs.height = edgeLabel.height; - attrs.dummy = "edge-label"; - attrs.labelpos = edgeLabel.labelpos; - } - g.setEdge(v, dummy, { weight: edgeLabel.weight }, name); - if (i === 0) { - g.graph().dummyChains.push(dummy); - } - v = dummy; - } - - g.setEdge(v, w, { weight: edgeLabel.weight }, name); -} - -function undo(g) { - _.each(g.graph().dummyChains, function(v) { - var node = g.node(v), - origLabel = node.edgeLabel, - w; - g.setEdge(node.edgeObj, origLabel); - while (node.dummy) { - w = g.successors(v)[0]; - g.removeNode(v); - origLabel.points.push({ x: node.x, y: node.y }); - if (node.dummy === "edge-label") { - origLabel.x = node.x; - origLabel.y = node.y; - origLabel.width = node.width; - origLabel.height = node.height; - } - v = w; - node = g.node(v); - } - }); -} - -},{"./lodash":10,"./util":29}],13:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = addSubgraphConstraints; - -function addSubgraphConstraints(g, cg, vs) { - var prev = {}, - rootPrev; - - _.each(vs, function(v) { - var child = g.parent(v), - parent, - prevChild; - while (child) { - parent = g.parent(child); - if (parent) { - prevChild = prev[parent]; - prev[parent] = child; - } else { - prevChild = rootPrev; - rootPrev = child; - } - if (prevChild && prevChild !== child) { - cg.setEdge(prevChild, child); - return; - } - child = parent; - } - }); - - /* - function dfs(v) { - var children = v ? g.children(v) : g.children(); - if (children.length) { - var min = Number.POSITIVE_INFINITY, - subgraphs = []; - _.each(children, function(child) { - var childMin = dfs(child); - if (g.children(child).length) { - subgraphs.push({ v: child, order: childMin }); - } - min = Math.min(min, childMin); - }); - _.reduce(_.sortBy(subgraphs, "order"), function(prev, curr) { - cg.setEdge(prev.v, curr.v); - return curr; - }); - return min; - } - return g.node(v).order; - } - dfs(undefined); - */ -} - -},{"../lodash":10}],14:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = barycenter; - -function barycenter(g, movable) { - return _.map(movable, function(v) { - var inV = g.inEdges(v); - if (!inV.length) { - return { v: v }; - } else { - var result = _.reduce(inV, function(acc, e) { - var edge = g.edge(e), - nodeU = g.node(e.v); - return { - sum: acc.sum + (edge.weight * nodeU.order), - weight: acc.weight + edge.weight - }; - }, { sum: 0, weight: 0 }); - - return { - v: v, - barycenter: result.sum / result.weight, - weight: result.weight - }; - } - }); -} - - -},{"../lodash":10}],15:[function(require,module,exports){ -var _ = require("../lodash"), - Graph = require("../graphlib").Graph; - -module.exports = buildLayerGraph; - -/* - * Constructs a graph that can be used to sort a layer of nodes. The graph will - * contain all base and subgraph nodes from the request layer in their original - * hierarchy and any edges that are incident on these nodes and are of the type - * requested by the "relationship" parameter. - * - * Nodes from the requested rank that do not have parents are assigned a root - * node in the output graph, which is set in the root graph attribute. This - * makes it easy to walk the hierarchy of movable nodes during ordering. - * - * Pre-conditions: - * - * 1. Input graph is a DAG - * 2. Base nodes in the input graph have a rank attribute - * 3. Subgraph nodes in the input graph has minRank and maxRank attributes - * 4. Edges have an assigned weight - * - * Post-conditions: - * - * 1. Output graph has all nodes in the movable rank with preserved - * hierarchy. - * 2. Root nodes in the movable layer are made children of the node - * indicated by the root attribute of the graph. - * 3. Non-movable nodes incident on movable nodes, selected by the - * relationship parameter, are included in the graph (without hierarchy). - * 4. Edges incident on movable nodes, selected by the relationship - * parameter, are added to the output graph. - * 5. The weights for copied edges are aggregated as need, since the output - * graph is not a multi-graph. - */ -function buildLayerGraph(g, rank, relationship) { - var root = createRootNode(g), - result = new Graph({ compound: true }).setGraph({ root: root }) - .setDefaultNodeLabel(function(v) { return g.node(v); }); - - _.each(g.nodes(), function(v) { - var node = g.node(v), - parent = g.parent(v); - - if (node.rank === rank || node.minRank <= rank && rank <= node.maxRank) { - result.setNode(v); - result.setParent(v, parent || root); - - // This assumes we have only short edges! - _.each(g[relationship](v), function(e) { - var u = e.v === v ? e.w : e.v, - edge = result.edge(u, v), - weight = !_.isUndefined(edge) ? edge.weight : 0; - result.setEdge(u, v, { weight: g.edge(e).weight + weight }); - }); - - if (_.has(node, "minRank")) { - result.setNode(v, { - borderLeft: node.borderLeft[rank], - borderRight: node.borderRight[rank] - }); - } - } - }); - - return result; -} - -function createRootNode(g) { - var v; - while (g.hasNode((v = _.uniqueId("_root")))); - return v; -} - -},{"../graphlib":7,"../lodash":10}],16:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = crossCount; - -/* - * A function that takes a layering (an array of layers, each with an array of - * ordererd nodes) and a graph and returns a weighted crossing count. - * - * Pre-conditions: - * - * 1. Input graph must be simple (not a multigraph), directed, and include - * only simple edges. - * 2. Edges in the input graph must have assigned weights. - * - * Post-conditions: - * - * 1. The graph and layering matrix are left unchanged. - * - * This algorithm is derived from Barth, et al., "Bilayer Cross Counting." - */ -function crossCount(g, layering) { - var cc = 0; - for (var i = 1; i < layering.length; ++i) { - cc += twoLayerCrossCount(g, layering[i-1], layering[i]); - } - return cc; -} - -function twoLayerCrossCount(g, northLayer, southLayer) { - // Sort all of the edges between the north and south layers by their position - // in the north layer and then the south. Map these edges to the position of - // their head in the south layer. - var southPos = _.zipObject(southLayer, - _.map(southLayer, function (v, i) { return i; })); - var southEntries = _.flatten(_.map(northLayer, function(v) { - return _.chain(g.outEdges(v)) - .map(function(e) { - return { pos: southPos[e.w], weight: g.edge(e).weight }; - }) - .sortBy("pos") - .value(); - }), true); - - // Build the accumulator tree - var firstIndex = 1; - while (firstIndex < southLayer.length) firstIndex <<= 1; - var treeSize = 2 * firstIndex - 1; - firstIndex -= 1; - var tree = _.map(new Array(treeSize), function() { return 0; }); - - // Calculate the weighted crossings - var cc = 0; - _.each(southEntries.forEach(function(entry) { - var index = entry.pos + firstIndex; - tree[index] += entry.weight; - var weightSum = 0; - while (index > 0) { - if (index % 2) { - weightSum += tree[index + 1]; - } - index = (index - 1) >> 1; - tree[index] += entry.weight; - } - cc += entry.weight * weightSum; - })); - - return cc; -} - -},{"../lodash":10}],17:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - initOrder = require("./init-order"), - crossCount = require("./cross-count"), - sortSubgraph = require("./sort-subgraph"), - buildLayerGraph = require("./build-layer-graph"), - addSubgraphConstraints = require("./add-subgraph-constraints"), - Graph = require("../graphlib").Graph, - util = require("../util"); - -module.exports = order; - -/* - * Applies heuristics to minimize edge crossings in the graph and sets the best - * order solution as an order attribute on each node. - * - * Pre-conditions: - * - * 1. Graph must be DAG - * 2. Graph nodes must be objects with a "rank" attribute - * 3. Graph edges must have the "weight" attribute - * - * Post-conditions: - * - * 1. Graph nodes will have an "order" attribute based on the results of the - * algorithm. - */ -function order(g) { - var maxRank = util.maxRank(g), - downLayerGraphs = buildLayerGraphs(g, _.range(1, maxRank + 1), "inEdges"), - upLayerGraphs = buildLayerGraphs(g, _.range(maxRank - 1, -1, -1), "outEdges"); - - var layering = initOrder(g); - assignOrder(g, layering); - - var bestCC = Number.POSITIVE_INFINITY, - best; - - for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) { - sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2); - - layering = util.buildLayerMatrix(g); - var cc = crossCount(g, layering); - if (cc < bestCC) { - lastBest = 0; - best = _.cloneDeep(layering); - bestCC = cc; - } - } - - assignOrder(g, best); -} - -function buildLayerGraphs(g, ranks, relationship) { - return _.map(ranks, function(rank) { - return buildLayerGraph(g, rank, relationship); - }); -} - -function sweepLayerGraphs(layerGraphs, biasRight) { - var cg = new Graph(); - _.each(layerGraphs, function(lg) { - var root = lg.graph().root; - var sorted = sortSubgraph(lg, root, cg, biasRight); - _.each(sorted.vs, function(v, i) { - lg.node(v).order = i; - }); - addSubgraphConstraints(lg, cg, sorted.vs); - }); -} - -function assignOrder(g, layering) { - _.each(layering, function(layer) { - _.each(layer, function(v, i) { - g.node(v).order = i; - }); - }); -} - -},{"../graphlib":7,"../lodash":10,"../util":29,"./add-subgraph-constraints":13,"./build-layer-graph":15,"./cross-count":16,"./init-order":18,"./sort-subgraph":20}],18:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = initOrder; - -/* - * Assigns an initial order value for each node by performing a DFS search - * starting from nodes in the first rank. Nodes are assigned an order in their - * rank as they are first visited. - * - * This approach comes from Gansner, et al., "A Technique for Drawing Directed - * Graphs." - * - * Returns a layering matrix with an array per layer and each layer sorted by - * the order of its nodes. - */ -function initOrder(g) { - var visited = {}, - simpleNodes = _.filter(g.nodes(), function(v) { - return !g.children(v).length; - }), - maxRank = _.max(_.map(simpleNodes, function(v) { return g.node(v).rank; })), - layers = _.map(_.range(maxRank + 1), function() { return []; }); - - function dfs(v) { - if (_.has(visited, v)) return; - visited[v] = true; - var node = g.node(v); - layers[node.rank].push(v); - _.each(g.successors(v), dfs); - } - - var orderedVs = _.sortBy(simpleNodes, function(v) { return g.node(v).rank; }); - _.each(orderedVs, dfs); - - return layers; -} - -},{"../lodash":10}],19:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = resolveConflicts; - -/* - * Given a list of entries of the form {v, barycenter, weight} and a - * constraint graph this function will resolve any conflicts between the - * constraint graph and the barycenters for the entries. If the barycenters for - * an entry would violate a constraint in the constraint graph then we coalesce - * the nodes in the conflict into a new node that respects the constraint and - * aggregates barycenter and weight information. - * - * This implementation is based on the description in Forster, "A Fast and - * Simple Hueristic for Constrained Two-Level Crossing Reduction," thought it - * differs in some specific details. - * - * Pre-conditions: - * - * 1. Each entry has the form {v, barycenter, weight}, or if the node has - * no barycenter, then {v}. - * - * Returns: - * - * A new list of entries of the form {vs, i, barycenter, weight}. The list - * `vs` may either be a singleton or it may be an aggregation of nodes - * ordered such that they do not violate constraints from the constraint - * graph. The property `i` is the lowest original index of any of the - * elements in `vs`. - */ -function resolveConflicts(entries, cg) { - var mappedEntries = {}; - _.each(entries, function(entry, i) { - var tmp = mappedEntries[entry.v] = { - indegree: 0, - in: [], - out: [], - vs: [entry.v], - i: i - }; - if (!_.isUndefined(entry.barycenter)) { - tmp.barycenter = entry.barycenter; - tmp.weight = entry.weight; - } - }); - - _.each(cg.edges(), function(e) { - var entryV = mappedEntries[e.v], - entryW = mappedEntries[e.w]; - if (!_.isUndefined(entryV) && !_.isUndefined(entryW)) { - entryW.indegree++; - entryV.out.push(mappedEntries[e.w]); - } - }); - - var sourceSet = _.filter(mappedEntries, function(entry) { - return !entry.indegree; - }); - - return doResolveConflicts(sourceSet); -} - -function doResolveConflicts(sourceSet) { - var entries = []; - - function handleIn(vEntry) { - return function(uEntry) { - if (uEntry.merged) { - return; - } - if (_.isUndefined(uEntry.barycenter) || - _.isUndefined(vEntry.barycenter) || - uEntry.barycenter >= vEntry.barycenter) { - mergeEntries(vEntry, uEntry); - } - }; - } - - function handleOut(vEntry) { - return function(wEntry) { - wEntry.in.push(vEntry); - if (--wEntry.indegree === 0) { - sourceSet.push(wEntry); - } - }; - } - - while (sourceSet.length) { - var entry = sourceSet.pop(); - entries.push(entry); - _.each(entry.in.reverse(), handleIn(entry)); - _.each(entry.out, handleOut(entry)); - } - - return _.chain(entries) - .filter(function(entry) { return !entry.merged; }) - .map(function(entry) { - return _.pick(entry, ["vs", "i", "barycenter", "weight"]); - }) - .value(); -} - -function mergeEntries(target, source) { - var sum = 0, - weight = 0; - - if (target.weight) { - sum += target.barycenter * target.weight; - weight += target.weight; - } - - if (source.weight) { - sum += source.barycenter * source.weight; - weight += source.weight; - } - - target.vs = source.vs.concat(target.vs); - target.barycenter = sum / weight; - target.weight = weight; - target.i = Math.min(source.i, target.i); - source.merged = true; -} - -},{"../lodash":10}],20:[function(require,module,exports){ -var _ = require("../lodash"), - barycenter = require("./barycenter"), - resolveConflicts = require("./resolve-conflicts"), - sort = require("./sort"); - -module.exports = sortSubgraph; - -function sortSubgraph(g, v, cg, biasRight) { - var movable = g.children(v), - node = g.node(v), - bl = node ? node.borderLeft : undefined, - br = node ? node.borderRight: undefined, - subgraphs = {}; - - if (bl) { - movable = _.filter(movable, function(w) { - return w !== bl && w !== br; - }); - } - - var barycenters = barycenter(g, movable); - _.each(barycenters, function(entry) { - if (g.children(entry.v).length) { - var subgraphResult = sortSubgraph(g, entry.v, cg, biasRight); - subgraphs[entry.v] = subgraphResult; - if (_.has(subgraphResult, "barycenter")) { - mergeBarycenters(entry, subgraphResult); - } - } - }); - - var entries = resolveConflicts(barycenters, cg); - expandSubgraphs(entries, subgraphs); - - var result = sort(entries, biasRight); - - if (bl) { - result.vs = _.flatten([bl, result.vs, br], true); - if (g.predecessors(bl).length) { - var blPred = g.node(g.predecessors(bl)[0]), - brPred = g.node(g.predecessors(br)[0]); - if (!_.has(result, "barycenter")) { - result.barycenter = 0; - result.weight = 0; - } - result.barycenter = (result.barycenter * result.weight + - blPred.order + brPred.order) / (result.weight + 2); - result.weight += 2; - } - } - - return result; -} - -function expandSubgraphs(entries, subgraphs) { - _.each(entries, function(entry) { - entry.vs = _.flatten(entry.vs.map(function(v) { - if (subgraphs[v]) { - return subgraphs[v].vs; - } - return v; - }), true); - }); -} - -function mergeBarycenters(target, other) { - if (!_.isUndefined(target.barycenter)) { - target.barycenter = (target.barycenter * target.weight + - other.barycenter * other.weight) / - (target.weight + other.weight); - target.weight += other.weight; - } else { - target.barycenter = other.barycenter; - target.weight = other.weight; - } -} - -},{"../lodash":10,"./barycenter":14,"./resolve-conflicts":19,"./sort":21}],21:[function(require,module,exports){ -var _ = require("../lodash"), - util = require("../util"); - -module.exports = sort; - -function sort(entries, biasRight) { - var parts = util.partition(entries, function(entry) { - return _.has(entry, "barycenter"); - }); - var sortable = parts.lhs, - unsortable = _.sortBy(parts.rhs, function(entry) { return -entry.i; }), - vs = [], - sum = 0, - weight = 0, - vsIndex = 0; - - sortable.sort(compareWithBias(!!biasRight)); - - vsIndex = consumeUnsortable(vs, unsortable, vsIndex); - - _.each(sortable, function (entry) { - vsIndex += entry.vs.length; - vs.push(entry.vs); - sum += entry.barycenter * entry.weight; - weight += entry.weight; - vsIndex = consumeUnsortable(vs, unsortable, vsIndex); - }); - - var result = { vs: _.flatten(vs, true) }; - if (weight) { - result.barycenter = sum / weight; - result.weight = weight; - } - return result; -} - -function consumeUnsortable(vs, unsortable, index) { - var last; - while (unsortable.length && (last = _.last(unsortable)).i <= index) { - unsortable.pop(); - vs.push(last.vs); - index++; - } - return index; -} - -function compareWithBias(bias) { - return function(entryV, entryW) { - if (entryV.barycenter < entryW.barycenter) { - return -1; - } else if (entryV.barycenter > entryW.barycenter) { - return 1; - } - - return !bias ? entryV.i - entryW.i : entryW.i - entryV.i; - }; -} - -},{"../lodash":10,"../util":29}],22:[function(require,module,exports){ -var _ = require("./lodash"); - -module.exports = parentDummyChains; - -function parentDummyChains(g) { - var postorderNums = postorder(g); - - _.each(g.graph().dummyChains, function(v) { - var node = g.node(v), - edgeObj = node.edgeObj, - pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w), - path = pathData.path, - lca = pathData.lca, - pathIdx = 0, - pathV = path[pathIdx], - ascending = true; - - while (v !== edgeObj.w) { - node = g.node(v); - - if (ascending) { - while ((pathV = path[pathIdx]) !== lca && - g.node(pathV).maxRank < node.rank) { - pathIdx++; - } - - if (pathV === lca) { - ascending = false; - } - } - - if (!ascending) { - while (pathIdx < path.length - 1 && - g.node(pathV = path[pathIdx + 1]).minRank <= node.rank) { - pathIdx++; - } - pathV = path[pathIdx]; - } - - g.setParent(v, pathV); - v = g.successors(v)[0]; - } - }); -} - -// Find a path from v to w through the lowest common ancestor (LCA). Return the -// full path and the LCA. -function findPath(g, postorderNums, v, w) { - var vPath = [], - wPath = [], - low = Math.min(postorderNums[v].low, postorderNums[w].low), - lim = Math.max(postorderNums[v].lim, postorderNums[w].lim), - parent, - lca; - - // Traverse up from v to find the LCA - parent = v; - do { - parent = g.parent(parent); - vPath.push(parent); - } while (parent && - (postorderNums[parent].low > low || lim > postorderNums[parent].lim)); - lca = parent; - - // Traverse from w to LCA - parent = w; - while ((parent = g.parent(parent)) !== lca) { - wPath.push(parent); - } - - return { path: vPath.concat(wPath.reverse()), lca: lca }; -} - -function postorder(g) { - var result = {}, - lim = 0; - - function dfs(v) { - var low = lim; - _.each(g.children(v), dfs); - result[v] = { low: low, lim: lim++ }; - } - _.each(g.children(), dfs); - - return result; -} - -},{"./lodash":10}],23:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - util = require("../util"); - -/* - * This module provides coordinate assignment based on Brandes and Köpf, "Fast - * and Simple Horizontal Coordinate Assignment." - */ - -module.exports = { - positionX: positionX, - findType1Conflicts: findType1Conflicts, - findType2Conflicts: findType2Conflicts, - addConflict: addConflict, - hasConflict: hasConflict, - verticalAlignment: verticalAlignment, - horizontalCompaction: horizontalCompaction, - alignCoordinates: alignCoordinates, - findSmallestWidthAlignment: findSmallestWidthAlignment, - balance: balance -}; - -/* - * Marks all edges in the graph with a type-1 conflict with the "type1Conflict" - * property. A type-1 conflict is one where a non-inner segment crosses an - * inner segment. An inner segment is an edge with both incident nodes marked - * with the "dummy" property. - * - * This algorithm scans layer by layer, starting with the second, for type-1 - * conflicts between the current layer and the previous layer. For each layer - * it scans the nodes from left to right until it reaches one that is incident - * on an inner segment. It then scans predecessors to determine if they have - * edges that cross that inner segment. At the end a final scan is done for all - * nodes on the current rank to see if they cross the last visited inner - * segment. - * - * This algorithm (safely) assumes that a dummy node will only be incident on a - * single node in the layers being scanned. - */ -function findType1Conflicts(g, layering) { - var conflicts = {}; - - function visitLayer(prevLayer, layer) { - var - // last visited node in the previous layer that is incident on an inner - // segment. - k0 = 0, - // Tracks the last node in this layer scanned for crossings with a type-1 - // segment. - scanPos = 0, - prevLayerLength = prevLayer.length, - lastNode = _.last(layer); - - _.each(layer, function(v, i) { - var w = findOtherInnerSegmentNode(g, v), - k1 = w ? g.node(w).order : prevLayerLength; - - if (w || v === lastNode) { - _.each(layer.slice(scanPos, i +1), function(scanNode) { - _.each(g.predecessors(scanNode), function(u) { - var uLabel = g.node(u), - uPos = uLabel.order; - if ((uPos < k0 || k1 < uPos) && - !(uLabel.dummy && g.node(scanNode).dummy)) { - addConflict(conflicts, u, scanNode); - } - }); - }); - scanPos = i + 1; - k0 = k1; - } - }); - - return layer; - } - - _.reduce(layering, visitLayer); - return conflicts; -} - -function findType2Conflicts(g, layering) { - var conflicts = {}; - - function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) { - var v; - _.each(_.range(southPos, southEnd), function(i) { - v = south[i]; - if (g.node(v).dummy) { - _.each(g.predecessors(v), function(u) { - var uNode = g.node(u); - if (uNode.dummy && - (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) { - addConflict(conflicts, u, v); - } - }); - } - }); - } - - - function visitLayer(north, south) { - var prevNorthPos = -1, - nextNorthPos, - southPos = 0; - - _.each(south, function(v, southLookahead) { - if (g.node(v).dummy === "border") { - var predecessors = g.predecessors(v); - if (predecessors.length) { - nextNorthPos = g.node(predecessors[0]).order; - scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos); - southPos = southLookahead; - prevNorthPos = nextNorthPos; - } - } - scan(south, southPos, south.length, nextNorthPos, north.length); - }); - - return south; - } - - _.reduce(layering, visitLayer); - return conflicts; -} - -function findOtherInnerSegmentNode(g, v) { - if (g.node(v).dummy) { - return _.find(g.predecessors(v), function(u) { - return g.node(u).dummy; - }); - } -} - -function addConflict(conflicts, v, w) { - if (v > w) { - var tmp = v; - v = w; - w = tmp; - } - - var conflictsV = conflicts[v]; - if (!conflictsV) { - conflicts[v] = conflictsV = {}; - } - conflictsV[w] = true; -} - -function hasConflict(conflicts, v, w) { - if (v > w) { - var tmp = v; - v = w; - w = tmp; - } - return _.has(conflicts[v], w); -} - -/* - * Try to align nodes into vertical "blocks" where possible. This algorithm - * attempts to align a node with one of its median neighbors. If the edge - * connecting a neighbor is a type-1 conflict then we ignore that possibility. - * If a previous node has already formed a block with a node after the node - * we're trying to form a block with, we also ignore that possibility - our - * blocks would be split in that scenario. - */ -function verticalAlignment(g, layering, conflicts, neighborFn) { - var root = {}, - align = {}, - pos = {}; - - // We cache the position here based on the layering because the graph and - // layering may be out of sync. The layering matrix is manipulated to - // generate different extreme alignments. - _.each(layering, function(layer) { - _.each(layer, function(v, order) { - root[v] = v; - align[v] = v; - pos[v] = order; - }); - }); - - _.each(layering, function(layer) { - var prevIdx = -1; - _.each(layer, function(v) { - var ws = neighborFn(v); - if (ws.length) { - ws = _.sortBy(ws, function(w) { return pos[w]; }); - var mp = (ws.length - 1) / 2; - for (var i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) { - var w = ws[i]; - if (align[v] === v && - prevIdx < pos[w] && - !hasConflict(conflicts, v, w)) { - align[w] = v; - align[v] = root[v] = root[w]; - prevIdx = pos[w]; - } - } - } - }); - }); - - return { root: root, align: align }; -} - -function horizontalCompaction(g, layering, root, align, reverseSep) { - // We use local variables for these parameters instead of manipulating the - // graph because it becomes more verbose to access them in a chained manner. - var shift = {}, - shiftNeighbor = {}, - sink = {}, - xs = {}, - pred = {}, - graphLabel = g.graph(), - sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep); - - _.each(layering, function(layer) { - _.each(layer, function(v, order) { - sink[v] = v; - shift[v] = Number.POSITIVE_INFINITY; - pred[v] = layer[order - 1]; - }); - }); - - _.each(g.nodes(), function(v) { - if (root[v] === v) { - placeBlock(g, layering, sepFn, root, align, shift, shiftNeighbor, sink, pred, xs, v); - } - }); - - _.each(layering, function(layer) { - _.each(layer, function(v) { - xs[v] = xs[root[v]]; - // This line differs from the source paper. See - // http://www.inf.uni-konstanz.de/~brandes/publications/ for details. - if (v === root[v] && shift[sink[root[v]]] < Number.POSITIVE_INFINITY) { - xs[v] += shift[sink[root[v]]]; - - // Cascade shifts as necessary - var w = shiftNeighbor[sink[root[v]]]; - if (w && shift[w] !== Number.POSITIVE_INFINITY) { - xs[v] += shift[w]; - } - } - }); - }); - - return xs; -} - -function placeBlock(g, layering, sepFn, root, align, shift, shiftNeighbor, sink, pred, xs, v) { - if (_.has(xs, v)) return; - xs[v] = 0; - - var w = v, - u; - do { - if (pred[w]) { - u = root[pred[w]]; - placeBlock(g, layering, sepFn, root, align, shift, shiftNeighbor, sink, pred, xs, u); - if (sink[v] === v) { - sink[v] = sink[u]; - } - - var delta = sepFn(g, w, pred[w]); - if (sink[v] !== sink[u]) { - shift[sink[u]] = Math.min(shift[sink[u]], xs[v] - xs[u] - delta); - shiftNeighbor[sink[u]] = sink[v]; - } else { - xs[v] = Math.max(xs[v], xs[u] + delta); - } - } - w = align[w]; - } while (w !== v); -} - -/* - * Returns the alignment that has the smallest width of the given alignments. - */ -function findSmallestWidthAlignment(g, xss) { - return _.min(xss, function(xs) { - var min = _.min(xs, function(x, v) { return x - width(g, v) / 2; }), - max = _.max(xs, function(x, v) { return x + width(g, v) / 2; }); - return max - min; - }); -} - -/* - * Align the coordinates of each of the layout alignments such that - * left-biased alignments have their minimum coordinate at the same point as - * the minimum coordinate of the smallest width alignment and right-biased - * alignments have their maximum coordinate at the same point as the maximum - * coordinate of the smallest width alignment. - */ -function alignCoordinates(xss, alignTo) { - var alignToMin = _.min(alignTo), - alignToMax = _.max(alignTo); - - _.each(["u", "d"], function(vert) { - _.each(["l", "r"], function(horiz) { - var alignment = vert + horiz, - xs = xss[alignment], - delta; - if (xs === alignTo) return; - - delta = horiz === "l" ? alignToMin - _.min(xs) : alignToMax - _.max(xs); - - if (delta) { - xss[alignment] = _.mapValues(xs, function(x) { return x + delta; }); - } - }); - }); -} - -function balance(xss, align) { - return _.mapValues(xss.ul, function(ignore, v) { - if (align) { - return xss[align.toLowerCase()][v]; - } else { - var xs = _.sortBy(_.pluck(xss, v)); - return (xs[1] + xs[2]) / 2; - } - }); -} - -function positionX(g) { - var layering = util.buildLayerMatrix(g), - conflicts = _.merge(findType1Conflicts(g, layering), - findType2Conflicts(g, layering)); - - var xss = {}, - adjustedLayering; - _.each(["u", "d"], function(vert) { - adjustedLayering = vert === "u" ? layering : _.values(layering).reverse(); - _.each(["l", "r"], function(horiz) { - if (horiz === "r") { - adjustedLayering = _.map(adjustedLayering, function(inner) { - return _.values(inner).reverse(); - }); - } - - var neighborFn = _.bind(vert === "u" ? g.predecessors : g.successors, g); - var align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn); - var xs = horizontalCompaction(g, adjustedLayering, - align.root, align.align, - horiz === "r"); - if (horiz === "r") { - xs = _.mapValues(xs, function(x) { return -x; }); - } - xss[vert + horiz] = xs; - }); - }); - - var smallestWidth = findSmallestWidthAlignment(g, xss); - alignCoordinates(xss, smallestWidth); - return balance(xss, g.graph().align); -} - -function sep(nodeSep, edgeSep, reverseSep) { - return function(g, v, w) { - var vLabel = g.node(v), - wLabel = g.node(w), - sum = 0, - delta; - - sum += vLabel.width / 2; - if (_.has(vLabel, "labelpos")) { - switch (vLabel.labelpos.toLowerCase()) { - case "l": delta = -vLabel.width / 2; break; - case "r": delta = vLabel.width / 2; break; - } - } - if (delta) { - sum += reverseSep ? delta : -delta; - } - delta = 0; - - sum += (vLabel.dummy ? edgeSep : nodeSep) / 2; - sum += (wLabel.dummy ? edgeSep : nodeSep) / 2; - - sum += wLabel.width / 2; - if (_.has(wLabel, "labelpos")) { - switch (wLabel.labelpos.toLowerCase()) { - case "l": delta = wLabel.width / 2; break; - case "r": delta = -wLabel.width / 2; break; - } - } - if (delta) { - sum += reverseSep ? delta : -delta; - } - delta = 0; - - return sum; - }; -} - -function width(g, v) { - return g.node(v).width; -} - -},{"../lodash":10,"../util":29}],24:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - util = require("../util"), - positionX = require("./bk").positionX; - -module.exports = position; - -function position(g) { - g = util.asNonCompoundGraph(g); - - positionY(g); - _.each(positionX(g), function(x, v) { - g.node(v).x = x; - }); -} - -function positionY(g) { - var layering = util.buildLayerMatrix(g), - rankSep = g.graph().ranksep, - prevY = 0; - _.each(layering, function(layer) { - var maxHeight = _.max(_.map(layer, function(v) { return g.node(v).height; })); - _.each(layer, function(v) { - g.node(v).y = prevY + maxHeight / 2; - }); - prevY += maxHeight + rankSep; - }); -} - - -},{"../lodash":10,"../util":29,"./bk":23}],25:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - Graph = require("../graphlib").Graph, - slack = require("./util").slack; - -module.exports = feasibleTree; - -/* - * Constructs a spanning tree with tight edges and adjusted the input node's - * ranks to achieve this. A tight edge is one that is has a length that matches - * its "minlen" attribute. - * - * The basic structure for this function is derived from Gansner, et al., "A - * Technique for Drawing Directed Graphs." - * - * Pre-conditions: - * - * 1. Graph must be a DAG. - * 2. Graph must be connected. - * 3. Graph must have at least one node. - * 5. Graph nodes must have been previously assigned a "rank" property that - * respects the "minlen" property of incident edges. - * 6. Graph edges must have a "minlen" property. - * - * Post-conditions: - * - * - Graph nodes will have their rank adjusted to ensure that all edges are - * tight. - * - * Returns a tree (undirected graph) that is constructed using only "tight" - * edges. - */ -function feasibleTree(g) { - var t = new Graph({ directed: false }); - - // Choose arbitrary node from which to start our tree - var start = g.nodes()[0], - size = g.nodeCount(); - t.setNode(start, {}); - - var edge, delta; - while (tightTree(t, g) < size) { - edge = findMinSlackEdge(t, g); - delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge); - shiftRanks(t, g, delta); - } - - return t; -} - -/* - * Finds a maximal tree of tight edges and returns the number of nodes in the - * tree. - */ -function tightTree(t, g) { - function dfs(v) { - _.each(g.nodeEdges(v), function(e) { - var edgeV = e.v, - w = (v === edgeV) ? e.w : edgeV; - if (!t.hasNode(w) && !slack(g, e)) { - t.setNode(w, {}); - t.setEdge(v, w, {}); - dfs(w); - } - }); - } - - _.each(t.nodes(), dfs); - return t.nodeCount(); -} - -/* - * Finds the edge with the smallest slack that is incident on tree and returns - * it. - */ -function findMinSlackEdge(t, g) { - return _.min(g.edges(), function(e) { - if (t.hasNode(e.v) !== t.hasNode(e.w)) { - return slack(g, e); - } - }); -} - -function shiftRanks(t, g, delta) { - _.each(t.nodes(), function(v) { - g.node(v).rank += delta; - }); -} - -},{"../graphlib":7,"../lodash":10,"./util":28}],26:[function(require,module,exports){ -"use strict"; - -var rankUtil = require("./util"), - longestPath = rankUtil.longestPath, - feasibleTree = require("./feasible-tree"), - networkSimplex = require("./network-simplex"); - -module.exports = rank; - -/* - * Assigns a rank to each node in the input graph that respects the "minlen" - * constraint specified on edges between nodes. - * - * This basic structure is derived from Gansner, et al., "A Technique for - * Drawing Directed Graphs." - * - * Pre-conditions: - * - * 1. Graph must be a connected DAG - * 2. Graph nodes must be objects - * 3. Graph edges must have "weight" and "minlen" attributes - * - * Post-conditions: - * - * 1. Graph nodes will have a "rank" attribute based on the results of the - * algorithm. Ranks can start at any index (including negative), we'll - * fix them up later. - */ -function rank(g) { - switch(g.graph().ranker) { - case "network-simplex": networkSimplexRanker(g); break; - case "tight-tree": tightTreeRanker(g); break; - case "longest-path": longestPathRanker(g); break; - default: networkSimplexRanker(g); - } -} - -// A fast and simple ranker, but results are far from optimal. -var longestPathRanker = longestPath; - -function tightTreeRanker(g) { - longestPath(g); - feasibleTree(g); -} - -function networkSimplexRanker(g) { - networkSimplex(g); -} - -},{"./feasible-tree":25,"./network-simplex":27,"./util":28}],27:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"), - feasibleTree = require("./feasible-tree"), - slack = require("./util").slack, - initRank = require("./util").longestPath, - preorder = require("../graphlib").alg.preorder, - postorder = require("../graphlib").alg.postorder, - simplify = require("../util").simplify; - -module.exports = networkSimplex; - -// Expose some internals for testing purposes -networkSimplex.initLowLimValues = initLowLimValues; -networkSimplex.initCutValues = initCutValues; -networkSimplex.calcCutValue = calcCutValue; -networkSimplex.leaveEdge = leaveEdge; -networkSimplex.enterEdge = enterEdge; -networkSimplex.exchangeEdges = exchangeEdges; - -/* - * The network simplex algorithm assigns ranks to each node in the input graph - * and iteratively improves the ranking to reduce the length of edges. - * - * Preconditions: - * - * 1. The input graph must be a DAG. - * 2. All nodes in the graph must have an object value. - * 3. All edges in the graph must have "minlen" and "weight" attributes. - * - * Postconditions: - * - * 1. All nodes in the graph will have an assigned "rank" attribute that has - * been optimized by the network simplex algorithm. Ranks start at 0. - * - * - * A rough sketch of the algorithm is as follows: - * - * 1. Assign initial ranks to each node. We use the longest path algorithm, - * which assigns ranks to the lowest position possible. In general this - * leads to very wide bottom ranks and unnecessarily long edges. - * 2. Construct a feasible tight tree. A tight tree is one such that all - * edges in the tree have no slack (difference between length of edge - * and minlen for the edge). This by itself greatly improves the assigned - * rankings by shorting edges. - * 3. Iteratively find edges that have negative cut values. Generally a - * negative cut value indicates that the edge could be removed and a new - * tree edge could be added to produce a more compact graph. - * - * Much of the algorithms here are derived from Gansner, et al., "A Technique - * for Drawing Directed Graphs." The structure of the file roughly follows the - * structure of the overall algorithm. - */ -function networkSimplex(g) { - g = simplify(g); - initRank(g); - var t = feasibleTree(g); - initLowLimValues(t); - initCutValues(t, g); - - var e, f; - while ((e = leaveEdge(t))) { - f = enterEdge(t, g, e); - exchangeEdges(t, g, e, f); - } -} - -/* - * Initializes cut values for all edges in the tree. - */ -function initCutValues(t, g) { - var vs = postorder(t, t.nodes()); - vs = vs.slice(0, vs.length - 1); - _.each(vs, function(v) { - assignCutValue(t, g, v); - }); -} - -function assignCutValue(t, g, child) { - var childLab = t.node(child), - parent = childLab.parent; - t.edge(child, parent).cutvalue = calcCutValue(t, g, child); -} - -/* - * Given the tight tree, its graph, and a child in the graph calculate and - * return the cut value for the edge between the child and its parent. - */ -function calcCutValue(t, g, child) { - var childLab = t.node(child), - parent = childLab.parent, - // True if the child is on the tail end of the edge in the directed graph - childIsTail = true, - // The graph's view of the tree edge we're inspecting - graphEdge = g.edge(child, parent), - // The accumulated cut value for the edge between this node and its parent - cutValue = 0; - - if (!graphEdge) { - childIsTail = false; - graphEdge = g.edge(parent, child); - } - - cutValue = graphEdge.weight; - - _.each(g.nodeEdges(child), function(e) { - var isOutEdge = e.v === child, - other = isOutEdge ? e.w : e.v; - - if (other !== parent) { - var pointsToHead = isOutEdge === childIsTail, - otherWeight = g.edge(e).weight; - - cutValue += pointsToHead ? otherWeight : -otherWeight; - if (isTreeEdge(t, child, other)) { - var otherCutValue = t.edge(child, other).cutvalue; - cutValue += pointsToHead ? -otherCutValue : otherCutValue; - } - } - }); - - return cutValue; -} - -function initLowLimValues(tree, root) { - if (arguments.length < 2) { - root = tree.nodes()[0]; - } - dfsAssignLowLim(tree, {}, 1, root); -} - -function dfsAssignLowLim(tree, visited, nextLim, v, parent) { - var low = nextLim, - label = tree.node(v); - - visited[v] = true; - _.each(tree.neighbors(v), function(w) { - if (!_.has(visited, w)) { - nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v); - } - }); - - label.low = low; - label.lim = nextLim++; - if (parent) { - label.parent = parent; - } else { - // TODO should be able to remove this when we incrementally update low lim - delete label.parent; - } - - return nextLim; -} - -function leaveEdge(tree) { - return _.find(tree.edges(), function(e) { - return tree.edge(e).cutvalue < 0; - }); -} - -function enterEdge(t, g, edge) { - var v = edge.v, - w = edge.w; - - // For the rest of this function we assume that v is the tail and w is the - // head, so if we don't have this edge in the graph we should flip it to - // match the correct orientation. - if (!g.hasEdge(v, w)) { - v = edge.w; - w = edge.v; - } - - var vLabel = t.node(v), - wLabel = t.node(w), - tailLabel = vLabel, - flip = false; - - // If the root is in the tail of the edge then we need to flip the logic that - // checks for the head and tail nodes in the candidates function below. - if (vLabel.lim > wLabel.lim) { - tailLabel = wLabel; - flip = true; - } - - var candidates = _.filter(g.edges(), function(edge) { - return flip === isDescendant(t, t.node(edge.v), tailLabel) && - flip !== isDescendant(t, t.node(edge.w), tailLabel); - }); - - return _.min(candidates, function(edge) { return slack(g, edge); }); -} - -function exchangeEdges(t, g, e, f) { - var v = e.v, - w = e.w; - t.removeEdge(v, w); - t.setEdge(f.v, f.w, {}); - initLowLimValues(t); - initCutValues(t, g); - updateRanks(t, g); -} - -function updateRanks(t, g) { - var root = _.find(t.nodes(), function(v) { return !g.node(v).parent; }), - vs = preorder(t, root); - vs = vs.slice(1); - _.each(vs, function(v) { - var parent = t.node(v).parent, - edge = g.edge(v, parent), - flipped = false; - - if (!edge) { - edge = g.edge(parent, v); - flipped = true; - } - - g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen); - }); -} - -/* - * Returns true if the edge is in the tree. - */ -function isTreeEdge(tree, u, v) { - return tree.hasEdge(u, v); -} - -/* - * Returns true if the specified node is descendant of the root node per the - * assigned low and lim attributes in the tree. - */ -function isDescendant(tree, vLabel, rootLabel) { - return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim; -} - -},{"../graphlib":7,"../lodash":10,"../util":29,"./feasible-tree":25,"./util":28}],28:[function(require,module,exports){ -"use strict"; - -var _ = require("../lodash"); - -module.exports = { - longestPath: longestPath, - slack: slack -}; - -/* - * Initializes ranks for the input graph using the longest path algorithm. This - * algorithm scales well and is fast in practice, it yields rather poor - * solutions. Nodes are pushed to the lowest layer possible, leaving the bottom - * ranks wide and leaving edges longer than necessary. However, due to its - * speed, this algorithm is good for getting an initial ranking that can be fed - * into other algorithms. - * - * This algorithm does not normalize layers because it will be used by other - * algorithms in most cases. If using this algorithm directly, be sure to - * run normalize at the end. - * - * Pre-conditions: - * - * 1. Input graph is a DAG. - * 2. Input graph node labels can be assigned properties. - * - * Post-conditions: - * - * 1. Each node will be assign an (unnormalized) "rank" property. - */ -function longestPath(g) { - var visited = {}; - - function dfs(v) { - var label = g.node(v); - if (_.has(visited, v)) { - return label.rank; - } - visited[v] = true; - - var rank = _.min(_.map(g.outEdges(v), function(e) { - return dfs(e.w) - g.edge(e).minlen; - })); - - if (rank === Number.POSITIVE_INFINITY) { - rank = 0; - } - - return (label.rank = rank); - } - - _.each(g.sources(), dfs); -} - -/* - * Returns the amount of slack for the given edge. The slack is defined as the - * difference between the length of the edge and its minimum length. - */ -function slack(g, e) { - return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen; -} - -},{"../lodash":10}],29:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"), - Graph = require("./graphlib").Graph; - -module.exports = { - addDummyNode: addDummyNode, - simplify: simplify, - asNonCompoundGraph: asNonCompoundGraph, - successorWeights: successorWeights, - predecessorWeights: predecessorWeights, - intersectRect: intersectRect, - buildLayerMatrix: buildLayerMatrix, - normalizeRanks: normalizeRanks, - removeEmptyRanks: removeEmptyRanks, - addBorderNode: addBorderNode, - maxRank: maxRank, - partition: partition, - time: time, - notime: notime -}; - -/* - * Adds a dummy node to the graph and return v. - */ -function addDummyNode(g, type, attrs, name) { - var v; - do { - v = _.uniqueId(name); - } while (g.hasNode(v)); - - attrs.dummy = type; - g.setNode(v, attrs); - return v; -} - -/* - * Returns a new graph with only simple edges. Handles aggregation of data - * associated with multi-edges. - */ -function simplify(g) { - var simplified = new Graph().setGraph(g.graph()); - _.each(g.nodes(), function(v) { simplified.setNode(v, g.node(v)); }); - _.each(g.edges(), function(e) { - var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 }, - label = g.edge(e); - simplified.setEdge(e.v, e.w, { - weight: simpleLabel.weight + label.weight, - minlen: Math.max(simpleLabel.minlen, label.minlen) - }); - }); - return simplified; -} - -function asNonCompoundGraph(g) { - var simplified = new Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph()); - _.each(g.nodes(), function(v) { - if (!g.children(v).length) { - simplified.setNode(v, g.node(v)); - } - }); - _.each(g.edges(), function(e) { - simplified.setEdge(e, g.edge(e)); - }); - return simplified; -} - -function successorWeights(g) { - var weightMap = _.map(g.nodes(), function(v) { - var sucs = {}; - _.each(g.outEdges(v), function(e) { - sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight; - }); - return sucs; - }); - return _.zipObject(g.nodes(), weightMap); -} - -function predecessorWeights(g) { - var weightMap = _.map(g.nodes(), function(v) { - var preds = {}; - _.each(g.inEdges(v), function(e) { - preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight; - }); - return preds; - }); - return _.zipObject(g.nodes(), weightMap); -} - -/* - * Finds where a line starting at point ({x, y}) would intersect a rectangle - * ({x, y, width, height}) if it were pointing at the rectangle's center. - */ -function intersectRect(rect, point) { - var x = rect.x; - var y = rect.y; - - // Rectangle intersection algorithm from: - // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes - var dx = point.x - x; - var dy = point.y - y; - var w = rect.width / 2; - var h = rect.height / 2; - - if (!dx && !dy) { - throw new Error("Not possible to find intersection inside of the rectangle"); - } - - var sx, sy; - if (Math.abs(dy) * w > Math.abs(dx) * h) { - // Intersection is top or bottom of rect. - if (dy < 0) { - h = -h; - } - sx = h * dx / dy; - sy = h; - } else { - // Intersection is left or right of rect. - if (dx < 0) { - w = -w; - } - sx = w; - sy = w * dy / dx; - } - - return { x: x + sx, y: y + sy }; -} - -/* - * Given a DAG with each node assigned "rank" and "order" properties, this - * function will produce a matrix with the ids of each node. - */ -function buildLayerMatrix(g) { - var layering = _.map(_.range(maxRank(g) + 1), function() { return []; }); - _.each(g.nodes(), function(v) { - var node = g.node(v), - rank = node.rank; - if (!_.isUndefined(rank)) { - layering[rank][node.order] = v; - } - }); - return layering; -} - -/* - * Adjusts the ranks for all nodes in the graph such that all nodes v have - * rank(v) >= 0 and at least one node w has rank(w) = 0. - */ -function normalizeRanks(g) { - var min = _.min(_.map(g.nodes(), function(v) { return g.node(v).rank; })); - _.each(g.nodes(), function(v) { - var node = g.node(v); - if (_.has(node, "rank")) { - node.rank -= min; - } - }); -} - -function removeEmptyRanks(g) { - // Ranks may not start at 0, so we need to offset them - var offset = _.min(_.map(g.nodes(), function(v) { return g.node(v).rank; })); - - var layers = []; - _.each(g.nodes(), function(v) { - var rank = g.node(v).rank - offset; - if (!_.has(layers, rank)) { - layers[rank] = []; - } - layers[rank].push(v); - }); - - var delta = 0, - nodeRankFactor = g.graph().nodeRankFactor; - _.each(layers, function(vs, i) { - if (_.isUndefined(vs) && i % nodeRankFactor !== 0) { - --delta; - } else if (delta) { - _.each(vs, function(v) { g.node(v).rank += delta; }); - } - }); -} - -function addBorderNode(g, prefix, rank, order) { - var node = { - width: 0, - height: 0 - }; - if (arguments.length >= 4) { - node.rank = rank; - node.order = order; - } - return addDummyNode(g, "border", node, prefix); -} - -function maxRank(g) { - return _.max(_.map(g.nodes(), function(v) { - var rank = g.node(v).rank; - if (!_.isUndefined(rank)) { - return rank; - } - })); -} - -/* - * Partition a collection into two groups: `lhs` and `rhs`. If the supplied - * function returns true for an entry it goes into `lhs`. Otherwise it goes - * into `rhs. - */ -function partition(collection, fn) { - var result = { lhs: [], rhs: [] }; - _.each(collection, function(value) { - if (fn(value)) { - result.lhs.push(value); - } else { - result.rhs.push(value); - } - }); - return result; -} - -/* - * Returns a new function that wraps `fn` with a timer. The wrapper logs the - * time it takes to execute the function. - */ -function time(name, fn) { - var start = _.now(); - try { - return fn(); - } finally { - console.log(name + " time: " + (_.now() - start) + "ms"); - } -} - -function notime(name, fn) { - return fn(); -} - -},{"./graphlib":7,"./lodash":10}],30:[function(require,module,exports){ -module.exports = "0.6.4"; - -},{}]},{},[1])(1) -}); \ No newline at end of file diff --git a/vitrage_dashboard/dashboard/static/vendor/graphlib/graphlib.core.js b/vitrage_dashboard/dashboard/static/vendor/graphlib/graphlib.core.js deleted file mode 100644 index 9ccbe3f..0000000 --- a/vitrage_dashboard/dashboard/static/vendor/graphlib/graphlib.core.js +++ /dev/null @@ -1,1237 +0,0 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { - v = pq.removeMin(); - vEntry = results[v]; - if (vEntry.distance === Number.POSITIVE_INFINITY) { - break; - } - - edgeFn(v).forEach(updateNeighbors); - } - - return results; -} - -},{"../data/priority-queue":16,"../lodash":20}],7:[function(require,module,exports){ -var _ = require("../lodash"), - tarjan = require("./tarjan"); - -module.exports = findCycles; - -function findCycles(g) { - return _.filter(tarjan(g), function(cmpt) { - return cmpt.length > 1 || (cmpt.length === 1 && g.hasEdge(cmpt[0], cmpt[0])); - }); -} - -},{"../lodash":20,"./tarjan":14}],8:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = floydWarshall; - -var DEFAULT_WEIGHT_FUNC = _.constant(1); - -function floydWarshall(g, weightFn, edgeFn) { - return runFloydWarshall(g, - weightFn || DEFAULT_WEIGHT_FUNC, - edgeFn || function(v) { return g.outEdges(v); }); -} - -function runFloydWarshall(g, weightFn, edgeFn) { - var results = {}, - nodes = g.nodes(); - - nodes.forEach(function(v) { - results[v] = {}; - results[v][v] = { distance: 0 }; - nodes.forEach(function(w) { - if (v !== w) { - results[v][w] = { distance: Number.POSITIVE_INFINITY }; - } - }); - edgeFn(v).forEach(function(edge) { - var w = edge.v === v ? edge.w : edge.v, - d = weightFn(edge); - results[v][w] = { distance: d, predecessor: v }; - }); - }); - - nodes.forEach(function(k) { - var rowK = results[k]; - nodes.forEach(function(i) { - var rowI = results[i]; - nodes.forEach(function(j) { - var ik = rowI[k]; - var kj = rowK[j]; - var ij = rowI[j]; - var altDistance = ik.distance + kj.distance; - if (altDistance < ij.distance) { - ij.distance = altDistance; - ij.predecessor = kj.predecessor; - } - }); - }); - }); - - return results; -} - -},{"../lodash":20}],9:[function(require,module,exports){ -module.exports = { - components: require("./components"), - dijkstra: require("./dijkstra"), - dijkstraAll: require("./dijkstra-all"), - findCycles: require("./find-cycles"), - floydWarshall: require("./floyd-warshall"), - isAcyclic: require("./is-acyclic"), - postorder: require("./postorder"), - preorder: require("./preorder"), - prim: require("./prim"), - tarjan: require("./tarjan"), - topsort: require("./topsort") -}; - -},{"./components":3,"./dijkstra":6,"./dijkstra-all":5,"./find-cycles":7,"./floyd-warshall":8,"./is-acyclic":10,"./postorder":11,"./preorder":12,"./prim":13,"./tarjan":14,"./topsort":15}],10:[function(require,module,exports){ -var topsort = require("./topsort"); - -module.exports = isAcyclic; - -function isAcyclic(g) { - try { - topsort(g); - } catch (e) { - if (e instanceof topsort.CycleException) { - return false; - } - throw e; - } - return true; -} - -},{"./topsort":15}],11:[function(require,module,exports){ -var dfs = require("./dfs"); - -module.exports = postorder; - -function postorder(g, vs) { - return dfs(g, vs, "post"); -} - -},{"./dfs":4}],12:[function(require,module,exports){ -var dfs = require("./dfs"); - -module.exports = preorder; - -function preorder(g, vs) { - return dfs(g, vs, "pre"); -} - -},{"./dfs":4}],13:[function(require,module,exports){ -var _ = require("../lodash"), - Graph = require("../graph"), - PriorityQueue = require("../data/priority-queue"); - -module.exports = prim; - -function prim(g, weightFunc) { - var result = new Graph(), - parents = {}, - pq = new PriorityQueue(), - v; - - function updateNeighbors(edge) { - var w = edge.v === v ? edge.w : edge.v, - pri = pq.priority(w); - if (pri !== undefined) { - var edgeWeight = weightFunc(edge); - if (edgeWeight < pri) { - parents[w] = v; - pq.decrease(w, edgeWeight); - } - } - } - - if (g.nodeCount() === 0) { - return result; - } - - _.each(g.nodes(), function(v) { - pq.add(v, Number.POSITIVE_INFINITY); - result.setNode(v); - }); - - // Start from an arbitrary node - pq.decrease(g.nodes()[0], 0); - - var init = false; - while (pq.size() > 0) { - v = pq.removeMin(); - if (_.has(parents, v)) { - result.setEdge(v, parents[v]); - } else if (init) { - throw new Error("Input graph is not connected: " + g); - } else { - init = true; - } - - g.nodeEdges(v).forEach(updateNeighbors); - } - - return result; -} - -},{"../data/priority-queue":16,"../graph":17,"../lodash":20}],14:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = tarjan; - -function tarjan(g) { - var index = 0, - stack = [], - visited = {}, // node id -> { onStack, lowlink, index } - results = []; - - function dfs(v) { - var entry = visited[v] = { - onStack: true, - lowlink: index, - index: index++ - }; - stack.push(v); - - g.successors(v).forEach(function(w) { - if (!_.has(visited, w)) { - dfs(w); - entry.lowlink = Math.min(entry.lowlink, visited[w].lowlink); - } else if (visited[w].onStack) { - entry.lowlink = Math.min(entry.lowlink, visited[w].index); - } - }); - - if (entry.lowlink === entry.index) { - var cmpt = [], - w; - do { - w = stack.pop(); - visited[w].onStack = false; - cmpt.push(w); - } while (v !== w); - results.push(cmpt); - } - } - - g.nodes().forEach(function(v) { - if (!_.has(visited, v)) { - dfs(v); - } - }); - - return results; -} - -},{"../lodash":20}],15:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = topsort; -topsort.CycleException = CycleException; - -function topsort(g) { - var visited = {}, - stack = {}, - results = []; - - function visit(node) { - if (_.has(stack, node)) { - throw new CycleException(); - } - - if (!_.has(visited, node)) { - stack[node] = true; - visited[node] = true; - _.each(g.predecessors(node), visit); - delete stack[node]; - results.push(node); - } - } - - _.each(g.sinks(), visit); - - if (_.size(visited) !== g.nodeCount()) { - throw new CycleException(); - } - - return results; -} - -function CycleException() {} - -},{"../lodash":20}],16:[function(require,module,exports){ -var _ = require("../lodash"); - -module.exports = PriorityQueue; - -/** - * A min-priority queue data structure. This algorithm is derived from Cormen, - * et al., "Introduction to Algorithms". The basic idea of a min-priority - * queue is that you can efficiently (in O(1) time) get the smallest key in - * the queue. Adding and removing elements takes O(log n) time. A key can - * have its priority decreased in O(log n) time. - */ -function PriorityQueue() { - this._arr = []; - this._keyIndices = {}; -} - -/** - * Returns the number of elements in the queue. Takes `O(1)` time. - */ -PriorityQueue.prototype.size = function() { - return this._arr.length; -}; - -/** - * Returns the keys that are in the queue. Takes `O(n)` time. - */ -PriorityQueue.prototype.keys = function() { - return this._arr.map(function(x) { return x.key; }); -}; - -/** - * Returns `true` if **key** is in the queue and `false` if not. - */ -PriorityQueue.prototype.has = function(key) { - return _.has(this._keyIndices, key); -}; - -/** - * Returns the priority for **key**. If **key** is not present in the queue - * then this function returns `undefined`. Takes `O(1)` time. - * - * @param {Object} key - */ -PriorityQueue.prototype.priority = function(key) { - var index = this._keyIndices[key]; - if (index !== undefined) { - return this._arr[index].priority; - } -}; - -/** - * Returns the key for the minimum element in this queue. If the queue is - * empty this function throws an Error. Takes `O(1)` time. - */ -PriorityQueue.prototype.min = function() { - if (this.size() === 0) { - throw new Error("Queue underflow"); - } - return this._arr[0].key; -}; - -/** - * Inserts a new key into the priority queue. If the key already exists in - * the queue this function returns `false`; otherwise it will return `true`. - * Takes `O(n)` time. - * - * @param {Object} key the key to add - * @param {Number} priority the initial priority for the key - */ -PriorityQueue.prototype.add = function(key, priority) { - var keyIndices = this._keyIndices; - key = String(key); - if (!_.has(keyIndices, key)) { - var arr = this._arr; - var index = arr.length; - keyIndices[key] = index; - arr.push({key: key, priority: priority}); - this._decrease(index); - return true; - } - return false; -}; - -/** - * Removes and returns the smallest key in the queue. Takes `O(log n)` time. - */ -PriorityQueue.prototype.removeMin = function() { - this._swap(0, this._arr.length - 1); - var min = this._arr.pop(); - delete this._keyIndices[min.key]; - this._heapify(0); - return min.key; -}; - -/** - * Decreases the priority for **key** to **priority**. If the new priority is - * greater than the previous priority, this function will throw an Error. - * - * @param {Object} key the key for which to raise priority - * @param {Number} priority the new priority for the key - */ -PriorityQueue.prototype.decrease = function(key, priority) { - var index = this._keyIndices[key]; - if (priority > this._arr[index].priority) { - throw new Error("New priority is greater than current priority. " + - "Key: " + key + " Old: " + this._arr[index].priority + " New: " + priority); - } - this._arr[index].priority = priority; - this._decrease(index); -}; - -PriorityQueue.prototype._heapify = function(i) { - var arr = this._arr; - var l = 2 * i, - r = l + 1, - largest = i; - if (l < arr.length) { - largest = arr[l].priority < arr[largest].priority ? l : largest; - if (r < arr.length) { - largest = arr[r].priority < arr[largest].priority ? r : largest; - } - if (largest !== i) { - this._swap(i, largest); - this._heapify(largest); - } - } -}; - -PriorityQueue.prototype._decrease = function(index) { - var arr = this._arr; - var priority = arr[index].priority; - var parent; - while (index !== 0) { - parent = index >> 1; - if (arr[parent].priority < priority) { - break; - } - this._swap(index, parent); - index = parent; - } -}; - -PriorityQueue.prototype._swap = function(i, j) { - var arr = this._arr; - var keyIndices = this._keyIndices; - var origArrI = arr[i]; - var origArrJ = arr[j]; - arr[i] = origArrJ; - arr[j] = origArrI; - keyIndices[origArrJ.key] = i; - keyIndices[origArrI.key] = j; -}; - -},{"../lodash":20}],17:[function(require,module,exports){ -"use strict"; - -var _ = require("./lodash"); - -module.exports = Graph; - -var DEFAULT_EDGE_NAME = "\x00", - GRAPH_NODE = "\x00", - EDGE_KEY_DELIM = "\x01"; - -// Implementation notes: -// -// * Node id query functions should return string ids for the nodes -// * Edge id query functions should return an "edgeObj", edge object, that is -// composed of enough information to uniquely identify an edge: {v, w, name}. -// * Internally we use an "edgeId", a stringified form of the edgeObj, to -// reference edges. This is because we need a performant way to look these -// edges up and, object properties, which have string keys, are the closest -// we're going to get to a performant hashtable in JavaScript. - -function Graph(opts) { - this._isDirected = _.has(opts, "directed") ? opts.directed : true; - this._isMultigraph = _.has(opts, "multigraph") ? opts.multigraph : false; - this._isCompound = _.has(opts, "compound") ? opts.compound : false; - - // Label for the graph itself - this._label = undefined; - - // Defaults to be set when creating a new node - this._defaultNodeLabelFn = _.constant(undefined); - - // Defaults to be set when creating a new edge - this._defaultEdgeLabelFn = _.constant(undefined); - - // v -> label - this._nodes = {}; - - if (this._isCompound) { - // v -> parent - this._parent = {}; - - // v -> children - this._children = {}; - this._children[GRAPH_NODE] = {}; - } - - // v -> edgeObj - this._in = {}; - - // u -> v -> Number - this._preds = {}; - - // v -> edgeObj - this._out = {}; - - // v -> w -> Number - this._sucs = {}; - - // e -> edgeObj - this._edgeObjs = {}; - - // e -> label - this._edgeLabels = {}; -} - -/* Number of nodes in the graph. Should only be changed by the implementation. */ -Graph.prototype._nodeCount = 0; - -/* Number of edges in the graph. Should only be changed by the implementation. */ -Graph.prototype._edgeCount = 0; - - -/* === Graph functions ========= */ - -Graph.prototype.isDirected = function() { - return this._isDirected; -}; - -Graph.prototype.isMultigraph = function() { - return this._isMultigraph; -}; - -Graph.prototype.isCompound = function() { - return this._isCompound; -}; - -Graph.prototype.setGraph = function(label) { - this._label = label; - return this; -}; - -Graph.prototype.graph = function() { - return this._label; -}; - - -/* === Node functions ========== */ - -Graph.prototype.setDefaultNodeLabel = function(newDefault) { - if (!_.isFunction(newDefault)) { - newDefault = _.constant(newDefault); - } - this._defaultNodeLabelFn = newDefault; - return this; -}; - -Graph.prototype.nodeCount = function() { - return this._nodeCount; -}; - -Graph.prototype.nodes = function() { - return _.keys(this._nodes); -}; - -Graph.prototype.sources = function() { - return _.filter(this.nodes(), function(v) { - return _.isEmpty(this._in[v]); - }, this); -}; - -Graph.prototype.sinks = function() { - return _.filter(this.nodes(), function(v) { - return _.isEmpty(this._out[v]); - }, this); -}; - -Graph.prototype.setNodes = function(vs, value) { - var args = arguments; - _.each(vs, function(v) { - if (args.length > 1) { - this.setNode(v, value); - } else { - this.setNode(v); - } - }, this); - return this; -}; - -Graph.prototype.setNode = function(v, value) { - if (_.has(this._nodes, v)) { - if (arguments.length > 1) { - this._nodes[v] = value; - } - return this; - } - - this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); - if (this._isCompound) { - this._parent[v] = GRAPH_NODE; - this._children[v] = {}; - this._children[GRAPH_NODE][v] = true; - } - this._in[v] = {}; - this._preds[v] = {}; - this._out[v] = {}; - this._sucs[v] = {}; - ++this._nodeCount; - return this; -}; - -Graph.prototype.node = function(v) { - return this._nodes[v]; -}; - -Graph.prototype.hasNode = function(v) { - return _.has(this._nodes, v); -}; - -Graph.prototype.removeNode = function(v) { - var self = this; - if (_.has(this._nodes, v)) { - var removeEdge = function(e) { self.removeEdge(self._edgeObjs[e]); }; - delete this._nodes[v]; - if (this._isCompound) { - this._removeFromParentsChildList(v); - delete this._parent[v]; - _.each(this.children(v), function(child) { - this.setParent(child); - }, this); - delete this._children[v]; - } - _.each(_.keys(this._in[v]), removeEdge); - delete this._in[v]; - delete this._preds[v]; - _.each(_.keys(this._out[v]), removeEdge); - delete this._out[v]; - delete this._sucs[v]; - --this._nodeCount; - } - return this; -}; - -Graph.prototype.setParent = function(v, parent) { - if (!this._isCompound) { - throw new Error("Cannot set parent in a non-compound graph"); - } - - if (_.isUndefined(parent)) { - parent = GRAPH_NODE; - } else { - // Coerce parent to string - parent += ""; - for (var ancestor = parent; - !_.isUndefined(ancestor); - ancestor = this.parent(ancestor)) { - if (ancestor === v) { - throw new Error("Setting " + parent+ " as parent of " + v + - " would create create a cycle"); - } - } - - this.setNode(parent); - } - - this.setNode(v); - this._removeFromParentsChildList(v); - this._parent[v] = parent; - this._children[parent][v] = true; - return this; -}; - -Graph.prototype._removeFromParentsChildList = function(v) { - delete this._children[this._parent[v]][v]; -}; - -Graph.prototype.parent = function(v) { - if (this._isCompound) { - var parent = this._parent[v]; - if (parent !== GRAPH_NODE) { - return parent; - } - } -}; - -Graph.prototype.children = function(v) { - if (_.isUndefined(v)) { - v = GRAPH_NODE; - } - - if (this._isCompound) { - var children = this._children[v]; - if (children) { - return _.keys(children); - } - } else if (v === GRAPH_NODE) { - return this.nodes(); - } else if (this.hasNode(v)) { - return []; - } -}; - -Graph.prototype.predecessors = function(v) { - var predsV = this._preds[v]; - if (predsV) { - return _.keys(predsV); - } -}; - -Graph.prototype.successors = function(v) { - var sucsV = this._sucs[v]; - if (sucsV) { - return _.keys(sucsV); - } -}; - -Graph.prototype.neighbors = function(v) { - var preds = this.predecessors(v); - if (preds) { - return _.union(preds, this.successors(v)); - } -}; - -Graph.prototype.filterNodes = function(filter) { - var copy = new this.constructor({ - directed: this._isDirected, - multigraph: this._isMultigraph, - compound: this._isCompound - }); - - copy.setGraph(this.graph()); - - _.each(this._nodes, function(value, v) { - if (filter(v)) { - copy.setNode(v, value); - } - }, this); - - _.each(this._edgeObjs, function(e) { - if (copy.hasNode(e.v) && copy.hasNode(e.w)) { - copy.setEdge(e, this.edge(e)); - } - }, this); - - var self = this; - var parents = {}; - function findParent(v) { - var parent = self.parent(v); - if (parent === undefined || copy.hasNode(parent)) { - parents[v] = parent; - return parent; - } else if (parent in parents) { - return parents[parent]; - } else { - return findParent(parent); - } - } - - if (this._isCompound) { - _.each(copy.nodes(), function(v) { - copy.setParent(v, findParent(v)); - }); - } - - return copy; -}; - -/* === Edge functions ========== */ - -Graph.prototype.setDefaultEdgeLabel = function(newDefault) { - if (!_.isFunction(newDefault)) { - newDefault = _.constant(newDefault); - } - this._defaultEdgeLabelFn = newDefault; - return this; -}; - -Graph.prototype.edgeCount = function() { - return this._edgeCount; -}; - -Graph.prototype.edges = function() { - return _.values(this._edgeObjs); -}; - -Graph.prototype.setPath = function(vs, value) { - var self = this, - args = arguments; - _.reduce(vs, function(v, w) { - if (args.length > 1) { - self.setEdge(v, w, value); - } else { - self.setEdge(v, w); - } - return w; - }); - return this; -}; - -/* - * setEdge(v, w, [value, [name]]) - * setEdge({ v, w, [name] }, [value]) - */ -Graph.prototype.setEdge = function() { - var v, w, name, value, - valueSpecified = false, - arg0 = arguments[0]; - - if (typeof arg0 === "object" && arg0 !== null && "v" in arg0) { - v = arg0.v; - w = arg0.w; - name = arg0.name; - if (arguments.length === 2) { - value = arguments[1]; - valueSpecified = true; - } - } else { - v = arg0; - w = arguments[1]; - name = arguments[3]; - if (arguments.length > 2) { - value = arguments[2]; - valueSpecified = true; - } - } - - v = "" + v; - w = "" + w; - if (!_.isUndefined(name)) { - name = "" + name; - } - - var e = edgeArgsToId(this._isDirected, v, w, name); - if (_.has(this._edgeLabels, e)) { - if (valueSpecified) { - this._edgeLabels[e] = value; - } - return this; - } - - if (!_.isUndefined(name) && !this._isMultigraph) { - throw new Error("Cannot set a named edge when isMultigraph = false"); - } - - // It didn't exist, so we need to create it. - // First ensure the nodes exist. - this.setNode(v); - this.setNode(w); - - this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name); - - var edgeObj = edgeArgsToObj(this._isDirected, v, w, name); - // Ensure we add undirected edges in a consistent way. - v = edgeObj.v; - w = edgeObj.w; - - Object.freeze(edgeObj); - this._edgeObjs[e] = edgeObj; - incrementOrInitEntry(this._preds[w], v); - incrementOrInitEntry(this._sucs[v], w); - this._in[w][e] = edgeObj; - this._out[v][e] = edgeObj; - this._edgeCount++; - return this; -}; - -Graph.prototype.edge = function(v, w, name) { - var e = (arguments.length === 1 - ? edgeObjToId(this._isDirected, arguments[0]) - : edgeArgsToId(this._isDirected, v, w, name)); - return this._edgeLabels[e]; -}; - -Graph.prototype.hasEdge = function(v, w, name) { - var e = (arguments.length === 1 - ? edgeObjToId(this._isDirected, arguments[0]) - : edgeArgsToId(this._isDirected, v, w, name)); - return _.has(this._edgeLabels, e); -}; - -Graph.prototype.removeEdge = function(v, w, name) { - var e = (arguments.length === 1 - ? edgeObjToId(this._isDirected, arguments[0]) - : edgeArgsToId(this._isDirected, v, w, name)), - edge = this._edgeObjs[e]; - if (edge) { - v = edge.v; - w = edge.w; - delete this._edgeLabels[e]; - delete this._edgeObjs[e]; - decrementOrRemoveEntry(this._preds[w], v); - decrementOrRemoveEntry(this._sucs[v], w); - delete this._in[w][e]; - delete this._out[v][e]; - this._edgeCount--; - } - return this; -}; - -Graph.prototype.inEdges = function(v, u) { - var inV = this._in[v]; - if (inV) { - var edges = _.values(inV); - if (!u) { - return edges; - } - return _.filter(edges, function(edge) { return edge.v === u; }); - } -}; - -Graph.prototype.outEdges = function(v, w) { - var outV = this._out[v]; - if (outV) { - var edges = _.values(outV); - if (!w) { - return edges; - } - return _.filter(edges, function(edge) { return edge.w === w; }); - } -}; - -Graph.prototype.nodeEdges = function(v, w) { - var inEdges = this.inEdges(v, w); - if (inEdges) { - return inEdges.concat(this.outEdges(v, w)); - } -}; - -function incrementOrInitEntry(map, k) { - if (map[k]) { - map[k]++; - } else { - map[k] = 1; - } -} - -function decrementOrRemoveEntry(map, k) { - if (!--map[k]) { delete map[k]; } -} - -function edgeArgsToId(isDirected, v_, w_, name) { - var v = "" + v_; - var w = "" + w_; - if (!isDirected && v > w) { - var tmp = v; - v = w; - w = tmp; - } - return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + - (_.isUndefined(name) ? DEFAULT_EDGE_NAME : name); -} - -function edgeArgsToObj(isDirected, v_, w_, name) { - var v = "" + v_; - var w = "" + w_; - if (!isDirected && v > w) { - var tmp = v; - v = w; - w = tmp; - } - var edgeObj = { v: v, w: w }; - if (name) { - edgeObj.name = name; - } - return edgeObj; -} - -function edgeObjToId(isDirected, edgeObj) { - return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); -} - -},{"./lodash":20}],18:[function(require,module,exports){ -// Includes only the "core" of graphlib -module.exports = { - Graph: require("./graph"), - version: require("./version") -}; - -},{"./graph":17,"./version":21}],19:[function(require,module,exports){ -var _ = require("./lodash"), - Graph = require("./graph"); - -module.exports = { - write: write, - read: read -}; - -function write(g) { - var json = { - options: { - directed: g.isDirected(), - multigraph: g.isMultigraph(), - compound: g.isCompound() - }, - nodes: writeNodes(g), - edges: writeEdges(g) - }; - if (!_.isUndefined(g.graph())) { - json.value = _.clone(g.graph()); - } - return json; -} - -function writeNodes(g) { - return _.map(g.nodes(), function(v) { - var nodeValue = g.node(v), - parent = g.parent(v), - node = { v: v }; - if (!_.isUndefined(nodeValue)) { - node.value = nodeValue; - } - if (!_.isUndefined(parent)) { - node.parent = parent; - } - return node; - }); -} - -function writeEdges(g) { - return _.map(g.edges(), function(e) { - var edgeValue = g.edge(e), - edge = { v: e.v, w: e.w }; - if (!_.isUndefined(e.name)) { - edge.name = e.name; - } - if (!_.isUndefined(edgeValue)) { - edge.value = edgeValue; - } - return edge; - }); -} - -function read(json) { - var g = new Graph(json.options).setGraph(json.value); - _.each(json.nodes, function(entry) { - g.setNode(entry.v, entry.value); - if (entry.parent) { - g.setParent(entry.v, entry.parent); - } - }); - _.each(json.edges, function(entry) { - g.setEdge({ v: entry.v, w: entry.w, name: entry.name }, entry.value); - }); - return g; -} - -},{"./graph":17,"./lodash":20}],20:[function(require,module,exports){ -/* global window */ - -var lodash; - -if (typeof require === "function") { - try { - lodash = require("lodash"); - } catch (e) {} -} - -if (!lodash) { - lodash = window._; -} - -module.exports = lodash; - -},{"lodash":undefined}],21:[function(require,module,exports){ -module.exports = '1.0.7'; - -},{}]},{},[1]); diff --git a/vitrage_dashboard/dashboard/static/vendor/lodash/lodash.compat.js b/vitrage_dashboard/dashboard/static/vendor/lodash/lodash.compat.js deleted file mode 100644 index 5ce0c30..0000000 --- a/vitrage_dashboard/dashboard/static/vendor/lodash/lodash.compat.js +++ /dev/null @@ -1,7158 +0,0 @@ -/** - * @license - * Lo-Dash 2.4.2 (Custom Build) - * Build: `lodash -o ./dist/lodash.compat.js` - * Copyright 2012-2013 The Dojo Foundation - * Based on Underscore.js 1.5.2 - * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre ES5 environments */ - var undefined; - - /** Used to pool arrays and objects used internally */ - var arrayPool = [], - objectPool = []; - - /** Used to generate unique IDs */ - var idCounter = 0; - - /** Used internally to indicate various things */ - var indicatorObject = {}; - - /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ - var keyPrefix = +new Date + ''; - - /** Used as the size when optimizations are enabled for large arrays */ - var largeArraySize = 75; - - /** Used as the max size of the `arrayPool` and `objectPool` */ - var maxPoolSize = 40; - - /** Used to detect and test whitespace */ - var whitespace = ( - // whitespace - ' \t\x0B\f\xA0\ufeff' + - - // line terminators - '\n\r\u2028\u2029' + - - // unicode category "Zs" space separators - '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' - ); - - /** Used to match empty string literals in compiled template source */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** - * Used to match ES6 template delimiters - * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match regexp flags from their coerced string values */ - var reFlags = /\w*$/; - - /** Used to detected named functions */ - var reFuncName = /^\s*function[ \n\r\t]+\w/; - - /** Used to match "interpolate" template delimiters */ - var reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match leading whitespace and zeros to be removed */ - var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); - - /** Used to ensure capturing order of template delimiters */ - var reNoMatch = /($^)/; - - /** Used to detect functions containing a `this` reference */ - var reThis = /\bthis\b/; - - /** Used to match unescaped characters in compiled string literals */ - var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; - - /** Used to assign default `context` object properties */ - var contextProps = [ - 'Array', 'Boolean', 'Date', 'Error', 'Function', 'Math', 'Number', 'Object', - 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', - 'parseInt', 'setTimeout' - ]; - - /** Used to fix the JScript [[DontEnum]] bug */ - var shadowedProps = [ - 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', - 'toLocaleString', 'toString', 'valueOf' - ]; - - /** Used to make template sourceURLs easier to identify */ - var templateCounter = 0; - - /** `Object#toString` result shortcuts */ - var argsClass = '[object Arguments]', - arrayClass = '[object Array]', - boolClass = '[object Boolean]', - dateClass = '[object Date]', - errorClass = '[object Error]', - funcClass = '[object Function]', - numberClass = '[object Number]', - objectClass = '[object Object]', - regexpClass = '[object RegExp]', - stringClass = '[object String]'; - - /** Used to identify object classifications that `_.clone` supports */ - var cloneableClasses = {}; - cloneableClasses[funcClass] = false; - cloneableClasses[argsClass] = cloneableClasses[arrayClass] = - cloneableClasses[boolClass] = cloneableClasses[dateClass] = - cloneableClasses[numberClass] = cloneableClasses[objectClass] = - cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; - - /** Used as an internal `_.debounce` options object */ - var debounceOptions = { - 'leading': false, - 'maxWait': 0, - 'trailing': false - }; - - /** Used as the property descriptor for `__bindData__` */ - var descriptor = { - 'configurable': false, - 'enumerable': false, - 'value': null, - 'writable': false - }; - - /** Used as the data object for `iteratorTemplate` */ - var iteratorData = { - 'args': '', - 'array': null, - 'bottom': '', - 'firstArg': '', - 'init': '', - 'keys': null, - 'loop': '', - 'shadowedProps': null, - 'support': null, - 'top': '', - 'useHas': false - }; - - /** Used to determine if values are of the language type Object */ - var objectTypes = { - 'boolean': false, - 'function': true, - 'object': true, - 'number': false, - 'string': false, - 'undefined': false - }; - - /** Used to escape characters for inclusion in compiled string literals */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\t': 't', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Used as a reference to the global object */ - var root = (objectTypes[typeof window] && window) || this; - - /** Detect free variable `exports` */ - var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; - - /** Detect free variable `module` */ - var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports` */ - var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; - - /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ - var freeGlobal = objectTypes[typeof global] && global; - if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { - root = freeGlobal; - } - - /*--------------------------------------------------------------------------*/ - - /** - * The base implementation of `_.indexOf` without support for binary searches - * or `fromIndex` constraints. - * - * @private - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value or `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - var index = (fromIndex || 0) - 1, - length = array ? array.length : 0; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * An implementation of `_.contains` for cache objects that mimics the return - * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. - * - * @private - * @param {Object} cache The cache object to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns `0` if `value` is found, else `-1`. - */ - function cacheIndexOf(cache, value) { - var type = typeof value; - cache = cache.cache; - - if (type == 'boolean' || value == null) { - return cache[value] ? 0 : -1; - } - if (type != 'number' && type != 'string') { - type = 'object'; - } - var key = type == 'number' ? value : keyPrefix + value; - cache = (cache = cache[type]) && cache[key]; - - return type == 'object' - ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) - : (cache ? 0 : -1); - } - - /** - * Adds a given value to the corresponding cache object. - * - * @private - * @param {*} value The value to add to the cache. - */ - function cachePush(value) { - var cache = this.cache, - type = typeof value; - - if (type == 'boolean' || value == null) { - cache[value] = true; - } else { - if (type != 'number' && type != 'string') { - type = 'object'; - } - var key = type == 'number' ? value : keyPrefix + value, - typeCache = cache[type] || (cache[type] = {}); - - if (type == 'object') { - (typeCache[key] || (typeCache[key] = [])).push(value); - } else { - typeCache[key] = true; - } - } - } - - /** - * Used by `_.max` and `_.min` as the default callback when a given - * collection is a string value. - * - * @private - * @param {string} value The character to inspect. - * @returns {number} Returns the code unit of given character. - */ - function charAtCallback(value) { - return value.charCodeAt(0); - } - - /** - * Used by `sortBy` to compare transformed `collection` elements, stable sorting - * them in ascending order. - * - * @private - * @param {Object} a The object to compare to `b`. - * @param {Object} b The object to compare to `a`. - * @returns {number} Returns the sort order indicator of `1` or `-1`. - */ - function compareAscending(a, b) { - var ac = a.criteria, - bc = b.criteria, - index = -1, - length = ac.length; - - while (++index < length) { - var value = ac[index], - other = bc[index]; - - if (value !== other) { - if (value > other || typeof value == 'undefined') { - return 1; - } - if (value < other || typeof other == 'undefined') { - return -1; - } - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to return the same value for - // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 - // - // This also ensures a stable sort in V8 and other engines. - // See http://code.google.com/p/v8/issues/detail?id=90 - return a.index - b.index; - } - - /** - * Creates a cache object to optimize linear searches of large arrays. - * - * @private - * @param {Array} [array=[]] The array to search. - * @returns {null|Object} Returns the cache object or `null` if caching should not be used. - */ - function createCache(array) { - var index = -1, - length = array.length, - first = array[0], - mid = array[(length / 2) | 0], - last = array[length - 1]; - - if (first && typeof first == 'object' && - mid && typeof mid == 'object' && last && typeof last == 'object') { - return false; - } - var cache = getObject(); - cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; - - var result = getObject(); - result.array = array; - result.cache = cache; - result.push = cachePush; - - while (++index < length) { - result.push(array[index]); - } - return result; - } - - /** - * Used by `template` to escape characters for inclusion in compiled - * string literals. - * - * @private - * @param {string} match The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(match) { - return '\\' + stringEscapes[match]; - } - - /** - * Gets an array from the array pool or creates a new one if the pool is empty. - * - * @private - * @returns {Array} The array from the pool. - */ - function getArray() { - return arrayPool.pop() || []; - } - - /** - * Gets an object from the object pool or creates a new one if the pool is empty. - * - * @private - * @returns {Object} The object from the pool. - */ - function getObject() { - return objectPool.pop() || { - 'array': null, - 'cache': null, - 'criteria': null, - 'false': false, - 'index': 0, - 'null': false, - 'number': null, - 'object': null, - 'push': null, - 'string': null, - 'true': false, - 'undefined': false, - 'value': null - }; - } - - /** - * Checks if `value` is a DOM node in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a DOM node, else `false`. - */ - function isNode(value) { - // IE < 9 presents DOM nodes as `Object` objects except they have `toString` - // methods that are `typeof` "string" and still can coerce nodes to strings - return typeof value.toString != 'function' && typeof (value + '') == 'string'; - } - - /** - * Releases the given array back to the array pool. - * - * @private - * @param {Array} [array] The array to release. - */ - function releaseArray(array) { - array.length = 0; - if (arrayPool.length < maxPoolSize) { - arrayPool.push(array); - } - } - - /** - * Releases the given object back to the object pool. - * - * @private - * @param {Object} [object] The object to release. - */ - function releaseObject(object) { - var cache = object.cache; - if (cache) { - releaseObject(cache); - } - object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; - if (objectPool.length < maxPoolSize) { - objectPool.push(object); - } - } - - /** - * Slices the `collection` from the `start` index up to, but not including, - * the `end` index. - * - * Note: This function is used instead of `Array#slice` to support node lists - * in IE < 9 and to ensure dense arrays are returned. - * - * @private - * @param {Array|Object|string} collection The collection to slice. - * @param {number} start The start index. - * @param {number} end The end index. - * @returns {Array} Returns the new array. - */ - function slice(array, start, end) { - start || (start = 0); - if (typeof end == 'undefined') { - end = array ? array.length : 0; - } - var index = -1, - length = end - start || 0, - result = Array(length < 0 ? 0 : length); - - while (++index < length) { - result[index] = array[start + index]; - } - return result; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Create a new `lodash` function using the given context object. - * - * @static - * @memberOf _ - * @category Utilities - * @param {Object} [context=root] The context object. - * @returns {Function} Returns the `lodash` function. - */ - function runInContext(context) { - // Avoid issues with some ES3 environments that attempt to use values, named - // after built-in constructors like `Object`, for the creation of literals. - // ES5 clears this up by stating that literals must use built-in constructors. - // See http://es5.github.io/#x11.1.5. - context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; - - /** Native constructor references */ - var Array = context.Array, - Boolean = context.Boolean, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Number = context.Number, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; - - /** - * Used for `Array` method references. - * - * Normally `Array.prototype` would suffice, however, using an array literal - * avoids issues in Narwhal. - */ - var arrayRef = []; - - /** Used for native method references */ - var errorProto = Error.prototype, - objectProto = Object.prototype, - stringProto = String.prototype; - - /** Used to restore the original `_` reference in `noConflict` */ - var oldDash = context._; - - /** Used to resolve the internal [[Class]] of values */ - var toString = objectProto.toString; - - /** Used to detect if a method is native */ - var reNative = RegExp('^' + - String(toString) - .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - .replace(/toString| for [^\]]+/g, '.*?') + '$' - ); - - /** Native method shortcuts */ - var ceil = Math.ceil, - clearTimeout = context.clearTimeout, - floor = Math.floor, - fnToString = Function.prototype.toString, - getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, - hasOwnProperty = objectProto.hasOwnProperty, - push = arrayRef.push, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - setTimeout = context.setTimeout, - splice = arrayRef.splice, - unshift = arrayRef.unshift; - - /** Used to set meta data on functions */ - var defineProperty = (function() { - // IE 8 only accepts DOM elements - try { - var o = {}, - func = isNative(func = Object.defineProperty) && func, - result = func(o, o, o) && func; - } catch(e) { } - return result; - }()); - - /* Native method shortcuts for methods with the same name as other `lodash` methods */ - var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, - nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, - nativeIsFinite = context.isFinite, - nativeIsNaN = context.isNaN, - nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, - nativeMax = Math.max, - nativeMin = Math.min, - nativeParseInt = context.parseInt, - nativeRandom = Math.random; - - /** Used to lookup a built-in constructor by [[Class]] */ - var ctorByClass = {}; - ctorByClass[arrayClass] = Array; - ctorByClass[boolClass] = Boolean; - ctorByClass[dateClass] = Date; - ctorByClass[funcClass] = Function; - ctorByClass[objectClass] = Object; - ctorByClass[numberClass] = Number; - ctorByClass[regexpClass] = RegExp; - ctorByClass[stringClass] = String; - - /** Used to avoid iterating non-enumerable properties in IE < 9 */ - var nonEnumProps = {}; - nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; - nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; - nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; - nonEnumProps[objectClass] = { 'constructor': true }; - - (function() { - var length = shadowedProps.length; - while (length--) { - var key = shadowedProps[length]; - for (var className in nonEnumProps) { - if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], key)) { - nonEnumProps[className][key] = false; - } - } - } - }()); - - /*--------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps the given value to enable intuitive - * method chaining. - * - * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: - * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, - * and `unshift` - * - * Chaining is supported in custom builds as long as the `value` method is - * implicitly or explicitly included in the build. - * - * The chainable wrapper functions are: - * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, - * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, - * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, - * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, - * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, - * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, - * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, - * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, - * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, - * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, - * and `zip` - * - * The non-chainable wrapper functions are: - * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, - * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, - * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, - * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, - * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, - * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, - * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, - * `template`, `unescape`, `uniqueId`, and `value` - * - * The wrapper functions `first` and `last` return wrapped values when `n` is - * provided, otherwise they return unwrapped values. - * - * Explicit chaining can be enabled by using the `_.chain` method. - * - * @name _ - * @constructor - * @category Chaining - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns a `lodash` instance. - * @example - * - * var wrapped = _([1, 2, 3]); - * - * // returns an unwrapped value - * wrapped.reduce(function(sum, num) { - * return sum + num; - * }); - * // => 6 - * - * // returns a wrapped value - * var squares = wrapped.map(function(num) { - * return num * num; - * }); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor - return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) - ? value - : new lodashWrapper(value); - } - - /** - * A fast path for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap in a `lodash` instance. - * @param {boolean} chainAll A flag to enable chaining for all methods - * @returns {Object} Returns a `lodash` instance. - */ - function lodashWrapper(value, chainAll) { - this.__chain__ = !!chainAll; - this.__wrapped__ = value; - } - // ensure `new lodashWrapper` is an instance of `lodash` - lodashWrapper.prototype = lodash.prototype; - - /** - * An object used to flag environments features. - * - * @static - * @memberOf _ - * @type Object - */ - var support = lodash.support = {}; - - (function() { - var ctor = function() { this.x = 1; }, - object = { '0': 1, 'length': 1 }, - props = []; - - ctor.prototype = { 'valueOf': 1, 'y': 1 }; - for (var key in new ctor) { props.push(key); } - for (key in arguments) { } - - /** - * Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). - * - * @memberOf _.support - * @type boolean - */ - support.argsClass = toString.call(arguments) == argsClass; - - /** - * Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5). - * - * @memberOf _.support - * @type boolean - */ - support.argsObject = arguments.constructor == Object && !(arguments instanceof Array); - - /** - * Detect if `name` or `message` properties of `Error.prototype` are - * enumerable by default. (IE < 9, Safari < 5.1) - * - * @memberOf _.support - * @type boolean - */ - support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); - - /** - * Detect if `prototype` properties are enumerable by default. - * - * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 - * (if the prototype or a property on the prototype has been set) - * incorrectly sets a function's `prototype` property [[Enumerable]] - * value to `true`. - * - * @memberOf _.support - * @type boolean - */ - support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); - - /** - * Detect if functions can be decompiled by `Function#toString` - * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). - * - * @memberOf _.support - * @type boolean - */ - support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); - - /** - * Detect if `Function#name` is supported (all but IE). - * - * @memberOf _.support - * @type boolean - */ - support.funcNames = typeof Function.name == 'string'; - - /** - * Detect if `arguments` object indexes are non-enumerable - * (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1). - * - * @memberOf _.support - * @type boolean - */ - support.nonEnumArgs = key != 0; - - /** - * Detect if properties shadowing those on `Object.prototype` are non-enumerable. - * - * In IE < 9 an objects own properties, shadowing non-enumerable ones, are - * made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug). - * - * @memberOf _.support - * @type boolean - */ - support.nonEnumShadows = !/valueOf/.test(props); - - /** - * Detect if own properties are iterated after inherited properties (all but IE < 9). - * - * @memberOf _.support - * @type boolean - */ - support.ownLast = props[0] != 'x'; - - /** - * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly. - * - * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` - * and `splice()` functions that fail to remove the last element, `value[0]`, - * of array-like objects even though the `length` property is set to `0`. - * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` - * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. - * - * @memberOf _.support - * @type boolean - */ - support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]); - - /** - * Detect lack of support for accessing string characters by index. - * - * IE < 8 can't access characters by index and IE 8 can only access - * characters by index on string literals. - * - * @memberOf _.support - * @type boolean - */ - support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; - - /** - * Detect if a DOM node's [[Class]] is resolvable (all but IE < 9) - * and that the JS engine errors when attempting to coerce an object to - * a string without a `toString` function. - * - * @memberOf _.support - * @type boolean - */ - try { - support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); - } catch(e) { - support.nodeClass = true; - } - }(1)); - - /** - * By default, the template delimiters used by Lo-Dash are similar to those in - * embedded Ruby (ERB). Change the following template settings to use alternative - * delimiters. - * - * @static - * @memberOf _ - * @type Object - */ - lodash.templateSettings = { - - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'escape': /<%-([\s\S]+?)%>/g, - - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'evaluate': /<%([\s\S]+?)%>/g, - - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'interpolate': reInterpolate, - - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type string - */ - 'variable': '', - - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type Object - */ - 'imports': { - - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type Function - */ - '_': lodash - } - }; - - /*--------------------------------------------------------------------------*/ - - /** - * The template used to create iterator functions. - * - * @private - * @param {Object} data The data object used to populate the text. - * @returns {string} Returns the interpolated text. - */ - var iteratorTemplate = function(obj) { - - var __p = 'var index, iterable = ' + - (obj.firstArg) + - ', result = ' + - (obj.init) + - ';\nif (!iterable) return result;\n' + - (obj.top) + - ';'; - if (obj.array) { - __p += '\nvar length = iterable.length; index = -1;\nif (' + - (obj.array) + - ') { '; - if (support.unindexedChars) { - __p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } '; - } - __p += '\n while (++index < length) {\n ' + - (obj.loop) + - ';\n }\n}\nelse { '; - } else if (support.nonEnumArgs) { - __p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' + - (obj.loop) + - ';\n }\n } else { '; - } - - if (support.enumPrototypes) { - __p += '\n var skipProto = typeof iterable == \'function\';\n '; - } - - if (support.enumErrorProps) { - __p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n '; - } - - var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); } - - if (obj.useHas && obj.keys) { - __p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n'; - if (conditions.length) { - __p += ' if (' + - (conditions.join(' && ')) + - ') {\n '; - } - __p += - (obj.loop) + - '; '; - if (conditions.length) { - __p += '\n }'; - } - __p += '\n } '; - } else { - __p += '\n for (index in iterable) {\n'; - if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) { - __p += ' if (' + - (conditions.join(' && ')) + - ') {\n '; - } - __p += - (obj.loop) + - '; '; - if (conditions.length) { - __p += '\n }'; - } - __p += '\n } '; - if (support.nonEnumShadows) { - __p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n '; - for (k = 0; k < 7; k++) { - __p += '\n index = \'' + - (obj.shadowedProps[k]) + - '\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))'; - if (!obj.useHas) { - __p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])'; - } - __p += ') {\n ' + - (obj.loop) + - ';\n } '; - } - __p += '\n } '; - } - - } - - if (obj.array || support.nonEnumArgs) { - __p += '\n}'; - } - __p += - (obj.bottom) + - ';\nreturn result'; - - return __p - }; - - /*--------------------------------------------------------------------------*/ - - /** - * The base implementation of `_.bind` that creates the bound function and - * sets its meta data. - * - * @private - * @param {Array} bindData The bind data array. - * @returns {Function} Returns the new bound function. - */ - function baseBind(bindData) { - var func = bindData[0], - partialArgs = bindData[2], - thisArg = bindData[4]; - - function bound() { - // `Function#bind` spec - // http://es5.github.io/#x15.3.4.5 - if (partialArgs) { - // avoid `arguments` object deoptimizations by using `slice` instead - // of `Array.prototype.slice.call` and not assigning `arguments` to a - // variable as a ternary expression - var args = slice(partialArgs); - push.apply(args, arguments); - } - // mimic the constructor's `return` behavior - // http://es5.github.io/#x13.2.2 - if (this instanceof bound) { - // ensure `new bound` is an instance of `func` - var thisBinding = baseCreate(func.prototype), - result = func.apply(thisBinding, args || arguments); - return isObject(result) ? result : thisBinding; - } - return func.apply(thisArg, args || arguments); - } - setBindData(bound, bindData); - return bound; - } - - /** - * The base implementation of `_.clone` without argument juggling or support - * for `thisArg` binding. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep=false] Specify a deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates clones with source counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, callback, stackA, stackB) { - if (callback) { - var result = callback(value); - if (typeof result != 'undefined') { - return result; - } - } - // inspect [[Class]] - var isObj = isObject(value); - if (isObj) { - var className = toString.call(value); - if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) { - return value; - } - var ctor = ctorByClass[className]; - switch (className) { - case boolClass: - case dateClass: - return new ctor(+value); - - case numberClass: - case stringClass: - return new ctor(value); - - case regexpClass: - result = ctor(value.source, reFlags.exec(value)); - result.lastIndex = value.lastIndex; - return result; - } - } else { - return value; - } - var isArr = isArray(value); - if (isDeep) { - // check for circular references and return corresponding clone - var initedStack = !stackA; - stackA || (stackA = getArray()); - stackB || (stackB = getArray()); - - var length = stackA.length; - while (length--) { - if (stackA[length] == value) { - return stackB[length]; - } - } - result = isArr ? ctor(value.length) : {}; - } - else { - result = isArr ? slice(value) : assign({}, value); - } - // add array properties assigned by `RegExp#exec` - if (isArr) { - if (hasOwnProperty.call(value, 'index')) { - result.index = value.index; - } - if (hasOwnProperty.call(value, 'input')) { - result.input = value.input; - } - } - // exit for shallow clone - if (!isDeep) { - return result; - } - // add the source value to the stack of traversed objects - // and associate it with its clone - stackA.push(value); - stackB.push(result); - - // recursively populate clone (susceptible to call stack limits) - (isArr ? baseEach : forOwn)(value, function(objValue, key) { - result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); - }); - - if (initedStack) { - releaseArray(stackA); - releaseArray(stackB); - } - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(prototype, properties) { - return isObject(prototype) ? nativeCreate(prototype) : {}; - } - // fallback for browsers without `Object.create` - if (!nativeCreate) { - baseCreate = (function() { - function Object() {} - return function(prototype) { - if (isObject(prototype)) { - Object.prototype = prototype; - var result = new Object; - Object.prototype = null; - } - return result || context.Object(); - }; - }()); - } - - /** - * The base implementation of `_.createCallback` without support for creating - * "_.pluck" or "_.where" style callbacks. - * - * @private - * @param {*} [func=identity] The value to convert to a callback. - * @param {*} [thisArg] The `this` binding of the created callback. - * @param {number} [argCount] The number of arguments the callback accepts. - * @returns {Function} Returns a callback function. - */ - function baseCreateCallback(func, thisArg, argCount) { - if (typeof func != 'function') { - return identity; - } - // exit early for no `thisArg` or already bound by `Function#bind` - if (typeof thisArg == 'undefined' || !('prototype' in func)) { - return func; - } - var bindData = func.__bindData__; - if (typeof bindData == 'undefined') { - if (support.funcNames) { - bindData = !func.name; - } - bindData = bindData || !support.funcDecomp; - if (!bindData) { - var source = fnToString.call(func); - if (!support.funcNames) { - bindData = !reFuncName.test(source); - } - if (!bindData) { - // checks if `func` references the `this` keyword and stores the result - bindData = reThis.test(source); - setBindData(func, bindData); - } - } - } - // exit early if there are no `this` references or `func` is bound - if (bindData === false || (bindData !== true && bindData[1] & 1)) { - return func; - } - switch (argCount) { - case 1: return function(value) { - return func.call(thisArg, value); - }; - case 2: return function(a, b) { - return func.call(thisArg, a, b); - }; - case 3: return function(value, index, collection) { - return func.call(thisArg, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(thisArg, accumulator, value, index, collection); - }; - } - return bind(func, thisArg); - } - - /** - * The base implementation of `createWrapper` that creates the wrapper and - * sets its meta data. - * - * @private - * @param {Array} bindData The bind data array. - * @returns {Function} Returns the new function. - */ - function baseCreateWrapper(bindData) { - var func = bindData[0], - bitmask = bindData[1], - partialArgs = bindData[2], - partialRightArgs = bindData[3], - thisArg = bindData[4], - arity = bindData[5]; - - var isBind = bitmask & 1, - isBindKey = bitmask & 2, - isCurry = bitmask & 4, - isCurryBound = bitmask & 8, - key = func; - - function bound() { - var thisBinding = isBind ? thisArg : this; - if (partialArgs) { - var args = slice(partialArgs); - push.apply(args, arguments); - } - if (partialRightArgs || isCurry) { - args || (args = slice(arguments)); - if (partialRightArgs) { - push.apply(args, partialRightArgs); - } - if (isCurry && args.length < arity) { - bitmask |= 16 & ~32; - return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); - } - } - args || (args = arguments); - if (isBindKey) { - func = thisBinding[key]; - } - if (this instanceof bound) { - thisBinding = baseCreate(func.prototype); - var result = func.apply(thisBinding, args); - return isObject(result) ? result : thisBinding; - } - return func.apply(thisBinding, args); - } - setBindData(bound, bindData); - return bound; - } - - /** - * The base implementation of `_.difference` that accepts a single array - * of values to exclude. - * - * @private - * @param {Array} array The array to process. - * @param {Array} [values] The array of values to exclude. - * @returns {Array} Returns a new array of filtered values. - */ - function baseDifference(array, values) { - var index = -1, - indexOf = getIndexOf(), - length = array ? array.length : 0, - isLarge = length >= largeArraySize && indexOf === baseIndexOf, - result = []; - - if (isLarge) { - var cache = createCache(values); - if (cache) { - indexOf = cacheIndexOf; - values = cache; - } else { - isLarge = false; - } - } - while (++index < length) { - var value = array[index]; - if (indexOf(values, value) < 0) { - result.push(value); - } - } - if (isLarge) { - releaseObject(values); - } - return result; - } - - /** - * The base implementation of `_.flatten` without support for callback - * shorthands or `thisArg` binding. - * - * @private - * @param {Array} array The array to flatten. - * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. - * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. - * @param {number} [fromIndex=0] The index to start from. - * @returns {Array} Returns a new flattened array. - */ - function baseFlatten(array, isShallow, isStrict, fromIndex) { - var index = (fromIndex || 0) - 1, - length = array ? array.length : 0, - result = []; - - while (++index < length) { - var value = array[index]; - - if (value && typeof value == 'object' && typeof value.length == 'number' - && (isArray(value) || isArguments(value))) { - // recursively flatten arrays (susceptible to call stack limits) - if (!isShallow) { - value = baseFlatten(value, isShallow, isStrict); - } - var valIndex = -1, - valLength = value.length, - resIndex = result.length; - - result.length += valLength; - while (++valIndex < valLength) { - result[resIndex++] = value[valIndex]; - } - } else if (!isStrict) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.isEqual`, without support for `thisArg` binding, - * that allows partial "_.where" style comparisons. - * - * @private - * @param {*} a The value to compare. - * @param {*} b The other value to compare. - * @param {Function} [callback] The function to customize comparing values. - * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. - * @param {Array} [stackA=[]] Tracks traversed `a` objects. - * @param {Array} [stackB=[]] Tracks traversed `b` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { - // used to indicate that when comparing objects, `a` has at least the properties of `b` - if (callback) { - var result = callback(a, b); - if (typeof result != 'undefined') { - return !!result; - } - } - // exit early for identical values - if (a === b) { - // treat `+0` vs. `-0` as not equal - return a !== 0 || (1 / a == 1 / b); - } - var type = typeof a, - otherType = typeof b; - - // exit early for unlike primitive values - if (a === a && - !(a && objectTypes[type]) && - !(b && objectTypes[otherType])) { - return false; - } - // exit early for `null` and `undefined` avoiding ES3's Function#call behavior - // http://es5.github.io/#x15.3.4.4 - if (a == null || b == null) { - return a === b; - } - // compare [[Class]] names - var className = toString.call(a), - otherClass = toString.call(b); - - if (className == argsClass) { - className = objectClass; - } - if (otherClass == argsClass) { - otherClass = objectClass; - } - if (className != otherClass) { - return false; - } - switch (className) { - case boolClass: - case dateClass: - // coerce dates and booleans to numbers, dates to milliseconds and booleans - // to `1` or `0` treating invalid dates coerced to `NaN` as not equal - return +a == +b; - - case numberClass: - // treat `NaN` vs. `NaN` as equal - return (a != +a) - ? b != +b - // but treat `+0` vs. `-0` as not equal - : (a == 0 ? (1 / a == 1 / b) : a == +b); - - case regexpClass: - case stringClass: - // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) - // treat string primitives and their corresponding object instances as equal - return a == String(b); - } - var isArr = className == arrayClass; - if (!isArr) { - // unwrap any `lodash` wrapped values - var aWrapped = hasOwnProperty.call(a, '__wrapped__'), - bWrapped = hasOwnProperty.call(b, '__wrapped__'); - - if (aWrapped || bWrapped) { - return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); - } - // exit for functions and DOM nodes - if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { - return false; - } - // in older versions of Opera, `arguments` objects have `Array` constructors - var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, - ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; - - // non `Object` object instances with different constructors are not equal - if (ctorA != ctorB && - !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && - ('constructor' in a && 'constructor' in b) - ) { - return false; - } - } - // assume cyclic structures are equal - // the algorithm for detecting cyclic structures is adapted from ES 5.1 - // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) - var initedStack = !stackA; - stackA || (stackA = getArray()); - stackB || (stackB = getArray()); - - var length = stackA.length; - while (length--) { - if (stackA[length] == a) { - return stackB[length] == b; - } - } - var size = 0; - result = true; - - // add `a` and `b` to the stack of traversed objects - stackA.push(a); - stackB.push(b); - - // recursively compare objects and arrays (susceptible to call stack limits) - if (isArr) { - // compare lengths to determine if a deep comparison is necessary - length = a.length; - size = b.length; - result = size == length; - - if (result || isWhere) { - // deep compare the contents, ignoring non-numeric properties - while (size--) { - var index = length, - value = b[size]; - - if (isWhere) { - while (index--) { - if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { - break; - } - } - } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { - break; - } - } - } - } - else { - // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` - // which, in this case, is more costly - forIn(b, function(value, key, b) { - if (hasOwnProperty.call(b, key)) { - // count the number of properties. - size++; - // deep compare each property value. - return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); - } - }); - - if (result && !isWhere) { - // ensure both objects have the same number of properties - forIn(a, function(value, key, a) { - if (hasOwnProperty.call(a, key)) { - // `size` will be `-1` if `a` has more properties than `b` - return (result = --size > -1); - } - }); - } - } - stackA.pop(); - stackB.pop(); - - if (initedStack) { - releaseArray(stackA); - releaseArray(stackB); - } - return result; - } - - /** - * The base implementation of `_.merge` without argument juggling or support - * for `thisArg` binding. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {Function} [callback] The function to customize merging properties. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates values with source counterparts. - */ - function baseMerge(object, source, callback, stackA, stackB) { - (isArray(source) ? forEach : forOwn)(source, function(source, key) { - var found, - isArr, - result = source, - value = object[key]; - - if (source && ((isArr = isArray(source)) || isPlainObject(source))) { - // avoid merging previously merged cyclic sources - var stackLength = stackA.length; - while (stackLength--) { - if ((found = stackA[stackLength] == source)) { - value = stackB[stackLength]; - break; - } - } - if (!found) { - var isShallow; - if (callback) { - result = callback(value, source); - if ((isShallow = typeof result != 'undefined')) { - value = result; - } - } - if (!isShallow) { - value = isArr - ? (isArray(value) ? value : []) - : (isPlainObject(value) ? value : {}); - } - // add `source` and associated `value` to the stack of traversed objects - stackA.push(source); - stackB.push(value); - - // recursively merge objects and arrays (susceptible to call stack limits) - if (!isShallow) { - baseMerge(value, source, callback, stackA, stackB); - } - } - } - else { - if (callback) { - result = callback(value, source); - if (typeof result == 'undefined') { - result = source; - } - } - if (typeof result != 'undefined') { - value = result; - } - } - object[key] = value; - }); - } - - /** - * The base implementation of `_.random` without argument juggling or support - * for returning floating-point numbers. - * - * @private - * @param {number} min The minimum possible value. - * @param {number} max The maximum possible value. - * @returns {number} Returns a random number. - */ - function baseRandom(min, max) { - return min + floor(nativeRandom() * (max - min + 1)); - } - - /** - * The base implementation of `_.uniq` without support for callback shorthands - * or `thisArg` binding. - * - * @private - * @param {Array} array The array to process. - * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. - * @param {Function} [callback] The function called per iteration. - * @returns {Array} Returns a duplicate-value-free array. - */ - function baseUniq(array, isSorted, callback) { - var index = -1, - indexOf = getIndexOf(), - length = array ? array.length : 0, - result = []; - - var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, - seen = (callback || isLarge) ? getArray() : result; - - if (isLarge) { - var cache = createCache(seen); - indexOf = cacheIndexOf; - seen = cache; - } - while (++index < length) { - var value = array[index], - computed = callback ? callback(value, index, array) : value; - - if (isSorted - ? !index || seen[seen.length - 1] !== computed - : indexOf(seen, computed) < 0 - ) { - if (callback || isLarge) { - seen.push(computed); - } - result.push(value); - } - } - if (isLarge) { - releaseArray(seen.array); - releaseObject(seen); - } else if (callback) { - releaseArray(seen); - } - return result; - } - - /** - * Creates a function that aggregates a collection, creating an object composed - * of keys generated from the results of running each element of the collection - * through a callback. The given `setter` function sets the keys and values - * of the composed object. - * - * @private - * @param {Function} setter The setter function. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter) { - return function(collection, callback, thisArg) { - var result = {}; - callback = lodash.createCallback(callback, thisArg, 3); - - if (isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - setter(result, value, callback(value, index, collection), collection); - } - } else { - baseEach(collection, function(value, key, collection) { - setter(result, value, callback(value, key, collection), collection); - }); - } - return result; - }; - } - - /** - * Creates a function that, when called, either curries or invokes `func` - * with an optional `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to reference. - * @param {number} bitmask The bitmask of method flags to compose. - * The bitmask may be composed of the following flags: - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` - * 8 - `_.curry` (bound) - * 16 - `_.partial` - * 32 - `_.partialRight` - * @param {Array} [partialArgs] An array of arguments to prepend to those - * provided to the new function. - * @param {Array} [partialRightArgs] An array of arguments to append to those - * provided to the new function. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new function. - */ - function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { - var isBind = bitmask & 1, - isBindKey = bitmask & 2, - isCurry = bitmask & 4, - isCurryBound = bitmask & 8, - isPartial = bitmask & 16, - isPartialRight = bitmask & 32; - - if (!isBindKey && !isFunction(func)) { - throw new TypeError; - } - if (isPartial && !partialArgs.length) { - bitmask &= ~16; - isPartial = partialArgs = false; - } - if (isPartialRight && !partialRightArgs.length) { - bitmask &= ~32; - isPartialRight = partialRightArgs = false; - } - var bindData = func && func.__bindData__; - if (bindData && bindData !== true) { - // clone `bindData` - bindData = slice(bindData); - if (bindData[2]) { - bindData[2] = slice(bindData[2]); - } - if (bindData[3]) { - bindData[3] = slice(bindData[3]); - } - // set `thisBinding` is not previously bound - if (isBind && !(bindData[1] & 1)) { - bindData[4] = thisArg; - } - // set if previously bound but not currently (subsequent curried functions) - if (!isBind && bindData[1] & 1) { - bitmask |= 8; - } - // set curried arity if not yet set - if (isCurry && !(bindData[1] & 4)) { - bindData[5] = arity; - } - // append partial left arguments - if (isPartial) { - push.apply(bindData[2] || (bindData[2] = []), partialArgs); - } - // append partial right arguments - if (isPartialRight) { - unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); - } - // merge flags - bindData[1] |= bitmask; - return createWrapper.apply(null, bindData); - } - // fast path for `_.bind` - var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; - return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); - } - - /** - * Creates compiled iteration functions. - * - * @private - * @param {...Object} [options] The compile options object(s). - * @param {string} [options.array] Code to determine if the iterable is an array or array-like. - * @param {boolean} [options.useHas] Specify using `hasOwnProperty` checks in the object loop. - * @param {Function} [options.keys] A reference to `_.keys` for use in own property iteration. - * @param {string} [options.args] A comma separated string of iteration function arguments. - * @param {string} [options.top] Code to execute before the iteration branches. - * @param {string} [options.loop] Code to execute in the object loop. - * @param {string} [options.bottom] Code to execute after the iteration branches. - * @returns {Function} Returns the compiled function. - */ - function createIterator() { - // data properties - iteratorData.shadowedProps = shadowedProps; - - // iterator options - iteratorData.array = iteratorData.bottom = iteratorData.loop = iteratorData.top = ''; - iteratorData.init = 'iterable'; - iteratorData.useHas = true; - - // merge options into a template data object - for (var object, index = 0; object = arguments[index]; index++) { - for (var key in object) { - iteratorData[key] = object[key]; - } - } - var args = iteratorData.args; - iteratorData.firstArg = /^[^,]+/.exec(args)[0]; - - // create the function factory - var factory = Function( - 'baseCreateCallback, errorClass, errorProto, hasOwnProperty, ' + - 'indicatorObject, isArguments, isArray, isString, keys, objectProto, ' + - 'objectTypes, nonEnumProps, stringClass, stringProto, toString', - 'return function(' + args + ') {\n' + iteratorTemplate(iteratorData) + '\n}' - ); - - // return the compiled function - return factory( - baseCreateCallback, errorClass, errorProto, hasOwnProperty, - indicatorObject, isArguments, isArray, isString, iteratorData.keys, objectProto, - objectTypes, nonEnumProps, stringClass, stringProto, toString - ); - } - - /** - * Used by `escape` to convert characters to HTML entities. - * - * @private - * @param {string} match The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeHtmlChar(match) { - return htmlEscapes[match]; - } - - /** - * Gets the appropriate "indexOf" function. If the `_.indexOf` method is - * customized, this method returns the custom method, otherwise it returns - * the `baseIndexOf` function. - * - * @private - * @returns {Function} Returns the "indexOf" function. - */ - function getIndexOf() { - var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; - return result; - } - - /** - * Checks if `value` is a native function. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. - */ - function isNative(value) { - return typeof value == 'function' && reNative.test(value); - } - - /** - * Sets `this` binding data on a given function. - * - * @private - * @param {Function} func The function to set data on. - * @param {Array} value The data array to set. - */ - var setBindData = !defineProperty ? noop : function(func, value) { - descriptor.value = value; - defineProperty(func, '__bindData__', descriptor); - descriptor.value = null; - }; - - /** - * A fallback implementation of `isPlainObject` which checks if a given value - * is an object created by the `Object` constructor, assuming objects created - * by the `Object` constructor have no inherited enumerable properties and that - * there are no `Object.prototype` extensions. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - */ - function shimIsPlainObject(value) { - var ctor, - result; - - // avoid non Object objects, `arguments` objects, and DOM elements - if (!(value && toString.call(value) == objectClass) || - (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) || - (!support.argsClass && isArguments(value)) || - (!support.nodeClass && isNode(value))) { - return false; - } - // IE < 9 iterates inherited properties before own properties. If the first - // iterated property is an object's own property then there are no inherited - // enumerable properties. - if (support.ownLast) { - forIn(value, function(value, key, object) { - result = hasOwnProperty.call(object, key); - return false; - }); - return result !== false; - } - // In most environments an object's own properties are iterated before - // its inherited properties. If the last iterated property is an object's - // own property then there are no inherited enumerable properties. - forIn(value, function(value, key) { - result = key; - }); - return typeof result == 'undefined' || hasOwnProperty.call(value, result); - } - - /** - * Used by `unescape` to convert HTML entities to characters. - * - * @private - * @param {string} match The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - function unescapeHtmlChar(match) { - return htmlUnescapes[match]; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Checks if `value` is an `arguments` object. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. - * @example - * - * (function() { return _.isArguments(arguments); })(1, 2, 3); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - toString.call(value) == argsClass || false; - } - // fallback for browsers that can't detect `arguments` objects by [[Class]] - if (!support.argsClass) { - isArguments = function(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') || false; - }; - } - - /** - * Checks if `value` is an array. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an array, else `false`. - * @example - * - * (function() { return _.isArray(arguments); })(); - * // => false - * - * _.isArray([1, 2, 3]); - * // => true - */ - var isArray = nativeIsArray || function(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - toString.call(value) == arrayClass || false; - }; - - /** - * A fallback implementation of `Object.keys` which produces an array of the - * given object's own enumerable property names. - * - * @private - * @type Function - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names. - */ - var shimKeys = createIterator({ - 'args': 'object', - 'init': '[]', - 'top': 'if (!(objectTypes[typeof object])) return result', - 'loop': 'result.push(index)' - }); - - /** - * Creates an array composed of the own enumerable property names of an object. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names. - * @example - * - * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); - * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) - */ - var keys = !nativeKeys ? shimKeys : function(object) { - if (!isObject(object)) { - return []; - } - if ((support.enumPrototypes && typeof object == 'function') || - (support.nonEnumArgs && object.length && isArguments(object))) { - return shimKeys(object); - } - return nativeKeys(object); - }; - - /** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */ - var eachIteratorOptions = { - 'args': 'collection, callback, thisArg', - 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3)", - 'array': "typeof length == 'number'", - 'keys': keys, - 'loop': 'if (callback(iterable[index], index, collection) === false) return result' - }; - - /** Reusable iterator options for `assign` and `defaults` */ - var defaultsIteratorOptions = { - 'args': 'object, source, guard', - 'top': - 'var args = arguments,\n' + - ' argsIndex = 0,\n' + - " argsLength = typeof guard == 'number' ? 2 : args.length;\n" + - 'while (++argsIndex < argsLength) {\n' + - ' iterable = args[argsIndex];\n' + - ' if (iterable && objectTypes[typeof iterable]) {', - 'keys': keys, - 'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]", - 'bottom': ' }\n}' - }; - - /** Reusable iterator options for `forIn` and `forOwn` */ - var forOwnIteratorOptions = { - 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, - 'array': false - }; - - /** - * Used to convert characters to HTML entities: - * - * Though the `>` character is escaped for symmetry, characters like `>` and `/` - * don't require escaping in HTML and have no special meaning unless they're part - * of a tag or an unquoted attribute value. - * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") - */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Used to convert HTML entities to characters */ - var htmlUnescapes = invert(htmlEscapes); - - /** Used to match HTML entities and HTML characters */ - var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), - reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); - - /** - * A function compiled to iterate `arguments` objects, arrays, objects, and - * strings consistenly across environments, executing the callback for each - * element in the collection. The callback is bound to `thisArg` and invoked - * with three arguments; (value, index|key, collection). Callbacks may exit - * iteration early by explicitly returning `false`. - * - * @private - * @type Function - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array|Object|string} Returns `collection`. - */ - var baseEach = createIterator(eachIteratorOptions); - - /*--------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable properties of source object(s) to the destination - * object. Subsequent sources will overwrite property assignments of previous - * sources. If a callback is provided it will be executed to produce the - * assigned values. The callback is bound to `thisArg` and invoked with two - * arguments; (objectValue, sourceValue). - * - * @static - * @memberOf _ - * @type Function - * @alias extend - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param {Function} [callback] The function to customize assigning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the destination object. - * @example - * - * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); - * // => { 'name': 'fred', 'employer': 'slate' } - * - * var defaults = _.partialRight(_.assign, function(a, b) { - * return typeof a == 'undefined' ? b : a; - * }); - * - * var object = { 'name': 'barney' }; - * defaults(object, { 'name': 'fred', 'employer': 'slate' }); - * // => { 'name': 'barney', 'employer': 'slate' } - */ - var assign = createIterator(defaultsIteratorOptions, { - 'top': - defaultsIteratorOptions.top.replace(';', - ';\n' + - "if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" + - ' var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);\n' + - "} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" + - ' callback = args[--argsLength];\n' + - '}' - ), - 'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]' - }); - - /** - * Creates a clone of `value`. If `isDeep` is `true` nested objects will also - * be cloned, otherwise they will be assigned by reference. If a callback - * is provided it will be executed to produce the cloned values. If the - * callback returns `undefined` cloning will be handled by the method instead. - * The callback is bound to `thisArg` and invoked with one argument; (value). - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to clone. - * @param {boolean} [isDeep=false] Specify a deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the cloned value. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * var shallow = _.clone(characters); - * shallow[0] === characters[0]; - * // => true - * - * var deep = _.clone(characters, true); - * deep[0] === characters[0]; - * // => false - * - * _.mixin({ - * 'clone': _.partialRight(_.clone, function(value) { - * return _.isElement(value) ? value.cloneNode(false) : undefined; - * }) - * }); - * - * var clone = _.clone(document.body); - * clone.childNodes.length; - * // => 0 - */ - function clone(value, isDeep, callback, thisArg) { - // allows working with "Collections" methods without using their `index` - // and `collection` arguments for `isDeep` and `callback` - if (typeof isDeep != 'boolean' && isDeep != null) { - thisArg = callback; - callback = isDeep; - isDeep = false; - } - return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); - } - - /** - * Creates a deep clone of `value`. If a callback is provided it will be - * executed to produce the cloned values. If the callback returns `undefined` - * cloning will be handled by the method instead. The callback is bound to - * `thisArg` and invoked with one argument; (value). - * - * Note: This method is loosely based on the structured clone algorithm. Functions - * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and - * objects created by constructors other than `Object` are cloned to plain `Object` objects. - * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the deep cloned value. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * var deep = _.cloneDeep(characters); - * deep[0] === characters[0]; - * // => false - * - * var view = { - * 'label': 'docs', - * 'node': element - * }; - * - * var clone = _.cloneDeep(view, function(value) { - * return _.isElement(value) ? value.cloneNode(true) : undefined; - * }); - * - * clone.node == view.node; - * // => false - */ - function cloneDeep(value, callback, thisArg) { - return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); - } - - /** - * Creates an object that inherits from the given `prototype` object. If a - * `properties` object is provided its own enumerable properties are assigned - * to the created object. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties ? assign(result, properties) : result; - } - - /** - * Assigns own enumerable properties of source object(s) to the destination - * object for all destination properties that resolve to `undefined`. Once a - * property is set, additional defaults of the same property will be ignored. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param- {Object} [guard] Allows working with `_.reduce` without using its - * `key` and `object` arguments as sources. - * @returns {Object} Returns the destination object. - * @example - * - * var object = { 'name': 'barney' }; - * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); - * // => { 'name': 'barney', 'employer': 'slate' } - */ - var defaults = createIterator(defaultsIteratorOptions); - - /** - * This method is like `_.findIndex` except that it returns the key of the - * first element that passes the callback check, instead of the element itself. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to search. - * @param {Function|Object|string} [callback=identity] The function called per - * iteration. If a property name or object is provided it will be used to - * create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {string|undefined} Returns the key of the found element, else `undefined`. - * @example - * - * var characters = { - * 'barney': { 'age': 36, 'blocked': false }, - * 'fred': { 'age': 40, 'blocked': true }, - * 'pebbles': { 'age': 1, 'blocked': false } - * }; - * - * _.findKey(characters, function(chr) { - * return chr.age < 40; - * }); - * // => 'barney' (property order is not guaranteed across environments) - * - * // using "_.where" callback shorthand - * _.findKey(characters, { 'age': 1 }); - * // => 'pebbles' - * - * // using "_.pluck" callback shorthand - * _.findKey(characters, 'blocked'); - * // => 'fred' - */ - function findKey(object, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - forOwn(object, function(value, key, object) { - if (callback(value, key, object)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.findKey` except that it iterates over elements - * of a `collection` in the opposite order. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to search. - * @param {Function|Object|string} [callback=identity] The function called per - * iteration. If a property name or object is provided it will be used to - * create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {string|undefined} Returns the key of the found element, else `undefined`. - * @example - * - * var characters = { - * 'barney': { 'age': 36, 'blocked': true }, - * 'fred': { 'age': 40, 'blocked': false }, - * 'pebbles': { 'age': 1, 'blocked': true } - * }; - * - * _.findLastKey(characters, function(chr) { - * return chr.age < 40; - * }); - * // => returns `pebbles`, assuming `_.findKey` returns `barney` - * - * // using "_.where" callback shorthand - * _.findLastKey(characters, { 'age': 40 }); - * // => 'fred' - * - * // using "_.pluck" callback shorthand - * _.findLastKey(characters, 'blocked'); - * // => 'pebbles' - */ - function findLastKey(object, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - forOwnRight(object, function(value, key, object) { - if (callback(value, key, object)) { - result = key; - return false; - } - }); - return result; - } - - /** - * Iterates over own and inherited enumerable properties of an object, - * executing the callback for each property. The callback is bound to `thisArg` - * and invoked with three arguments; (value, key, object). Callbacks may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * Shape.prototype.move = function(x, y) { - * this.x += x; - * this.y += y; - * }; - * - * _.forIn(new Shape, function(value, key) { - * console.log(key); - * }); - * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) - */ - var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, { - 'useHas': false - }); - - /** - * This method is like `_.forIn` except that it iterates over elements - * of a `collection` in the opposite order. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * Shape.prototype.move = function(x, y) { - * this.x += x; - * this.y += y; - * }; - * - * _.forInRight(new Shape, function(value, key) { - * console.log(key); - * }); - * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' - */ - function forInRight(object, callback, thisArg) { - var pairs = []; - - forIn(object, function(value, key) { - pairs.push(key, value); - }); - - var length = pairs.length; - callback = baseCreateCallback(callback, thisArg, 3); - while (length--) { - if (callback(pairs[length--], pairs[length], object) === false) { - break; - } - } - return object; - } - - /** - * Iterates over own enumerable properties of an object, executing the callback - * for each property. The callback is bound to `thisArg` and invoked with three - * arguments; (value, key, object). Callbacks may exit iteration early by - * explicitly returning `false`. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { - * console.log(key); - * }); - * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) - */ - var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions); - - /** - * This method is like `_.forOwn` except that it iterates over elements - * of a `collection` in the opposite order. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { - * console.log(key); - * }); - * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' - */ - function forOwnRight(object, callback, thisArg) { - var props = keys(object), - length = props.length; - - callback = baseCreateCallback(callback, thisArg, 3); - while (length--) { - var key = props[length]; - if (callback(object[key], key, object) === false) { - break; - } - } - return object; - } - - /** - * Creates a sorted array of property names of all enumerable properties, - * own and inherited, of `object` that have function values. - * - * @static - * @memberOf _ - * @alias methods - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names that have function values. - * @example - * - * _.functions(_); - * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] - */ - function functions(object) { - var result = []; - forIn(object, function(value, key) { - if (isFunction(value)) { - result.push(key); - } - }); - return result.sort(); - } - - /** - * Checks if the specified property name exists as a direct property of `object`, - * instead of an inherited property. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @param {string} key The name of the property to check. - * @returns {boolean} Returns `true` if key is a direct property, else `false`. - * @example - * - * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); - * // => true - */ - function has(object, key) { - return object ? hasOwnProperty.call(object, key) : false; - } - - /** - * Creates an object composed of the inverted keys and values of the given object. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to invert. - * @returns {Object} Returns the created inverted object. - * @example - * - * _.invert({ 'first': 'fred', 'second': 'barney' }); - * // => { 'fred': 'first', 'barney': 'second' } - */ - function invert(object) { - var index = -1, - props = keys(object), - length = props.length, - result = {}; - - while (++index < length) { - var key = props[index]; - result[object[key]] = key; - } - return result; - } - - /** - * Checks if `value` is a boolean value. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. - * @example - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - value && typeof value == 'object' && toString.call(value) == boolClass || false; - } - - /** - * Checks if `value` is a date. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a date, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - */ - function isDate(value) { - return value && typeof value == 'object' && toString.call(value) == dateClass || false; - } - - /** - * Checks if `value` is a DOM element. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - */ - function isElement(value) { - return value && value.nodeType === 1 || false; - } - - /** - * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a - * length of `0` and objects with no own enumerable properties are considered - * "empty". - * - * @static - * @memberOf _ - * @category Objects - * @param {Array|Object|string} value The value to inspect. - * @returns {boolean} Returns `true` if the `value` is empty, else `false`. - * @example - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({}); - * // => true - * - * _.isEmpty(''); - * // => true - */ - function isEmpty(value) { - var result = true; - if (!value) { - return result; - } - var className = toString.call(value), - length = value.length; - - if ((className == arrayClass || className == stringClass || - (support.argsClass ? className == argsClass : isArguments(value))) || - (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { - return !length; - } - forOwn(value, function() { - return (result = false); - }); - return result; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent to each other. If a callback is provided it will be executed - * to compare values. If the callback returns `undefined` comparisons will - * be handled by the method instead. The callback is bound to `thisArg` and - * invoked with two arguments; (a, b). - * - * @static - * @memberOf _ - * @category Objects - * @param {*} a The value to compare. - * @param {*} b The other value to compare. - * @param {Function} [callback] The function to customize comparing values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'name': 'fred' }; - * var copy = { 'name': 'fred' }; - * - * object == copy; - * // => false - * - * _.isEqual(object, copy); - * // => true - * - * var words = ['hello', 'goodbye']; - * var otherWords = ['hi', 'goodbye']; - * - * _.isEqual(words, otherWords, function(a, b) { - * var reGreet = /^(?:hello|hi)$/i, - * aGreet = _.isString(a) && reGreet.test(a), - * bGreet = _.isString(b) && reGreet.test(b); - * - * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; - * }); - * // => true - */ - function isEqual(a, b, callback, thisArg) { - return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); - } - - /** - * Checks if `value` is, or can be coerced to, a finite number. - * - * Note: This is not the same as native `isFinite` which will return true for - * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is finite, else `false`. - * @example - * - * _.isFinite(-101); - * // => true - * - * _.isFinite('10'); - * // => true - * - * _.isFinite(true); - * // => false - * - * _.isFinite(''); - * // => false - * - * _.isFinite(Infinity); - * // => false - */ - function isFinite(value) { - return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); - } - - /** - * Checks if `value` is a function. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - */ - function isFunction(value) { - return typeof value == 'function'; - } - // fallback for older versions of Chrome and Safari - if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value == 'function' && toString.call(value) == funcClass; - }; - } - - /** - * Checks if `value` is the language type of Object. - * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(1); - * // => false - */ - function isObject(value) { - // check if the value is the ECMAScript language type of Object - // http://es5.github.io/#x8 - // and avoid a V8 bug - // http://code.google.com/p/v8/issues/detail?id=2291 - return !!(value && objectTypes[typeof value]); - } - - /** - * Checks if `value` is `NaN`. - * - * Note: This is not the same as native `isNaN` which will return `true` for - * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // `NaN` as a primitive is the only value that is not equal to itself - // (perform the [[Class]] check first to avoid errors with some host objects in IE) - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(undefined); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is a number. - * - * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a number, else `false`. - * @example - * - * _.isNumber(8.4 * 5); - * // => true - */ - function isNumber(value) { - return typeof value == 'number' || - value && typeof value == 'object' && toString.call(value) == numberClass || false; - } - - /** - * Checks if `value` is an object created by the `Object` constructor. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * _.isPlainObject(new Shape); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - */ - var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { - if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { - return false; - } - var valueOf = value.valueOf, - objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); - - return objProto - ? (value == objProto || getPrototypeOf(value) == objProto) - : shimIsPlainObject(value); - }; - - /** - * Checks if `value` is a regular expression. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. - * @example - * - * _.isRegExp(/fred/); - * // => true - */ - function isRegExp(value) { - return value && objectTypes[typeof value] && toString.call(value) == regexpClass || false; - } - - /** - * Checks if `value` is a string. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a string, else `false`. - * @example - * - * _.isString('fred'); - * // => true - */ - function isString(value) { - return typeof value == 'string' || - value && typeof value == 'object' && toString.call(value) == stringClass || false; - } - - /** - * Checks if `value` is `undefined`. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - */ - function isUndefined(value) { - return typeof value == 'undefined'; - } - - /** - * Creates an object with the same keys as `object` and values generated by - * running each own enumerable property of `object` through the callback. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, key, object). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new object with values of the results of each `callback` execution. - * @example - * - * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); - * // => { 'a': 3, 'b': 6, 'c': 9 } - * - * var characters = { - * 'fred': { 'name': 'fred', 'age': 40 }, - * 'pebbles': { 'name': 'pebbles', 'age': 1 } - * }; - * - * // using "_.pluck" callback shorthand - * _.mapValues(characters, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } - */ - function mapValues(object, callback, thisArg) { - var result = {}; - callback = lodash.createCallback(callback, thisArg, 3); - - forOwn(object, function(value, key, object) { - result[key] = callback(value, key, object); - }); - return result; - } - - /** - * Recursively merges own enumerable properties of the source object(s), that - * don't resolve to `undefined` into the destination object. Subsequent sources - * will overwrite property assignments of previous sources. If a callback is - * provided it will be executed to produce the merged values of the destination - * and source properties. If the callback returns `undefined` merging will - * be handled by the method instead. The callback is bound to `thisArg` and - * invoked with two arguments; (objectValue, sourceValue). - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param {Function} [callback] The function to customize merging properties. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the destination object. - * @example - * - * var names = { - * 'characters': [ - * { 'name': 'barney' }, - * { 'name': 'fred' } - * ] - * }; - * - * var ages = { - * 'characters': [ - * { 'age': 36 }, - * { 'age': 40 } - * ] - * }; - * - * _.merge(names, ages); - * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } - * - * var food = { - * 'fruits': ['apple'], - * 'vegetables': ['beet'] - * }; - * - * var otherFood = { - * 'fruits': ['banana'], - * 'vegetables': ['carrot'] - * }; - * - * _.merge(food, otherFood, function(a, b) { - * return _.isArray(a) ? a.concat(b) : undefined; - * }); - * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } - */ - function merge(object) { - var args = arguments, - length = 2; - - if (!isObject(object)) { - return object; - } - // allows working with `_.reduce` and `_.reduceRight` without using - // their `index` and `collection` arguments - if (typeof args[2] != 'number') { - length = args.length; - } - if (length > 3 && typeof args[length - 2] == 'function') { - var callback = baseCreateCallback(args[--length - 1], args[length--], 2); - } else if (length > 2 && typeof args[length - 1] == 'function') { - callback = args[--length]; - } - var sources = slice(arguments, 1, length), - index = -1, - stackA = getArray(), - stackB = getArray(); - - while (++index < length) { - baseMerge(object, sources[index], callback, stackA, stackB); - } - releaseArray(stackA); - releaseArray(stackB); - return object; - } - - /** - * Creates a shallow clone of `object` excluding the specified properties. - * Property names may be specified as individual arguments or as arrays of - * property names. If a callback is provided it will be executed for each - * property of `object` omitting the properties the callback returns truey - * for. The callback is bound to `thisArg` and invoked with three arguments; - * (value, key, object). - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The source object. - * @param {Function|...string|string[]} [callback] The properties to omit or the - * function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns an object without the omitted properties. - * @example - * - * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); - * // => { 'name': 'fred' } - * - * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { - * return typeof value == 'number'; - * }); - * // => { 'name': 'fred' } - */ - function omit(object, callback, thisArg) { - var result = {}; - if (typeof callback != 'function') { - var props = []; - forIn(object, function(value, key) { - props.push(key); - }); - props = baseDifference(props, baseFlatten(arguments, true, false, 1)); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - result[key] = object[key]; - } - } else { - callback = lodash.createCallback(callback, thisArg, 3); - forIn(object, function(value, key, object) { - if (!callback(value, key, object)) { - result[key] = value; - } - }); - } - return result; - } - - /** - * Creates a two dimensional array of an object's key-value pairs, - * i.e. `[[key1, value1], [key2, value2]]`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns new array of key-value pairs. - * @example - * - * _.pairs({ 'barney': 36, 'fred': 40 }); - * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) - */ - function pairs(object) { - var index = -1, - props = keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - var key = props[index]; - result[index] = [key, object[key]]; - } - return result; - } - - /** - * Creates a shallow clone of `object` composed of the specified properties. - * Property names may be specified as individual arguments or as arrays of - * property names. If a callback is provided it will be executed for each - * property of `object` picking the properties the callback returns truey - * for. The callback is bound to `thisArg` and invoked with three arguments; - * (value, key, object). - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The source object. - * @param {Function|...string|string[]} [callback] The function called per - * iteration or property names to pick, specified as individual property - * names or arrays of property names. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns an object composed of the picked properties. - * @example - * - * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); - * // => { 'name': 'fred' } - * - * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { - * return key.charAt(0) != '_'; - * }); - * // => { 'name': 'fred' } - */ - function pick(object, callback, thisArg) { - var result = {}; - if (typeof callback != 'function') { - var index = -1, - props = baseFlatten(arguments, true, false, 1), - length = isObject(object) ? props.length : 0; - - while (++index < length) { - var key = props[index]; - if (key in object) { - result[key] = object[key]; - } - } - } else { - callback = lodash.createCallback(callback, thisArg, 3); - forIn(object, function(value, key, object) { - if (callback(value, key, object)) { - result[key] = value; - } - }); - } - return result; - } - - /** - * An alternative to `_.reduce` this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable properties through a callback, with each callback execution - * potentially mutating the `accumulator` object. The callback is bound to - * `thisArg` and invoked with four arguments; (accumulator, value, key, object). - * Callbacks may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Array|Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the accumulated value. - * @example - * - * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { - * num *= num; - * if (num % 2) { - * return result.push(num) < 3; - * } - * }); - * // => [1, 9, 25] - * - * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { - * result[key] = num * 3; - * }); - * // => { 'a': 3, 'b': 6, 'c': 9 } - */ - function transform(object, callback, accumulator, thisArg) { - var isArr = isArray(object); - if (accumulator == null) { - if (isArr) { - accumulator = []; - } else { - var ctor = object && object.constructor, - proto = ctor && ctor.prototype; - - accumulator = baseCreate(proto); - } - } - if (callback) { - callback = lodash.createCallback(callback, thisArg, 4); - (isArr ? baseEach : forOwn)(object, function(value, index, object) { - return callback(accumulator, value, index, object); - }); - } - return accumulator; - } - - /** - * Creates an array composed of the own enumerable property values of `object`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property values. - * @example - * - * _.values({ 'one': 1, 'two': 2, 'three': 3 }); - * // => [1, 2, 3] (property order is not guaranteed across environments) - */ - function values(object) { - var index = -1, - props = keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - result[index] = object[props[index]]; - } - return result; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Creates an array of elements from the specified indexes, or keys, of the - * `collection`. Indexes may be specified as individual arguments or as arrays - * of indexes. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` - * to retrieve, specified as individual indexes or arrays of indexes. - * @returns {Array} Returns a new array of elements corresponding to the - * provided indexes. - * @example - * - * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); - * // => ['a', 'c', 'e'] - * - * _.at(['fred', 'barney', 'pebbles'], 0, 2); - * // => ['fred', 'pebbles'] - */ - function at(collection) { - var args = arguments, - index = -1, - props = baseFlatten(args, true, false, 1), - length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, - result = Array(length); - - if (support.unindexedChars && isString(collection)) { - collection = collection.split(''); - } - while(++index < length) { - result[index] = collection[props[index]]; - } - return result; - } - - /** - * Checks if a given value is present in a collection using strict equality - * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the - * offset from the end of the collection. - * - * @static - * @memberOf _ - * @alias include - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {*} target The value to check for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {boolean} Returns `true` if the `target` element is found, else `false`. - * @example - * - * _.contains([1, 2, 3], 1); - * // => true - * - * _.contains([1, 2, 3], 1, 2); - * // => false - * - * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); - * // => true - * - * _.contains('pebbles', 'eb'); - * // => true - */ - function contains(collection, target, fromIndex) { - var index = -1, - indexOf = getIndexOf(), - length = collection ? collection.length : 0, - result = false; - - fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; - if (isArray(collection)) { - result = indexOf(collection, target, fromIndex) > -1; - } else if (typeof length == 'number') { - result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; - } else { - baseEach(collection, function(value) { - if (++index >= fromIndex) { - return !(result = value === target); - } - }); - } - return result; - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` through the callback. The corresponding value - * of each key is the number of times the key was returned by the callback. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); - * // => { '4': 1, '6': 2 } - * - * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); - * // => { '4': 1, '6': 2 } - * - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); - }); - - /** - * Checks if the given callback returns truey value for **all** elements of - * a collection. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias all - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {boolean} Returns `true` if all elements passed the callback check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes']); - * // => false - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * // using "_.pluck" callback shorthand - * _.every(characters, 'age'); - * // => true - * - * // using "_.where" callback shorthand - * _.every(characters, { 'age': 36 }); - * // => false - */ - function every(collection, callback, thisArg) { - var result = true; - callback = lodash.createCallback(callback, thisArg, 3); - - if (isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - if (!(result = !!callback(collection[index], index, collection))) { - break; - } - } - } else { - baseEach(collection, function(value, index, collection) { - return (result = !!callback(value, index, collection)); - }); - } - return result; - } - - /** - * Iterates over elements of a collection, returning an array of all elements - * the callback returns truey for. The callback is bound to `thisArg` and - * invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias select - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of elements that passed the callback check. - * @example - * - * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); - * // => [2, 4, 6] - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true } - * ]; - * - * // using "_.pluck" callback shorthand - * _.filter(characters, 'blocked'); - * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] - * - * // using "_.where" callback shorthand - * _.filter(characters, { 'age': 36 }); - * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] - */ - function filter(collection, callback, thisArg) { - var result = []; - callback = lodash.createCallback(callback, thisArg, 3); - - if (isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - if (callback(value, index, collection)) { - result.push(value); - } - } - } else { - baseEach(collection, function(value, index, collection) { - if (callback(value, index, collection)) { - result.push(value); - } - }); - } - return result; - } - - /** - * Iterates over elements of a collection, returning the first element that - * the callback returns truey for. The callback is bound to `thisArg` and - * invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias detect, findWhere - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the found element, else `undefined`. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true }, - * { 'name': 'pebbles', 'age': 1, 'blocked': false } - * ]; - * - * _.find(characters, function(chr) { - * return chr.age < 40; - * }); - * // => { 'name': 'barney', 'age': 36, 'blocked': false } - * - * // using "_.where" callback shorthand - * _.find(characters, { 'age': 1 }); - * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } - * - * // using "_.pluck" callback shorthand - * _.find(characters, 'blocked'); - * // => { 'name': 'fred', 'age': 40, 'blocked': true } - */ - function find(collection, callback, thisArg) { - callback = lodash.createCallback(callback, thisArg, 3); - - if (isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - if (callback(value, index, collection)) { - return value; - } - } - } else { - var result; - baseEach(collection, function(value, index, collection) { - if (callback(value, index, collection)) { - result = value; - return false; - } - }); - return result; - } - } - - /** - * This method is like `_.find` except that it iterates over elements - * of a `collection` from right to left. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the found element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(num) { - * return num % 2 == 1; - * }); - * // => 3 - */ - function findLast(collection, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - forEachRight(collection, function(value, index, collection) { - if (callback(value, index, collection)) { - result = value; - return false; - } - }); - return result; - } - - /** - * Iterates over elements of a collection, executing the callback for each - * element. The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). Callbacks may exit iteration early by - * explicitly returning `false`. - * - * Note: As with other "Collections" methods, objects with a `length` property - * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` - * may be used for object iteration. - * - * @static - * @memberOf _ - * @alias each - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); - * // => logs each number and returns '1,2,3' - * - * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); - * // => logs each number and returns the object (property order is not guaranteed across environments) - */ - function forEach(collection, callback, thisArg) { - if (callback && typeof thisArg == 'undefined' && isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - if (callback(collection[index], index, collection) === false) { - break; - } - } - } else { - baseEach(collection, callback, thisArg); - } - return collection; - } - - /** - * This method is like `_.forEach` except that it iterates over elements - * of a `collection` from right to left. - * - * @static - * @memberOf _ - * @alias eachRight - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); - * // => logs each number from right to left and returns '3,2,1' - */ - function forEachRight(collection, callback, thisArg) { - var iterable = collection, - length = collection ? collection.length : 0; - - callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); - if (isArray(collection)) { - while (length--) { - if (callback(collection[length], length, collection) === false) { - break; - } - } - } else { - if (typeof length != 'number') { - var props = keys(collection); - length = props.length; - } else if (support.unindexedChars && isString(collection)) { - iterable = collection.split(''); - } - baseEach(collection, function(value, key, collection) { - key = props ? props[--length] : --length; - return callback(iterable[key], key, collection); - }); - } - return collection; - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of a collection through the callback. The corresponding value - * of each key is an array of the elements responsible for generating the key. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false` - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); - * // => { '4': [4.2], '6': [6.1, 6.4] } - * - * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); - * // => { '4': [4.2], '6': [6.1, 6.4] } - * - * // using "_.pluck" callback shorthand - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of the collection through the given callback. The corresponding - * value of each key is the last element responsible for generating the key. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var keys = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.indexBy(keys, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - * - * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - */ - var indexBy = createAggregator(function(result, value, key) { - result[key] = value; - }); - - /** - * Invokes the method named by `methodName` on each element in the `collection` - * returning an array of the results of each invoked method. Additional arguments - * will be provided to each invoked method. If `methodName` is a function it - * will be invoked for, and `this` bound to, each element in the `collection`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|string} methodName The name of the method to invoke or - * the function invoked per iteration. - * @param {...*} [arg] Arguments to invoke the method with. - * @returns {Array} Returns a new array of the results of each invoked method. - * @example - * - * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invoke([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - function invoke(collection, methodName) { - var args = slice(arguments, 2), - index = -1, - isFunc = typeof methodName == 'function', - length = collection ? collection.length : 0, - result = Array(typeof length == 'number' ? length : 0); - - forEach(collection, function(value) { - result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); - }); - return result; - } - - /** - * Creates an array of values by running each element in the collection - * through the callback. The callback is bound to `thisArg` and invoked with - * three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias collect - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of the results of each `callback` execution. - * @example - * - * _.map([1, 2, 3], function(num) { return num * 3; }); - * // => [3, 6, 9] - * - * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); - * // => [3, 6, 9] (property order is not guaranteed across environments) - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * // using "_.pluck" callback shorthand - * _.map(characters, 'name'); - * // => ['barney', 'fred'] - */ - function map(collection, callback, thisArg) { - var index = -1, - length = collection ? collection.length : 0, - result = Array(typeof length == 'number' ? length : 0); - - callback = lodash.createCallback(callback, thisArg, 3); - if (isArray(collection)) { - while (++index < length) { - result[index] = callback(collection[index], index, collection); - } - } else { - baseEach(collection, function(value, key, collection) { - result[++index] = callback(value, key, collection); - }); - } - return result; - } - - /** - * Retrieves the maximum value of a collection. If the collection is empty or - * falsey `-Infinity` is returned. If a callback is provided it will be executed - * for each value in the collection to generate the criterion by which the value - * is ranked. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the maximum value. - * @example - * - * _.max([4, 2, 8, 6]); - * // => 8 - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * _.max(characters, function(chr) { return chr.age; }); - * // => { 'name': 'fred', 'age': 40 }; - * - * // using "_.pluck" callback shorthand - * _.max(characters, 'age'); - * // => { 'name': 'fred', 'age': 40 }; - */ - function max(collection, callback, thisArg) { - var computed = -Infinity, - result = computed; - - // allows working with functions like `_.map` without using - // their `index` argument as a callback - if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { - callback = null; - } - if (callback == null && isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - if (value > result) { - result = value; - } - } - } else { - callback = (callback == null && isString(collection)) - ? charAtCallback - : lodash.createCallback(callback, thisArg, 3); - - baseEach(collection, function(value, index, collection) { - var current = callback(value, index, collection); - if (current > computed) { - computed = current; - result = value; - } - }); - } - return result; - } - - /** - * Retrieves the minimum value of a collection. If the collection is empty or - * falsey `Infinity` is returned. If a callback is provided it will be executed - * for each value in the collection to generate the criterion by which the value - * is ranked. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the minimum value. - * @example - * - * _.min([4, 2, 8, 6]); - * // => 2 - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * _.min(characters, function(chr) { return chr.age; }); - * // => { 'name': 'barney', 'age': 36 }; - * - * // using "_.pluck" callback shorthand - * _.min(characters, 'age'); - * // => { 'name': 'barney', 'age': 36 }; - */ - function min(collection, callback, thisArg) { - var computed = Infinity, - result = computed; - - // allows working with functions like `_.map` without using - // their `index` argument as a callback - if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { - callback = null; - } - if (callback == null && isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - if (value < result) { - result = value; - } - } - } else { - callback = (callback == null && isString(collection)) - ? charAtCallback - : lodash.createCallback(callback, thisArg, 3); - - baseEach(collection, function(value, index, collection) { - var current = callback(value, index, collection); - if (current < computed) { - computed = current; - result = value; - } - }); - } - return result; - } - - /** - * Retrieves the value of a specified property from all elements in the collection. - * - * @static - * @memberOf _ - * @type Function - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {string} property The name of the property to pluck. - * @returns {Array} Returns a new array of property values. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * _.pluck(characters, 'name'); - * // => ['barney', 'fred'] - */ - var pluck = map; - - /** - * Reduces a collection to a value which is the accumulated result of running - * each element in the collection through the callback, where each successive - * callback execution consumes the return value of the previous execution. If - * `accumulator` is not provided the first element of the collection will be - * used as the initial `accumulator` value. The callback is bound to `thisArg` - * and invoked with four arguments; (accumulator, value, index|key, collection). - * - * @static - * @memberOf _ - * @alias foldl, inject - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [accumulator] Initial value of the accumulator. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the accumulated value. - * @example - * - * var sum = _.reduce([1, 2, 3], function(sum, num) { - * return sum + num; - * }); - * // => 6 - * - * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { - * result[key] = num * 3; - * return result; - * }, {}); - * // => { 'a': 3, 'b': 6, 'c': 9 } - */ - function reduce(collection, callback, accumulator, thisArg) { - var noaccum = arguments.length < 3; - callback = lodash.createCallback(callback, thisArg, 4); - - if (isArray(collection)) { - var index = -1, - length = collection.length; - - if (noaccum) { - accumulator = collection[++index]; - } - while (++index < length) { - accumulator = callback(accumulator, collection[index], index, collection); - } - } else { - baseEach(collection, function(value, index, collection) { - accumulator = noaccum - ? (noaccum = false, value) - : callback(accumulator, value, index, collection) - }); - } - return accumulator; - } - - /** - * This method is like `_.reduce` except that it iterates over elements - * of a `collection` from right to left. - * - * @static - * @memberOf _ - * @alias foldr - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [accumulator] Initial value of the accumulator. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the accumulated value. - * @example - * - * var list = [[0, 1], [2, 3], [4, 5]]; - * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, callback, accumulator, thisArg) { - var noaccum = arguments.length < 3; - callback = lodash.createCallback(callback, thisArg, 4); - forEachRight(collection, function(value, index, collection) { - accumulator = noaccum - ? (noaccum = false, value) - : callback(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The opposite of `_.filter` this method returns the elements of a - * collection that the callback does **not** return truey for. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of elements that failed the callback check. - * @example - * - * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); - * // => [1, 3, 5] - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true } - * ]; - * - * // using "_.pluck" callback shorthand - * _.reject(characters, 'blocked'); - * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] - * - * // using "_.where" callback shorthand - * _.reject(characters, { 'age': 36 }); - * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] - */ - function reject(collection, callback, thisArg) { - callback = lodash.createCallback(callback, thisArg, 3); - return filter(collection, function(value, index, collection) { - return !callback(value, index, collection); - }); - } - - /** - * Retrieves a random element or `n` random elements from a collection. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to sample. - * @param {number} [n] The number of elements to sample. - * @param- {Object} [guard] Allows working with functions like `_.map` - * without using their `index` arguments as `n`. - * @returns {Array} Returns the random sample(s) of `collection`. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - * - * _.sample([1, 2, 3, 4], 2); - * // => [3, 1] - */ - function sample(collection, n, guard) { - if (collection && typeof collection.length != 'number') { - collection = values(collection); - } else if (support.unindexedChars && isString(collection)) { - collection = collection.split(''); - } - if (n == null || guard) { - return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; - } - var result = shuffle(collection); - result.length = nativeMin(nativeMax(0, n), result.length); - return result; - } - - /** - * Creates an array of shuffled values, using a version of the Fisher-Yates - * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to shuffle. - * @returns {Array} Returns a new shuffled collection. - * @example - * - * _.shuffle([1, 2, 3, 4, 5, 6]); - * // => [4, 1, 6, 3, 5, 2] - */ - function shuffle(collection) { - var index = -1, - length = collection ? collection.length : 0, - result = Array(typeof length == 'number' ? length : 0); - - forEach(collection, function(value) { - var rand = baseRandom(0, ++index); - result[index] = result[rand]; - result[rand] = value; - }); - return result; - } - - /** - * Gets the size of the `collection` by returning `collection.length` for arrays - * and array-like objects or the number of own enumerable properties for objects. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns `collection.length` or number of own enumerable properties. - * @example - * - * _.size([1, 2]); - * // => 2 - * - * _.size({ 'one': 1, 'two': 2, 'three': 3 }); - * // => 3 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - var length = collection ? collection.length : 0; - return typeof length == 'number' ? length : keys(collection).length; - } - - /** - * Checks if the callback returns a truey value for **any** element of a - * collection. The function returns as soon as it finds a passing value and - * does not iterate over the entire collection. The callback is bound to - * `thisArg` and invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias any - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {boolean} Returns `true` if any element passed the callback check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true } - * ]; - * - * // using "_.pluck" callback shorthand - * _.some(characters, 'blocked'); - * // => true - * - * // using "_.where" callback shorthand - * _.some(characters, { 'age': 1 }); - * // => false - */ - function some(collection, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - - if (isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - if ((result = callback(collection[index], index, collection))) { - break; - } - } - } else { - baseEach(collection, function(value, index, collection) { - return !(result = callback(value, index, collection)); - }); - } - return !!result; - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection through the callback. This method - * performs a stable sort, that is, it will preserve the original sort order - * of equal elements. The callback is bound to `thisArg` and invoked with - * three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an array of property names is provided for `callback` the collection - * will be sorted by each property value. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Array|Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of sorted elements. - * @example - * - * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); - * // => [3, 1, 2] - * - * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); - * // => [3, 1, 2] - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 }, - * { 'name': 'barney', 'age': 26 }, - * { 'name': 'fred', 'age': 30 } - * ]; - * - * // using "_.pluck" callback shorthand - * _.map(_.sortBy(characters, 'age'), _.values); - * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] - * - * // sorting by multiple properties - * _.map(_.sortBy(characters, ['name', 'age']), _.values); - * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] - */ - function sortBy(collection, callback, thisArg) { - var index = -1, - isArr = isArray(callback), - length = collection ? collection.length : 0, - result = Array(typeof length == 'number' ? length : 0); - - if (!isArr) { - callback = lodash.createCallback(callback, thisArg, 3); - } - forEach(collection, function(value, key, collection) { - var object = result[++index] = getObject(); - if (isArr) { - object.criteria = map(callback, function(key) { return value[key]; }); - } else { - (object.criteria = getArray())[0] = callback(value, key, collection); - } - object.index = index; - object.value = value; - }); - - length = result.length; - result.sort(compareAscending); - while (length--) { - var object = result[length]; - result[length] = object.value; - if (!isArr) { - releaseArray(object.criteria); - } - releaseObject(object); - } - return result; - } - - /** - * Converts the `collection` to an array. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to convert. - * @returns {Array} Returns the new converted array. - * @example - * - * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); - * // => [2, 3, 4] - */ - function toArray(collection) { - if (collection && typeof collection.length == 'number') { - return (support.unindexedChars && isString(collection)) - ? collection.split('') - : slice(collection); - } - return values(collection); - } - - /** - * Performs a deep comparison of each element in a `collection` to the given - * `properties` object, returning an array of all elements that have equivalent - * property values. - * - * @static - * @memberOf _ - * @type Function - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Object} props The object of property values to filter by. - * @returns {Array} Returns a new array of elements that have the given properties. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, - * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } - * ]; - * - * _.where(characters, { 'age': 36 }); - * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] - * - * _.where(characters, { 'pets': ['dino'] }); - * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] - */ - var where = filter; - - /*--------------------------------------------------------------------------*/ - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are all falsey. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to compact. - * @returns {Array} Returns a new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array ? array.length : 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result.push(value); - } - } - return result; - } - - /** - * Creates an array excluding all values of the provided arrays using strict - * equality for comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to process. - * @param {...Array} [values] The arrays of values to exclude. - * @returns {Array} Returns a new array of filtered values. - * @example - * - * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); - * // => [1, 3, 4] - */ - function difference(array) { - return baseDifference(array, baseFlatten(arguments, true, true, 1)); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element that passes the callback check, instead of the element itself. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true }, - * { 'name': 'pebbles', 'age': 1, 'blocked': false } - * ]; - * - * _.findIndex(characters, function(chr) { - * return chr.age < 20; - * }); - * // => 2 - * - * // using "_.where" callback shorthand - * _.findIndex(characters, { 'age': 36 }); - * // => 0 - * - * // using "_.pluck" callback shorthand - * _.findIndex(characters, 'blocked'); - * // => 1 - */ - function findIndex(array, callback, thisArg) { - var index = -1, - length = array ? array.length : 0; - - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length) { - if (callback(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of a `collection` from right to left. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': true }, - * { 'name': 'fred', 'age': 40, 'blocked': false }, - * { 'name': 'pebbles', 'age': 1, 'blocked': true } - * ]; - * - * _.findLastIndex(characters, function(chr) { - * return chr.age > 30; - * }); - * // => 1 - * - * // using "_.where" callback shorthand - * _.findLastIndex(characters, { 'age': 36 }); - * // => 0 - * - * // using "_.pluck" callback shorthand - * _.findLastIndex(characters, 'blocked'); - * // => 2 - */ - function findLastIndex(array, callback, thisArg) { - var length = array ? array.length : 0; - callback = lodash.createCallback(callback, thisArg, 3); - while (length--) { - if (callback(array[length], length, array)) { - return length; - } - } - return -1; - } - - /** - * Gets the first element or first `n` elements of an array. If a callback - * is provided elements at the beginning of the array are returned as long - * as the callback returns truey. The callback is bound to `thisArg` and - * invoked with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias head, take - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback] The function called - * per element or the number of elements to return. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the first element(s) of `array`. - * @example - * - * _.first([1, 2, 3]); - * // => 1 - * - * _.first([1, 2, 3], 2); - * // => [1, 2] - * - * _.first([1, 2, 3], function(num) { - * return num < 3; - * }); - * // => [1, 2] - * - * var characters = [ - * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.first(characters, 'blocked'); - * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] - * - * // using "_.where" callback shorthand - * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); - * // => ['barney', 'fred'] - */ - function first(array, callback, thisArg) { - var n = 0, - length = array ? array.length : 0; - - if (typeof callback != 'number' && callback != null) { - var index = -1; - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length && callback(array[index], index, array)) { - n++; - } - } else { - n = callback; - if (n == null || thisArg) { - return array ? array[0] : undefined; - } - } - return slice(array, 0, nativeMin(nativeMax(0, n), length)); - } - - /** - * Flattens a nested array (the nesting can be to any depth). If `isShallow` - * is truey, the array will only be flattened a single level. If a callback - * is provided each element of the array is passed through the callback before - * flattening. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to flatten. - * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new flattened array. - * @example - * - * _.flatten([1, [2], [3, [[4]]]]); - * // => [1, 2, 3, 4]; - * - * _.flatten([1, [2], [3, [[4]]]], true); - * // => [1, 2, 3, [[4]]]; - * - * var characters = [ - * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, - * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } - * ]; - * - * // using "_.pluck" callback shorthand - * _.flatten(characters, 'pets'); - * // => ['hoppy', 'baby puss', 'dino'] - */ - function flatten(array, isShallow, callback, thisArg) { - // juggle arguments - if (typeof isShallow != 'boolean' && isShallow != null) { - thisArg = callback; - callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; - isShallow = false; - } - if (callback != null) { - array = map(array, callback, thisArg); - } - return baseFlatten(array, isShallow); - } - - /** - * Gets the index at which the first occurrence of `value` is found using - * strict equality for comparisons, i.e. `===`. If the array is already sorted - * providing `true` for `fromIndex` will run a faster binary search. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {boolean|number} [fromIndex=0] The index to search from or `true` - * to perform a binary search on a sorted array. - * @returns {number} Returns the index of the matched value or `-1`. - * @example - * - * _.indexOf([1, 2, 3, 1, 2, 3], 2); - * // => 1 - * - * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); - * // => 4 - * - * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); - * // => 2 - */ - function indexOf(array, value, fromIndex) { - if (typeof fromIndex == 'number') { - var length = array ? array.length : 0; - fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); - } else if (fromIndex) { - var index = sortedIndex(array, value); - return array[index] === value ? index : -1; - } - return baseIndexOf(array, value, fromIndex); - } - - /** - * Gets all but the last element or last `n` elements of an array. If a - * callback is provided elements at the end of the array are excluded from - * the result as long as the callback returns truey. The callback is bound - * to `thisArg` and invoked with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback=1] The function called - * per element or the number of elements to exclude. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - * - * _.initial([1, 2, 3], 2); - * // => [1] - * - * _.initial([1, 2, 3], function(num) { - * return num > 1; - * }); - * // => [1] - * - * var characters = [ - * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.initial(characters, 'blocked'); - * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] - * - * // using "_.where" callback shorthand - * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); - * // => ['barney', 'fred'] - */ - function initial(array, callback, thisArg) { - var n = 0, - length = array ? array.length : 0; - - if (typeof callback != 'number' && callback != null) { - var index = length; - callback = lodash.createCallback(callback, thisArg, 3); - while (index-- && callback(array[index], index, array)) { - n++; - } - } else { - n = (callback == null || thisArg) ? 1 : callback || n; - } - return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); - } - - /** - * Creates an array of unique values present in all provided arrays using - * strict equality for comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {...Array} [array] The arrays to inspect. - * @returns {Array} Returns an array of shared values. - * @example - * - * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); - * // => [1, 2] - */ - function intersection() { - var args = [], - argsIndex = -1, - argsLength = arguments.length, - caches = getArray(), - indexOf = getIndexOf(), - trustIndexOf = indexOf === baseIndexOf, - seen = getArray(); - - while (++argsIndex < argsLength) { - var value = arguments[argsIndex]; - if (isArray(value) || isArguments(value)) { - args.push(value); - caches.push(trustIndexOf && value.length >= largeArraySize && - createCache(argsIndex ? args[argsIndex] : seen)); - } - } - var array = args[0], - index = -1, - length = array ? array.length : 0, - result = []; - - outer: - while (++index < length) { - var cache = caches[0]; - value = array[index]; - - if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { - argsIndex = argsLength; - (cache || seen).push(value); - while (--argsIndex) { - cache = caches[argsIndex]; - if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { - continue outer; - } - } - result.push(value); - } - } - while (argsLength--) { - cache = caches[argsLength]; - if (cache) { - releaseObject(cache); - } - } - releaseArray(caches); - releaseArray(seen); - return result; - } - - /** - * Gets the last element or last `n` elements of an array. If a callback is - * provided elements at the end of the array are returned as long as the - * callback returns truey. The callback is bound to `thisArg` and invoked - * with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback] The function called - * per element or the number of elements to return. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the last element(s) of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - * - * _.last([1, 2, 3], 2); - * // => [2, 3] - * - * _.last([1, 2, 3], function(num) { - * return num > 1; - * }); - * // => [2, 3] - * - * var characters = [ - * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.pluck(_.last(characters, 'blocked'), 'name'); - * // => ['fred', 'pebbles'] - * - * // using "_.where" callback shorthand - * _.last(characters, { 'employer': 'na' }); - * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] - */ - function last(array, callback, thisArg) { - var n = 0, - length = array ? array.length : 0; - - if (typeof callback != 'number' && callback != null) { - var index = length; - callback = lodash.createCallback(callback, thisArg, 3); - while (index-- && callback(array[index], index, array)) { - n++; - } - } else { - n = callback; - if (n == null || thisArg) { - return array ? array[length - 1] : undefined; - } - } - return slice(array, nativeMax(0, length - n)); - } - - /** - * Gets the index at which the last occurrence of `value` is found using strict - * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used - * as the offset from the end of the collection. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value or `-1`. - * @example - * - * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); - * // => 4 - * - * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); - * // => 1 - */ - function lastIndexOf(array, value, fromIndex) { - var index = array ? array.length : 0; - if (typeof fromIndex == 'number') { - index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; - } - while (index--) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * Removes all provided values from the given array using strict equality for - * comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to modify. - * @param {...*} [value] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3, 1, 2, 3]; - * _.pull(array, 2, 3); - * console.log(array); - * // => [1, 1] - */ - function pull(array) { - var args = arguments, - argsIndex = 0, - argsLength = args.length, - length = array ? array.length : 0; - - while (++argsIndex < argsLength) { - var index = -1, - value = args[argsIndex]; - while (++index < length) { - if (array[index] === value) { - splice.call(array, index--, 1); - length--; - } - } - } - return array; - } - - /** - * Creates an array of numbers (positive and/or negative) progressing from - * `start` up to but not including `end`. If `start` is less than `stop` a - * zero-length range is created unless a negative `step` is specified. - * - * @static - * @memberOf _ - * @category Arrays - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @param {number} [step=1] The value to increment or decrement by. - * @returns {Array} Returns a new range array. - * @example - * - * _.range(4); - * // => [0, 1, 2, 3] - * - * _.range(1, 5); - * // => [1, 2, 3, 4] - * - * _.range(0, 20, 5); - * // => [0, 5, 10, 15] - * - * _.range(0, -4, -1); - * // => [0, -1, -2, -3] - * - * _.range(1, 4, 0); - * // => [1, 1, 1] - * - * _.range(0); - * // => [] - */ - function range(start, end, step) { - start = +start || 0; - step = typeof step == 'number' ? step : (+step || 1); - - if (end == null) { - end = start; - start = 0; - } - // use `Array(length)` so engines like Chakra and V8 avoid slower modes - // http://youtu.be/XAqIpGU8ZZk#t=17m25s - var index = -1, - length = nativeMax(0, ceil((end - start) / (step || 1))), - result = Array(length); - - while (++index < length) { - result[index] = start; - start += step; - } - return result; - } - - /** - * Removes all elements from an array that the callback returns truey for - * and returns an array of removed elements. The callback is bound to `thisArg` - * and invoked with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to modify. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4, 5, 6]; - * var evens = _.remove(array, function(num) { return num % 2 == 0; }); - * - * console.log(array); - * // => [1, 3, 5] - * - * console.log(evens); - * // => [2, 4, 6] - */ - function remove(array, callback, thisArg) { - var index = -1, - length = array ? array.length : 0, - result = []; - - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length) { - var value = array[index]; - if (callback(value, index, array)) { - result.push(value); - splice.call(array, index--, 1); - length--; - } - } - return result; - } - - /** - * The opposite of `_.initial` this method gets all but the first element or - * first `n` elements of an array. If a callback function is provided elements - * at the beginning of the array are excluded from the result as long as the - * callback returns truey. The callback is bound to `thisArg` and invoked - * with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias drop, tail - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback=1] The function called - * per element or the number of elements to exclude. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a slice of `array`. - * @example - * - * _.rest([1, 2, 3]); - * // => [2, 3] - * - * _.rest([1, 2, 3], 2); - * // => [3] - * - * _.rest([1, 2, 3], function(num) { - * return num < 3; - * }); - * // => [3] - * - * var characters = [ - * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.pluck(_.rest(characters, 'blocked'), 'name'); - * // => ['fred', 'pebbles'] - * - * // using "_.where" callback shorthand - * _.rest(characters, { 'employer': 'slate' }); - * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] - */ - function rest(array, callback, thisArg) { - if (typeof callback != 'number' && callback != null) { - var n = 0, - index = -1, - length = array ? array.length : 0; - - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length && callback(array[index], index, array)) { - n++; - } - } else { - n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); - } - return slice(array, n); - } - - /** - * Uses a binary search to determine the smallest index at which a value - * should be inserted into a given sorted array in order to maintain the sort - * order of the array. If a callback is provided it will be executed for - * `value` and each element of `array` to compute their sort ranking. The - * callback is bound to `thisArg` and invoked with one argument; (value). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to inspect. - * @param {*} value The value to evaluate. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([20, 30, 50], 40); - * // => 2 - * - * // using "_.pluck" callback shorthand - * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); - * // => 2 - * - * var dict = { - * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } - * }; - * - * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { - * return dict.wordToNumber[word]; - * }); - * // => 2 - * - * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { - * return this.wordToNumber[word]; - * }, dict); - * // => 2 - */ - function sortedIndex(array, value, callback, thisArg) { - var low = 0, - high = array ? array.length : low; - - // explicitly reference `identity` for better inlining in Firefox - callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; - value = callback(value); - - while (low < high) { - var mid = (low + high) >>> 1; - (callback(array[mid]) < value) - ? low = mid + 1 - : high = mid; - } - return low; - } - - /** - * Creates an array of unique values, in order, of the provided arrays using - * strict equality for comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {...Array} [array] The arrays to inspect. - * @returns {Array} Returns an array of combined values. - * @example - * - * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); - * // => [1, 2, 3, 5, 4] - */ - function union() { - return baseUniq(baseFlatten(arguments, true, true)); - } - - /** - * Creates a duplicate-value-free version of an array using strict equality - * for comparisons, i.e. `===`. If the array is sorted, providing - * `true` for `isSorted` will use a faster algorithm. If a callback is provided - * each element of `array` is passed through the callback before uniqueness - * is computed. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias unique - * @category Arrays - * @param {Array} array The array to process. - * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a duplicate-value-free array. - * @example - * - * _.uniq([1, 2, 1, 3, 1]); - * // => [1, 2, 3] - * - * _.uniq([1, 1, 2, 2, 3], true); - * // => [1, 2, 3] - * - * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); - * // => ['A', 'b', 'C'] - * - * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); - * // => [1, 2.5, 3] - * - * // using "_.pluck" callback shorthand - * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniq(array, isSorted, callback, thisArg) { - // juggle arguments - if (typeof isSorted != 'boolean' && isSorted != null) { - thisArg = callback; - callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; - isSorted = false; - } - if (callback != null) { - callback = lodash.createCallback(callback, thisArg, 3); - } - return baseUniq(array, isSorted, callback); - } - - /** - * Creates an array excluding all provided values using strict equality for - * comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to filter. - * @param {...*} [value] The values to exclude. - * @returns {Array} Returns a new array of filtered values. - * @example - * - * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); - * // => [2, 3, 4] - */ - function without(array) { - return baseDifference(array, slice(arguments, 1)); - } - - /** - * Creates an array that is the symmetric difference of the provided arrays. - * See http://en.wikipedia.org/wiki/Symmetric_difference. - * - * @static - * @memberOf _ - * @category Arrays - * @param {...Array} [array] The arrays to inspect. - * @returns {Array} Returns an array of values. - * @example - * - * _.xor([1, 2, 3], [5, 2, 1, 4]); - * // => [3, 5, 4] - * - * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); - * // => [1, 4, 5] - */ - function xor() { - var index = -1, - length = arguments.length; - - while (++index < length) { - var array = arguments[index]; - if (isArray(array) || isArguments(array)) { - var result = result - ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) - : array; - } - } - return result || []; - } - - /** - * Creates an array of grouped elements, the first of which contains the first - * elements of the given arrays, the second of which contains the second - * elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @alias unzip - * @category Arrays - * @param {...Array} [array] Arrays to process. - * @returns {Array} Returns a new array of grouped elements. - * @example - * - * _.zip(['fred', 'barney'], [30, 40], [true, false]); - * // => [['fred', 30, true], ['barney', 40, false]] - */ - function zip() { - var array = arguments.length > 1 ? arguments : arguments[0], - index = -1, - length = array ? max(pluck(array, 'length')) : 0, - result = Array(length < 0 ? 0 : length); - - while (++index < length) { - result[index] = pluck(array, index); - } - return result; - } - - /** - * Creates an object composed from arrays of `keys` and `values`. Provide - * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` - * or two arrays, one of `keys` and one of corresponding `values`. - * - * @static - * @memberOf _ - * @alias object - * @category Arrays - * @param {Array} keys The array of keys. - * @param {Array} [values=[]] The array of values. - * @returns {Object} Returns an object composed of the given keys and - * corresponding values. - * @example - * - * _.zipObject(['fred', 'barney'], [30, 40]); - * // => { 'fred': 30, 'barney': 40 } - */ - function zipObject(keys, values) { - var index = -1, - length = keys ? keys.length : 0, - result = {}; - - if (!values && length && !isArray(keys[0])) { - values = []; - } - while (++index < length) { - var key = keys[index]; - if (values) { - result[key] = values[index]; - } else if (key) { - result[key[0]] = key[1]; - } - } - return result; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Creates a function that executes `func`, with the `this` binding and - * arguments of the created function, only after being called `n` times. - * - * @static - * @memberOf _ - * @category Functions - * @param {number} n The number of times the function must be called before - * `func` is executed. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('Done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => logs 'Done saving!', after all saves have completed - */ - function after(n, func) { - if (!isFunction(func)) { - throw new TypeError; - } - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that, when called, invokes `func` with the `this` - * binding of `thisArg` and prepends any additional `bind` arguments to those - * provided to the bound function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to bind. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var func = function(greeting) { - * return greeting + ' ' + this.name; - * }; - * - * func = _.bind(func, { 'name': 'fred' }, 'hi'); - * func(); - * // => 'hi fred' - */ - function bind(func, thisArg) { - return arguments.length > 2 - ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) - : createWrapper(func, 1, null, null, thisArg); - } - - /** - * Binds methods of an object to the object itself, overwriting the existing - * method. Method names may be specified as individual arguments or as arrays - * of method names. If no method names are provided all the function properties - * of `object` will be bound. - * - * @static - * @memberOf _ - * @category Functions - * @param {Object} object The object to bind and assign the bound methods to. - * @param {...string} [methodName] The object method names to - * bind, specified as individual method names or arrays of method names. - * @returns {Object} Returns `object`. - * @example - * - * var view = { - * 'label': 'docs', - * 'onClick': function() { console.log('clicked ' + this.label); } - * }; - * - * _.bindAll(view); - * jQuery('#docs').on('click', view.onClick); - * // => logs 'clicked docs', when the button is clicked - */ - function bindAll(object) { - var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), - index = -1, - length = funcs.length; - - while (++index < length) { - var key = funcs[index]; - object[key] = createWrapper(object[key], 1, null, null, object); - } - return object; - } - - /** - * Creates a function that, when called, invokes the method at `object[key]` - * and prepends any additional `bindKey` arguments to those provided to the bound - * function. This method differs from `_.bind` by allowing bound functions to - * reference methods that will be redefined or don't yet exist. - * See http://michaux.ca/articles/lazy-function-definition-pattern. - * - * @static - * @memberOf _ - * @category Functions - * @param {Object} object The object the method belongs to. - * @param {string} key The key of the method. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'name': 'fred', - * 'greet': function(greeting) { - * return greeting + ' ' + this.name; - * } - * }; - * - * var func = _.bindKey(object, 'greet', 'hi'); - * func(); - * // => 'hi fred' - * - * object.greet = function(greeting) { - * return greeting + 'ya ' + this.name + '!'; - * }; - * - * func(); - * // => 'hiya fred!' - */ - function bindKey(object, key) { - return arguments.length > 2 - ? createWrapper(key, 19, slice(arguments, 2), null, object) - : createWrapper(key, 3, null, null, object); - } - - /** - * Creates a function that is the composition of the provided functions, - * where each function consumes the return value of the function that follows. - * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. - * Each function is executed with the `this` binding of the composed function. - * - * @static - * @memberOf _ - * @category Functions - * @param {...Function} [func] Functions to compose. - * @returns {Function} Returns the new composed function. - * @example - * - * var realNameMap = { - * 'pebbles': 'penelope' - * }; - * - * var format = function(name) { - * name = realNameMap[name.toLowerCase()] || name; - * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); - * }; - * - * var greet = function(formatted) { - * return 'Hiya ' + formatted + '!'; - * }; - * - * var welcome = _.compose(greet, format); - * welcome('pebbles'); - * // => 'Hiya Penelope!' - */ - function compose() { - var funcs = arguments, - length = funcs.length; - - while (length--) { - if (!isFunction(funcs[length])) { - throw new TypeError; - } - } - return function() { - var args = arguments, - length = funcs.length; - - while (length--) { - args = [funcs[length].apply(this, args)]; - } - return args[0]; - }; - } - - /** - * Creates a function which accepts one or more arguments of `func` that when - * invoked either executes `func` returning its result, if all `func` arguments - * have been provided, or returns a function that accepts one or more of the - * remaining `func` arguments, and so on. The arity of `func` can be specified - * if `func.length` is not sufficient. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @returns {Function} Returns the new curried function. - * @example - * - * var curried = _.curry(function(a, b, c) { - * console.log(a + b + c); - * }); - * - * curried(1)(2)(3); - * // => 6 - * - * curried(1, 2)(3); - * // => 6 - * - * curried(1, 2, 3); - * // => 6 - */ - function curry(func, arity) { - arity = typeof arity == 'number' ? arity : (+arity || func.length); - return createWrapper(func, 4, null, null, null, arity); - } - - /** - * Creates a function that will delay the execution of `func` until after - * `wait` milliseconds have elapsed since the last time it was invoked. - * Provide an options object to indicate that `func` should be invoked on - * the leading and/or trailing edge of the `wait` timeout. Subsequent calls - * to the debounced function will return the result of the last `func` call. - * - * Note: If `leading` and `trailing` options are `true` `func` will be called - * on the trailing edge of the timeout only if the debounced function is - * invoked more than once during the `wait` timeout. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to debounce. - * @param {number} wait The number of milliseconds to delay. - * @param {Object} [options] The options object. - * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. - * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. - * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // avoid costly calculations while the window size is in flux - * var lazyLayout = _.debounce(calculateLayout, 150); - * jQuery(window).on('resize', lazyLayout); - * - * // execute `sendMail` when the click event is fired, debouncing subsequent calls - * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * }); - * - * // ensure `batchLog` is executed once after 1 second of debounced calls - * var source = new EventSource('/stream'); - * source.addEventListener('message', _.debounce(batchLog, 250, { - * 'maxWait': 1000 - * }, false); - */ - function debounce(func, wait, options) { - var args, - maxTimeoutId, - result, - stamp, - thisArg, - timeoutId, - trailingCall, - lastCalled = 0, - maxWait = false, - trailing = true; - - if (!isFunction(func)) { - throw new TypeError; - } - wait = nativeMax(0, wait) || 0; - if (options === true) { - var leading = true; - trailing = false; - } else if (isObject(options)) { - leading = options.leading; - maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); - trailing = 'trailing' in options ? options.trailing : trailing; - } - var delayed = function() { - var remaining = wait - (now() - stamp); - if (remaining <= 0) { - if (maxTimeoutId) { - clearTimeout(maxTimeoutId); - } - var isCalled = trailingCall; - maxTimeoutId = timeoutId = trailingCall = undefined; - if (isCalled) { - lastCalled = now(); - result = func.apply(thisArg, args); - if (!timeoutId && !maxTimeoutId) { - args = thisArg = null; - } - } - } else { - timeoutId = setTimeout(delayed, remaining); - } - }; - - var maxDelayed = function() { - if (timeoutId) { - clearTimeout(timeoutId); - } - maxTimeoutId = timeoutId = trailingCall = undefined; - if (trailing || (maxWait !== wait)) { - lastCalled = now(); - result = func.apply(thisArg, args); - if (!timeoutId && !maxTimeoutId) { - args = thisArg = null; - } - } - }; - - return function() { - args = arguments; - stamp = now(); - thisArg = this; - trailingCall = trailing && (timeoutId || !leading); - - if (maxWait === false) { - var leadingCall = leading && !timeoutId; - } else { - if (!maxTimeoutId && !leading) { - lastCalled = stamp; - } - var remaining = maxWait - (stamp - lastCalled), - isCalled = remaining <= 0; - - if (isCalled) { - if (maxTimeoutId) { - maxTimeoutId = clearTimeout(maxTimeoutId); - } - lastCalled = stamp; - result = func.apply(thisArg, args); - } - else if (!maxTimeoutId) { - maxTimeoutId = setTimeout(maxDelayed, remaining); - } - } - if (isCalled && timeoutId) { - timeoutId = clearTimeout(timeoutId); - } - else if (!timeoutId && wait !== maxWait) { - timeoutId = setTimeout(delayed, wait); - } - if (leadingCall) { - isCalled = true; - result = func.apply(thisArg, args); - } - if (isCalled && !timeoutId && !maxTimeoutId) { - args = thisArg = null; - } - return result; - }; - } - - /** - * Defers executing the `func` function until the current call stack has cleared. - * Additional arguments will be provided to `func` when it is invoked. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to defer. - * @param {...*} [arg] Arguments to invoke the function with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { console.log(text); }, 'deferred'); - * // logs 'deferred' after one or more milliseconds - */ - function defer(func) { - if (!isFunction(func)) { - throw new TypeError; - } - var args = slice(arguments, 1); - return setTimeout(function() { func.apply(undefined, args); }, 1); - } - - /** - * Executes the `func` function after `wait` milliseconds. Additional arguments - * will be provided to `func` when it is invoked. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay execution. - * @param {...*} [arg] Arguments to invoke the function with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { console.log(text); }, 1000, 'later'); - * // => logs 'later' after one second - */ - function delay(func, wait) { - if (!isFunction(func)) { - throw new TypeError; - } - var args = slice(arguments, 2); - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided it will be used to determine the cache key for storing the result - * based on the arguments provided to the memoized function. By default, the - * first argument provided to the memoized function is used as the cache key. - * The `func` is executed with the `this` binding of the memoized function. - * The result cache is exposed as the `cache` property on the memoized function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] A function used to resolve the cache key. - * @returns {Function} Returns the new memoizing function. - * @example - * - * var fibonacci = _.memoize(function(n) { - * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); - * }); - * - * fibonacci(9) - * // => 34 - * - * var data = { - * 'fred': { 'name': 'fred', 'age': 40 }, - * 'pebbles': { 'name': 'pebbles', 'age': 1 } - * }; - * - * // modifying the result cache - * var get = _.memoize(function(name) { return data[name]; }, _.identity); - * get('pebbles'); - * // => { 'name': 'pebbles', 'age': 1 } - * - * get.cache.pebbles.name = 'penelope'; - * get('pebbles'); - * // => { 'name': 'penelope', 'age': 1 } - */ - function memoize(func, resolver) { - if (!isFunction(func)) { - throw new TypeError; - } - var memoized = function() { - var cache = memoized.cache, - key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; - - return hasOwnProperty.call(cache, key) - ? cache[key] - : (cache[key] = func.apply(this, arguments)); - } - memoized.cache = {}; - return memoized; - } - - /** - * Creates a function that is restricted to execute `func` once. Repeat calls to - * the function will return the value of the first call. The `func` is executed - * with the `this` binding of the created function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // `initialize` executes `createApplication` once - */ - function once(func) { - var ran, - result; - - if (!isFunction(func)) { - throw new TypeError; - } - return function() { - if (ran) { - return result; - } - ran = true; - result = func.apply(this, arguments); - - // clear the `func` variable so the function may be garbage collected - func = null; - return result; - }; - } - - /** - * Creates a function that, when called, invokes `func` with any additional - * `partial` arguments prepended to those provided to the new function. This - * method is similar to `_.bind` except it does **not** alter the `this` binding. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * var greet = function(greeting, name) { return greeting + ' ' + name; }; - * var hi = _.partial(greet, 'hi'); - * hi('fred'); - * // => 'hi fred' - */ - function partial(func) { - return createWrapper(func, 16, slice(arguments, 1)); - } - - /** - * This method is like `_.partial` except that `partial` arguments are - * appended to those provided to the new function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * var defaultsDeep = _.partialRight(_.merge, _.defaults); - * - * var options = { - * 'variable': 'data', - * 'imports': { 'jq': $ } - * }; - * - * defaultsDeep(options, _.templateSettings); - * - * options.variable - * // => 'data' - * - * options.imports - * // => { '_': _, 'jq': $ } - */ - function partialRight(func) { - return createWrapper(func, 32, null, slice(arguments, 1)); - } - - /** - * Creates a function that, when executed, will only call the `func` function - * at most once per every `wait` milliseconds. Provide an options object to - * indicate that `func` should be invoked on the leading and/or trailing edge - * of the `wait` timeout. Subsequent calls to the throttled function will - * return the result of the last `func` call. - * - * Note: If `leading` and `trailing` options are `true` `func` will be called - * on the trailing edge of the timeout only if the throttled function is - * invoked more than once during the `wait` timeout. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to throttle. - * @param {number} wait The number of milliseconds to throttle executions to. - * @param {Object} [options] The options object. - * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // avoid excessively updating the position while scrolling - * var throttled = _.throttle(updatePosition, 100); - * jQuery(window).on('scroll', throttled); - * - * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes - * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { - * 'trailing': false - * })); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (!isFunction(func)) { - throw new TypeError; - } - if (options === false) { - leading = false; - } else if (isObject(options)) { - leading = 'leading' in options ? options.leading : leading; - trailing = 'trailing' in options ? options.trailing : trailing; - } - debounceOptions.leading = leading; - debounceOptions.maxWait = wait; - debounceOptions.trailing = trailing; - - return debounce(func, wait, debounceOptions); - } - - /** - * Creates a function that provides `value` to the wrapper function as its - * first argument. Additional arguments provided to the function are appended - * to those provided to the wrapper function. The wrapper is executed with - * the `this` binding of the created function. - * - * @static - * @memberOf _ - * @category Functions - * @param {*} value The value to wrap. - * @param {Function} wrapper The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

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

Fred, Wilma, & Pebbles

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