2d-quadtree
Version:
Quadtree for games and simulations
1,565 lines (1,319 loc) • 72.8 kB
JavaScript
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var Quadtree = window.Quadtree = require('./quadtree.js');
var map = window.map = new Quadtree();
var object1 = window.object1 = {'x': 10, 'y': 10, 'height': 10, 'width': 10};
var object2 = window.object2 = {'x': 0, 'y': 0, 'height': 20, 'width': 20};
var object3 = window.object3 = {'x': 0, 'y': 0, 'height': 30, 'width': 30};
var object4 = window.object4 = {'x': 0, 'y': 0, 'height': 40, 'width': 40};
var object5 = window.object5 = {'x': 0, 'y': 0, 'height': 50, 'width': 50};
map.insert(object1);
map.insert(object2);
map.insert(object3);
map.insert(object4);
map.insert(object5);
console.log('-----------------------------------------------------------------------------');
console.log('Number of children: ' + map.getChildCount());
console.log('Number of orphans : ' + map.getOrphanCount());
console.log('Number of orphans and children: ' + map.getOrphanAndChildCount());
},{"./quadtree.js":2}],2:[function(require,module,exports){
'use strict';
var _ = require('underscore');
var DEFAULT_MAX_CHILDREN = 4,
DEFAULT_DEPTH = 4,
DEFAULT_WIDTH = 1000,
DEFAULT_HEIGHT = 1000,
NORTH_WEST = 1,
NORTH_EAST = 2,
SOUTH_WEST = 4,
SOUTH_EAST = 8;
/**
* Rectangles inserted into the quadtree are extended with this object literal
*/
var rectPrototype = {
/**
* Moves the rectangle in the quadtree to a new position (x, y)
* @method
* @param {Number} x The x coordinate as defined by the quadtree coordinate system
* @param {Number} y The y coordinate as defined by the quadtree coordinate system
*/
'move': function (x, y) {
this.x = x;
this.y = y;
if (this.parent.orphans.indexOf(this) !== -1 || !isWithinBounds(this.parent, this)) {
this.parent.remove(this);
this.parent.insert(this);
}
},
/**
* Returns an array of the rectangles within the quadtree that intersect with this rectangle
* @method
* @return {Array} The rectangles that intersect with this rectangle
*/
'getCollisions': function () {
return this.parent.getCollisions(this);
},
/**
* Comepletely removes this rectangle from the quadtree
* @method
*/
'remove': function () {
this.parent.remove(this);
}
};
/**
* Quadtree contstructor function. Use to initialize the Quadtree. Also, whenever the quadtree splits,
* this constructor is used to initialize the new nodes of the quadtree.
* @constructor
* @param {Object} options The only options of concern to you: width, height, maxChildren, depth
*/
function Quadtree (options) {
options = options || {};
this.maxChildren = options.maxChildren || DEFAULT_MAX_CHILDREN;
this.depth = options.depth || DEFAULT_DEPTH;
this.height = options.height || DEFAULT_HEIGHT;
this.width = options.width || DEFAULT_WIDTH;
this.halfHeight = this.height / 2;
this.halfWidth = this.width / 2;
this.x = options.x || 0;
this.y = options.y || 0;
this.parent = options.parent || null;
this.children = [];
this.orphans = [];
this.isLeaf = true;
this.quadrant = options.quadrant || (NORTH_WEST + NORTH_EAST + SOUTH_WEST + SOUTH_EAST);
}
/**
*
* Inserts an object into the quadTree
* @param {Object} An arbitrary object with rectangle properties (x, y, width, height)
*/
Quadtree.prototype.insert = function (object) {
var numberOfChildren = this.children.length;
if (!hasRectProps(object)) {
throw 'Inserting an object into the Quadtree requires a height, width, x, and y property';
}
if (!object.move) {
_.extend(object, rectPrototype);
}
if (!isWithinBounds(this, object)) {
if (this.parent) {
this.parent.insert(object);
return;
} else {
forceObjectWithinBounds(object, this);
}
}
object.parent = this;
object.quadrant = undefined;
// This quadTree does not contain quadTrees
if (this.isLeaf) {
this.children.push(object);
setQuadrant(object, this);
if (this.children.length > this.maxChildren && this.depth) {
this.divide();
return;
}
// This quadTree contains quadTrees
// We should check if the object we are inserting can be completely contained within
// one of these quadTrees. If it can't, it must be an orphan.
} else {
for (var i = 0; i < numberOfChildren; i++) {
if (isWithinBounds(this.children[i], object)) {
this.children[i].insert(object);
return;
}
}
// Object does not fit within any of the sub-quadTrees. It's an orphan.
setQuadrant(object, this);
this.orphans.push(object);
}
};
/**
* Removes the object and potentially collapses the quadTree
* @method remove
* @param {Object} Item that was inserted into the quadTree
*/
Quadtree.prototype.remove = function (object) {
var parent = object.parent,
children = parent.children,
orphans = parent.orphans,
newParent = parent;
if (_.contains(children, object)) {
children.splice(children.indexOf(object), 1);
} else if (_.contains(orphans, object)) {
orphans.splice(orphans.indexOf(object), 1);
} else {
throw 'Object not found in quadTree when attempting to remove';
}
while (newParent.parent) {
newParent = newParent.parent;
}
object.parent = newParent;
parent.collapse();
};
/**
* Partitions the quadTree into 4 equal sized quadTrees.
* It also re-inserts all of the children that the leaf contained.
*/
Quadtree.prototype.divide = function () {
var children = this.children,
quarterWidth = this.width / 4,
quarterHeight = this.height / 4,
options = {
'depth' : this.depth - 1,
'width' : this.width / 2,
'height': this.height / 2,
'parent': this
};
this.isLeaf = false;
this.children = [
new Quadtree(_.extend(options, {
'x' : this.x - quarterWidth,
'y' : this.y - quarterHeight,
'quadrant': NORTH_WEST
})),
new Quadtree(_.extend(options, {
'x' : this.x + quarterWidth,
'y' : this.y - quarterHeight,
'quadrant': NORTH_EAST
})),
new Quadtree(_.extend(options, {
'x' : this.x - quarterWidth,
'y' : this.y + quarterHeight,
'quadrant': SOUTH_WEST
})),
new Quadtree(_.extend(options, {
'x' : this.x + quarterWidth,
'y' : this.y + quarterHeight,
'quadrant': SOUTH_EAST
}))
];
for (var i = 0, l = children.length; i < l; i++) {
this.insert(children[i]);
}
};
/**
* Collapses the quadTree
*/
Quadtree.prototype.collapse = function () {
if (this.parent) {
if (this !== this.parent.children[0] && this !== this.parent.children[1] && this !== this.parent.children[2] && this !== this.parent.children[3]) {
throw 'This was a bug that was fixed, but I am paranoid this will get hit so I left it...';
}
}
if (this.parent && this.parent.canCollapse()) {
this.parent.collapse();
return;
}
if (this.canCollapse() && !this.isLeaf) {
var allChildrenAndOrphans = this.getOrphansAndChildren();
this.children = [];
this.orphans = [];
this.isLeaf = true;
for (var i = 0; i < allChildrenAndOrphans.length; i++) {
this.insert(allChildrenAndOrphans[i]);
}
}
};
/**
* Helper method that determines if the quadtree should collapse
*/
Quadtree.prototype.canCollapse = function () {
return this.getOrphanAndChildCount() <= this.maxChildren;
}
/**
* getOrphanCount returns the number of orphans in the quadTree
* @return {Array} number of orphans in the quadTree
*/
Quadtree.prototype.getOrphanCount = function () {
var numberOfOrphans = this.orphans.length,
numberOfChildren = this.children.length,
count = numberOfOrphans;
if (this.isLeaf) {
if (count !== 0) {
throw 'Why does this leaf have orphans?!';
}
return count; // should be 0.
} else {
for (var i = 0; i < numberOfChildren; i++) {
count += this.children[i].getOrphanCount();
}
}
return count;
};
/**
* Returns the number of children in the quadTree
* @return {Number} The number of children in the quadTree
*/
Quadtree.prototype.getChildCount = function () {
var count = 0,
numberOfChildren = this.children.length;
if (!this.isLeaf) {
for (var i = 0; i < numberOfChildren; i++) {
count += this.children[i].getChildCount();
}
} else {
count += numberOfChildren;
}
return count;
};
/**
* getOrphanAndChildCount returns all rectangles that have been inserted into the quadtree
* @return {Number} The number of all inserted objects in the quadtree
*/
Quadtree.prototype.getOrphanAndChildCount = function () {
return this.getOrphanCount() + this.getChildCount();
};
/**
* getOrphans return all the orphans of the quadTree
* @return {Array} all the orphans of the quadTree
*/
Quadtree.prototype.getOrphans = function () {
var orphans = [];
if (!this.isLeaf) {
orphans = this.orphans;
for (var i = 0; i < this.children.length; i++) {
orphans = orphans.concat(this.children[i].getOrphans());
}
}
return orphans;
};
/**
* getChildren returns an array of all the children of the quadTree
* @return {Array} all the children of the quadTree
*/
Quadtree.prototype.getChildren = function () {
var children = [];
if (this.isLeaf) {
return this.children;
} else {
for (var i = 0; i < this.children.length; i++) {
children = children.concat(this.children[i].getChildren());
}
}
return children;
};
/**
* getOrphansAndChildren returns an array of all the children and orphans of the quadTree
* @return {Array} all the children and orphans of the quadTree
*/
Quadtree.prototype.getOrphansAndChildren = function () {
return this.getChildren().concat(this.getOrphans());
};
/**
* getQuadtreeCount returns the number of divisions within the quadtree.
* @return {Number} The number of divisions within the quadtree.
*/
Quadtree.prototype.getQuadtreeCount = function () {
var count = this.children.length;
if (this.isLeaf) {
return 0;
}
for (var i = 0; i < this.children.length; i++) {
count += this.children[i].getQuadtreeCount();
}
return count;
};
Quadtree.prototype.getEntireQuadtreesOrphansAndChildren = function () {
var originalParent = this;
while (originalParent.parent) {
originalParent = originalParent.parent;
}
return originalParent.getOrphansAndChildren();
}
Quadtree.prototype.getParentOrphanComparisons = function () {
var comparisonList = [],
orphans = this.parent && this.parent.orphans;
if (!orphans) {
return comparisonList;
}
for (var i = 0; i < orphans.length; i++) {
if ((orphans[i].quadrant & this.quadrant)) {
comparisonList.push(orphans[i]);
}
}
return comparisonList.concat(this.parent.getParentOrphanComparisons());
};
Quadtree.prototype.getCollisions = function (rect) {
if (!hasRectProps(rect)) {
throw 'Collsion must be a rect';
}
return getCollisions(this.getComparisons(rect), rect);
};
// This might be an area to optimized. A rectangle that is an orphans of the parent-most quadtree
// that overlaps all quadrants will be the same as a brute force collision detector.
Quadtree.prototype.getOrphansAndChildrenInQuadrants = function (rect) {
var orphansAndChildren = [],
quadrant = rect.quadrant;
if (quadrant & NORTH_WEST) {
orphansAndChildren = orphansAndChildren.concat(this.children[0].getOrphansAndChildren());
}
if (quadrant & NORTH_EAST) {
orphansAndChildren = orphansAndChildren.concat(this.children[1].getOrphansAndChildren());
}
if (quadrant & SOUTH_WEST) {
orphansAndChildren = orphansAndChildren.concat(this.children[2].getOrphansAndChildren());
}
if (quadrant & SOUTH_EAST) {
orphansAndChildren = orphansAndChildren.concat(this.children[3].getOrphansAndChildren());
}
return orphansAndChildren;
};
Quadtree.prototype.getComparisons = function (rect) {
if (!hasRectProps(rect)) {
throw 'Collsion must be a rect';
}
if (!rect.quadrant) {
throw 'Rect does not have a quadrant property';
}
var comparisonList = rect.parent.isLeaf ? rect.parent.getChildren() : rect.parent.getOrphansAndChildrenInQuadrants(rect),
directOrphans = rect.parent.orphans,
parentOrphanComparisons = rect.parent.getParentOrphanComparisons(rect);
for (var i = 0; i < directOrphans.length; i++) {
if ((directOrphans[i].quadrant & rect.quadrant)) {
comparisonList.push(directOrphans[i]);
}
}
comparisonList = comparisonList.concat(parentOrphanComparisons);
if (_.contains(comparisonList, rect)) {
comparisonList.splice(comparisonList.indexOf(rect), 1);
}
return comparisonList;
};
Quadtree.prototype.getBruteForceCollisions = function (rect) {
if (!hasRectProps(rect)) {
throw 'Collsion must be a rect';
}
var comparisonList,
currentQuadTree = this;
while (currentQuadTree.parent) {
currentQuadTree = currentQuadTree.parent;
}
comparisonList = currentQuadTree.getOrphansAndChildren();
if (_.contains(comparisonList, rect)) {
comparisonList.splice(comparisonList.indexOf(rect), 1);
}
return getCollisions(comparisonList, rect);
};
// Helper functions
/**
* setQuadrant sets the overlapping quadrants (quadtrees) given an object
* @param {Object} object A rectangle that is inserted in the quadtree
* @param {Object} quadtree A quadtree
*/
function setQuadrant (object, quadtree) {
if (quadtree.isLeaf) {
if (quadtree.parent) {
object.quadrant = (isIntersecting(quadtree.parent.children[0], object) * NORTH_WEST) +
(isIntersecting(quadtree.parent.children[1], object) * NORTH_EAST) +
(isIntersecting(quadtree.parent.children[2], object) * SOUTH_WEST) +
(isIntersecting(quadtree.parent.children[3], object) * SOUTH_EAST);
} else {
object.quadrant = 15;
}
} else {
object.quadrant = (isIntersecting(quadtree.children[0], object) * NORTH_WEST) +
(isIntersecting(quadtree.children[1], object) * NORTH_EAST) +
(isIntersecting(quadtree.children[2], object) * SOUTH_WEST) +
(isIntersecting(quadtree.children[3], object) * SOUTH_EAST);
}
}
/**
* [hasRectProps determines if the object has the necessary properties to be considered a rectangle]
* @param {Object} object [The object questioned for rect props]
* @return {Boolean} [True if it is a rectangle]
*/
function hasRectProps (object) {
return typeof object.width !== 'undefined' && object.height !== 'undefined' && object.x !== 'undefined' && object.y !== 'undefined';
}
/**
* [getBounds returns the bounds of a rectangle]
* @param {Object} r [x, y, width, height]
* @return {Object} [left, right, top, bottom]
*/
function getBounds (r) {
return {
'left' : r.x - r.width / 2,
'right' : r.x + r.width / 2,
'top' : r.y - r.height / 2,
'bottom': r.y + r.height / 2
};
}
/**
* [isWithinBounds retuns true if rect2 is completely within rect1]
* @param {Object} r1 [x, y, width, height]
* @param {Object} r2 [x, y, width, height]
* @return {Boolean} [true if rect2 is completely within rect1]
*/
function isWithinBounds (r1, r2) {
var r1Bounds = getBounds(r1),
r2Bounds = getBounds(r2);
return (r2Bounds.left >= r1Bounds.left &&
r2Bounds.right <= r1Bounds.right &&
r2Bounds.top >= r1Bounds.top &&
r2Bounds.bottom <= r1Bounds.bottom);
}
/**
* [isIntersecting returns true if two rectangles intersect]
* @param {Object} r1 [rectangle]
* @param {Object} r2 [rectangle]
* @return {Boolean} [True if two rectangles isIntersecting]
* @diagram
*
* * * * * * *
* * r2 *
* * * * * *
* * * * * * * *
* * r1 *
* * * * *
*
* * * * * * *
* * r2 *
* * * * * * *
* * * * * * * * r1 *
* * *
* * * * *
*/
function isIntersecting (r1, r2) {
if (r1.radius && r2.radius) {
return isIntersectingCircles(r1, r2);
} else {
return isIntersectingSquares(r1, r2);
}
}
function isIntersectingSquares (r1, r2) {
var r1Bounds = getBounds(r1),
r2Bounds = getBounds(r2);
return (r1Bounds.left < r2Bounds.right &&
r1Bounds.right > r2Bounds.left &&
r1Bounds.top < r2Bounds.bottom &&
r1Bounds.bottom > r2Bounds.top);
}
function isIntersectingCircles (c1, c2) {
var dx = c1.x - c2.x,
dy = c1.y - c2.y,
distance = Math.sqrt(dx * dx + dy * dy);
return distance < c1.radius + c2.radius;
}
function getCollisions (comparisonList, rect) {
var collisionList = [];
for (var i = 0; i < comparisonList.length; i++) {
if (isIntersecting(comparisonList[i], rect)) {
collisionList.push(comparisonList[i]);
}
}
return collisionList;
}
/**
* [forceObjectWithinBounds forces the inserted object into the quadtree bounds.
* This makes the quadtree behave like pac-man when he goes into the opening on
* the side of the map]
* @param {Object} object [This is the parent-most quadtree]
* @param {Object} rect [The inserted rectangle]
*/
function forceObjectWithinBounds (object, rect) {
var objectBounds = getBounds(object),
containerBounds = getBounds(rect),
isTooFarLeft = objectBounds.left < containerBounds.left,
isTooFarRight = objectBounds.left > containerBounds.right,
isTooFarAbove = objectBounds.top < containerBounds.top,
isTooFarBelow = objectBounds.top > containerBounds.bottom;
if (isTooFarLeft) {
while (object.x < containerBounds.left) {
object.x = containerBounds.right + object.x + rect.halfWidth;
}
}
if (isTooFarRight) {
while (object.x > containerBounds.right) {
object.x = containerBounds.left + object.x - rect.halfWidth;
}
}
if (isTooFarAbove) {
while (object.y < containerBounds.top) {
object.y = containerBounds.bottom + object.y + rect.halfHeight;
}
}
if (isTooFarBelow) {
while (object.y > containerBounds.bottom) {
object.y = containerBounds.top + object.y - rect.halfHeight;
}
}
}
module.exports = Quadtree;
},{"underscore":3}],3:[function(require,module,exports){
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
// Naked function reference for surrogate-prototype-swapping.
var Ctor = function(){};
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.8.3';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
var cb = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
};
_.iteratee = function(value, context) {
return cb(value, context, Infinity);
};
// An internal function for creating assigner functions.
var createAssigner = function(keysFunc, undefinedOnly) {
return function(obj) {
var length = arguments.length;
if (length < 2 || obj == null) return obj;
for (var index = 1; index < length; index++) {
var source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
};
// An internal function for creating a new object that inherits from another.
var baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
};
var property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
};
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length);
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Create a reducing function iterating left or right.
function createReduce(dir) {
// Optimized iterator function as using arguments.length
// in the main function will deoptimize the, see #1991.
function iterator(obj, iteratee, memo, keys, index, length) {
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
}
return function(obj, iteratee, memo, context) {
iteratee = optimizeCb(iteratee, context, 4);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1;
// Determine the initial value if none is provided.
if (arguments.length < 3) {
memo = obj[keys ? keys[index] : index];
index += dir;
}
return iterator(obj, iteratee, memo, keys, index, length);
};
}
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = createReduce(1);
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = createReduce(-1);
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var key;
if (isArrayLike(obj)) {
key = _.findIndex(obj, predicate, context);
} else {
key = _.findKey(obj, predicate, context);
}
if (key !== void 0 && key !== -1) return obj[key];
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
predicate = cb(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(cb(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given item (using `===`).
// Aliased as `includes` and `include`.
_.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return _.indexOf(obj, item, fromIndex) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matcher(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matcher(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = isArrayLike(obj) ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = cb(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (isArrayLike(obj)) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = cb(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, startIndex) {
var output = [], idx = 0;
for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
//flatten current level of array or arguments object
if (!shallow) value = flatten(value, shallow, strict);
var j = 0, len = value.length;
output.length += len;
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!_.contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!_.contains(result, value)) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = getLength(array); i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(arguments, true, true, 1);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
return _.unzip(arguments);
};
// Complement of _.zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices
_.unzip = function(array) {
var length = array && _.max(array, getLength).length || 0;
var result = Array(length);
for (var index = 0; index < length; index++) {
result[index] = _.pluck(array, index);
}
return result;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
var result = {};
for (var i = 0, length = getLength(list); i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Generator function to create the findIndex and findLastIndex functions
function createPredicateIndexFinder(dir) {
return function(array, predicate, context) {
predicate = cb(predicate, context);
var length = getLength(array);
var index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
return -1;
};
}
// Returns the first index on an array-like that passes a predicate test
_.findIndex = createPredicateIndexFinder(1);
_.findLastIndex = createPredicateIndexFinder(-1);
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = getLength(array);
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Generator function to create the indexOf and lastIndexOf functions
function createIndexFinder(dir, predicateFind, sortedIndex) {
return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), _.isNaN);
return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
return -1;
};
}
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
_.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Determines whether to execute a function as a constructor
// or a normal function with the provided arguments
var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
var args = slice.call(arguments, 2);
var bound = function() {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
var bound = function() {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = _.partial(_.delay, _, 1);
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = fu