1.7.0~dfsg/0000755000000000000000000000000012377203462011267 5ustar rootroot1.7.0~dfsg/package.json0000644000000000000000000000211112377203462013550 0ustar rootroot{ "name": "underscore", "description": "JavaScript's functional programming helper library.", "homepage": "http://underscorejs.org", "keywords": [ "util", "functional", "server", "client", "browser" ], "author": "Jeremy Ashkenas ", "repository": { "type": "git", "url": "git://github.com/jashkenas/underscore.git" }, "main": "underscore.js", "version": "1.7.0", "devDependencies": { "docco": "0.6.x", "phantomjs": "1.9.7-1", "uglify-js": "2.4.x", "eslint": "0.6.x" }, "scripts": { "test": "phantomjs test/vendor/runner.js test/index.html?noglobals=true && eslint underscore.js test/*.js test/vendor/runner.js", "build": "uglifyjs underscore.js -c \"evaluate=false\" --comments \"/ .*/\" -m --source-map underscore-min.map -o underscore-min.js", "doc": "docco underscore.js" }, "licenses": [ { "type": "MIT", "url": "https://raw.github.com/jashkenas/underscore/master/LICENSE" } ], "files": [ "underscore.js", "underscore-min.js", "LICENSE" ] } 1.7.0~dfsg/index.html0000644000000000000000000034224512377203462013276 0ustar rootroot Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?” … and the tie to go along with jQuery's tux and Backbone's suspenders.

Underscore provides over 100 functions that support both your favorite workaday functional helpers: map, filter, invoke — as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so on.

A complete Test & Benchmark Suite is included for your perusal.

You may also read through the annotated source code.

Enjoying Underscore, and want to turn it up to 11? Try Underscore-contrib.

The project is hosted on GitHub. You can report bugs and discuss features on the issues page, on Freenode in the #documentcloud channel, or send tweets to @documentcloud.

Underscore is an open-source component of DocumentCloud.

Downloads (Right-click, and use "Save As")

Development Version (1.7.0) 44kb, Uncompressed with Plentiful Comments
Production Version (1.7.0) 5.0kb, Minified and Gzipped  (Source Map)
Edge Version Unreleased, current master, use at your own risk

Installation

Collection Functions (Arrays or Objects)

each_.each(list, iteratee, [context]) Alias: forEach
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining.

_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, alert);
=> alerts each number value in turn...

Note: Collection functions work on arrays, objects, and array-like objects such as arguments, NodeList and similar. But it works by duck-typing, so avoid passing objects with a numeric length property. It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.

map_.map(list, iteratee, [context]) Alias: collect
Produces a new array of values by mapping each value in list through a transformation function (iteratee). If list is a JavaScript object, iteratee's arguments will be (value, key, list).

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]

reduce_.reduce(list, iteratee, [memo], [context]) Aliases: inject, foldl
Also known as inject and foldl, reduce boils down a list of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iteratee. The iteratee is passed four arguments: the memo, then the value and index (or key) of the iteration, and finally a reference to the entire list.

If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.

var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6

reduceRight_.reduceRight(list, iteratee, memo, [context]) Alias: foldr
The right-associative version of reduce. Delegates to the JavaScript 1.8 version of reduceRight, if it exists. Foldr is not as useful in JavaScript as it would be in a language with lazy evaluation.

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]

find_.find(list, predicate, [context]) Alias: detect
Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.

var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2

filter_.filter(list, predicate, [context]) Alias: select
Looks through each value in the list, returning an array of all the values that pass a truth test (predicate).

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

where_.where(list, properties)
Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.

_.where(listOfPlays, {author: "Shakespeare", year: 1611});
=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},
    {title: "The Tempest", author: "Shakespeare", year: 1611}]

findWhere_.findWhere(list, properties)
Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});
=> {year: 1918, newsroom: "The New York Times",
  reason: "For its public service in publishing in full so many official reports,
  documents and speeches by European statesmen relating to the progress and
  conduct of the war."}

reject_.reject(list, predicate, [context])
Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter.

var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]

every_.every(list, [predicate], [context]) Alias: all
Returns true if all of the values in the list pass the predicate truth test.

_.every([true, 1, null, 'yes'], _.identity);
=> false

some_.some(list, [predicate], [context]) Alias: any
Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found.

_.some([null, 0, 'yes', false]);
=> true

contains_.contains(list, value) Alias: include
Returns true if the value is present in the list. Uses indexOf internally, if list is an Array.

_.contains([1, 2, 3], 3);
=> true

invoke_.invoke(list, methodName, *arguments)
Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation.

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
=> [[1, 5, 7], [1, 2, 3]]

pluck_.pluck(list, propertyName)
A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

max_.max(list, [iteratee], [context])
Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};

min_.min(list, [iteratee], [context])
Returns the minimum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. Infinity is returned if list is empty, so an isEmpty guard may be required.

var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
=> 2

sortBy_.sortBy(list, iteratee, [context])
Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iteratee. iteratee may also be the string name of the property to sort by (eg. length).

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]

groupBy_.groupBy(list, iteratee, [context])
Splits a collection into sets, grouped by the result of running each value through iteratee. If iteratee is a string instead of a function, groups by the property named by iteratee on each of the values.

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}

_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}

indexBy_.indexBy(list, iteratee, [context])
Given a list, and an iteratee function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
=> {
  "40": {name: 'moe', age: 40},
  "50": {name: 'larry', age: 50},
  "60": {name: 'curly', age: 60}
}

countBy_.countBy(list, iteratee, [context])
Sorts a list into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.

_.countBy([1, 2, 3, 4, 5], function(num) {
  return num % 2 == 0 ? 'even': 'odd';
});
=> {odd: 3, even: 2}

shuffle_.shuffle(list)
Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.

_.shuffle([1, 2, 3, 4, 5, 6]);
=> [4, 1, 6, 3, 5, 2]

sample_.sample(list, [n])
Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.

_.sample([1, 2, 3, 4, 5, 6]);
=> 4

_.sample([1, 2, 3, 4, 5, 6], 3);
=> [1, 6, 2]

toArray_.toArray(list)
Creates a real Array from the list (anything that can be iterated over). Useful for transmuting the arguments object.

(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
=> [2, 3, 4]

size_.size(list)
Return the number of values in the list.

_.size({one: 1, two: 2, three: 3});
=> 3

partition_.partition(array, predicate)
Split array into two arrays: one whose elements all satisfy predicate and one whose elements all do not satisfy predicate.

_.partition([0, 1, 2, 3, 4, 5], isOdd);
=> [[1, 3, 5], [0, 2, 4]]

Array Functions

Note: All array functions will also work on the arguments object. However, Underscore functions are not designed to work on "sparse" arrays.

first_.first(array, [n]) Alias: head, take
Returns the first element of an array. Passing n will return the first n elements of the array.

_.first([5, 4, 3, 2, 1]);
=> 5

initial_.initial(array, [n])
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result.

_.initial([5, 4, 3, 2, 1]);
=> [5, 4, 3, 2]

last_.last(array, [n])
Returns the last element of an array. Passing n will return the last n elements of the array.

_.last([5, 4, 3, 2, 1]);
=> 1

rest_.rest(array, [index]) Alias: tail, drop
Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.

_.rest([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]

compact_.compact(array)
Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

_.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]

flatten_.flatten(array, [shallow])
Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.

_.flatten([1, [2], [3, [[4]]]]);
=> [1, 2, 3, 4];

_.flatten([1, [2], [3, [[4]]]], true);
=> [1, 2, 3, [[4]]];

without_.without(array, *values)
Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

union_.union(*arrays)
Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

intersection_.intersection(*arrays)
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

difference_.difference(array, *others)
Similar to without, but returns the values from array that are not present in the other arrays.

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique
Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.

_.uniq([1, 2, 1, 3, 1, 4]);
=> [1, 2, 3, 4]

zip_.zip(*arrays)
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes. If you're working with a matrix of nested arrays, _.zip.apply can transpose the matrix in a similar fashion.

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

_.zip.apply(_, arrayOfRowsOfData);
=> arrayOfColumnsOfData

object_.object(list, [values])
Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. If duplicate keys exist, the last value wins.

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}

_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
=> {moe: 30, larry: 40, curly: 50}

indexOf_.indexOf(array, value, [isSorted])
Returns the index at which value can be found in the array, or -1 if value is not present in the array. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search ... or, pass a number as the third argument in order to look for the first matching value in the array after the given index.

_.indexOf([1, 2, 3], 2);
=> 1

lastIndexOf_.lastIndexOf(array, value, [fromIndex])
Returns the index of the last occurrence of value in the array, or -1 if value is not present. Pass fromIndex to start your search at a given index.

_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
=> 4

sortedIndex_.sortedIndex(list, value, [iteratee], [context])
Uses a binary search to determine the index at which the value should be inserted into the list in order to maintain the list's sorted order. If an iteratee function is provided, it will be used to compute the sort ranking of each value, including the value you pass. The iteratee may also be the string name of the property to sort by (eg. length).

_.sortedIndex([10, 20, 30, 40, 50], 35);
=> 3

var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];
_.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');
=> 1

range_.range([start], stop, [step])
A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1. Returns a list of integers from start to stop, incremented (or decremented) by step, exclusive. Note that ranges that stop before they start are considered to be zero-length instead of negative — if you'd like a negative range, use a negative step.

_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0);
=> []

Function (uh, ahem) Functions

bind_.bind(function, object, *arguments)
Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, pass arguments to the function to pre-fill them, also known as partial application. For partial application without context binding, use partial.

var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name: 'moe'}, 'hi');
func();
=> 'hi: moe'

bindAll_.bindAll(object, *methodNames)
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. methodNames are required.

var buttonView = {
  label  : 'underscore',
  onClick: function(){ alert('clicked: ' + this.label); },
  onHover: function(){ console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView, 'onClick', 'onHover');
// When the button is clicked, this.label will have the correct value.
jQuery('#underscore_button').bind('click', buttonView.onClick);

partial_.partial(function, *arguments)
Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be pre-filled, but left open to supply at call-time.

var add = function(a, b) { return a + b; };
add5 = _.partial(add, 5);
add5(10);
=> 15

memoize_.memoize(function, [hashFunction])
Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default hashFunction just uses the first argument to the memoized function as the key.

var fibonacci = _.memoize(function(n) {
  return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});

delay_.delay(function, wait, *arguments)
Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
=> 'logged later' // Appears after one second.

defer_.defer(function, *arguments)
Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

_.defer(function(){ alert('deferred'); });
// Returns from the function before the alert runs.

throttle_.throttle(function, wait, [options])
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

By default, throttle will execute the function as soon as you call it for the first time, and, if you call it again any number of times during the wait period, as soon as that period is over. If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable the execution on the trailing-edge, pass
{trailing: false}.

var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

debounce_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time.

var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);

once_.once(function)
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.

after_.after(count, function)
Creates a version of the function that will only be run after first being called count times. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

var renderNotes = _.after(notes.length, render);
_.each(notes, function(note) {
  note.asyncSave({success: renderNotes});
});
// renderNotes is run once, after all notes have saved.

before_.before(count, function)
Creates a version of the function that can be called no more than count times. The result of the last function call is memoized and returned when count has been reached.

var monthlyMeeting = _.before(3, askForRaise);
monthlyMeeting();
monthlyMeeting();
monthlyMeeting();
// the result of any subsequent calls is the same as the second call

wrap_.wrap(function, wrapper)
Wraps the first function inside of the wrapper function, passing it as the first argument. This allows the wrapper to execute code before and after the function runs, adjust the arguments, and execute it conditionally.

var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func) {
  return "before, " + func("moe") + ", after";
});
hello();
=> 'before, hello: moe, after'

negate_.negate(predicate)
Returns a new negated version of the predicate function.

var isFalsy = _.negate(Boolean);
_.find([-2, -1, 0, 1, 2], isFalsy);
=> 0

compose_.compose(*functions)
Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

var greet    = function(name){ return "hi: " + name; };
var exclaim  = function(statement){ return statement.toUpperCase() + "!"; };
var welcome = _.compose(greet, exclaim);
welcome('moe');
=> 'hi: MOE!'

Object Functions

keys_.keys(object)
Retrieve all the names of the object's properties.

_.keys({one: 1, two: 2, three: 3});
=> ["one", "two", "three"]

values_.values(object)
Return all of the values of the object's properties.

_.values({one: 1, two: 2, three: 3});
=> [1, 2, 3]

pairs_.pairs(object)
Convert an object into a list of [key, value] pairs.

_.pairs({one: 1, two: 2, three: 3});
=> [["one", 1], ["two", 2], ["three", 3]]

invert_.invert(object)
Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

_.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"});
=> {Moses: "Moe", Louis: "Larry", Jerome: "Curly"};

functions_.functions(object) Alias: methods
Returns a sorted list of the names of every method in an object — that is to say, the name of every function property of the object.

_.functions(_);
=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...

extend_.extend(destination, *sources)
Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments.

_.extend({name: 'moe'}, {age: 50});
=> {name: 'moe', age: 50}

pick_.pick(object, *keys)
Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {age: 50}

omit_.omit(object, *keys)
Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
=> {name: 'moe', age: 50}
_.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {name: 'moe', userid: 'moe1'}

defaults_.defaults(object, *defaults)
Fill in undefined properties in object with the first value present in the following list of defaults objects.

var iceCream = {flavor: "chocolate"};
_.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});
=> {flavor: "chocolate", sprinkles: "lots"}

clone_.clone(object)
Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

_.clone({name: 'moe'});
=> {name: 'moe'};

tap_.tap(object, interceptor)
Invokes interceptor with the object, and then returns object. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.

_.chain([1,2,3,200])
  .filter(function(num) { return num % 2 == 0; })
  .tap(alert)
  .map(function(num) { return num * num })
  .value();
=> // [2, 200] (alerted)
=> [4, 40000]

has_.has(object, key)
Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.

_.has({a: 1, b: 2, c: 3}, "b");
=> true

property_.property(key)
Returns a function that will itself return the key property of any passed-in object.

var moe = {name: 'moe'};
'moe' === _.property('name')(moe);
=> true

matches_.matches(attrs)
Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs.

var ready = _.matches({selected: true, visible: true});
var readyToGoList = _.filter(list, ready);

isEqual_.isEqual(object, other)
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

var moe   = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone = {name: 'moe', luckyNumbers: [13, 27, 34]};
moe == clone;
=> false
_.isEqual(moe, clone);
=> true

isEmpty_.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.

_.isEmpty([1, 2, 3]);
=> false
_.isEmpty({});
=> true

isElement_.isElement(object)
Returns true if object is a DOM element.

_.isElement(jQuery('body')[0]);
=> true

isArray_.isArray(object)
Returns true if object is an Array.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true

isObject_.isObject(value)
Returns true if value is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings and numbers are not.

_.isObject({});
=> true
_.isObject(1);
=> false

isArguments_.isArguments(object)
Returns true if object is an Arguments object.

(function(){ return _.isArguments(arguments); })(1, 2, 3);
=> true
_.isArguments([1,2,3]);
=> false

isFunction_.isFunction(object)
Returns true if object is a Function.

_.isFunction(alert);
=> true

isString_.isString(object)
Returns true if object is a String.

_.isString("moe");
=> true

isNumber_.isNumber(object)
Returns true if object is a Number (including NaN).

_.isNumber(8.4 * 5);
=> true

isFinite_.isFinite(object)
Returns true if object is a finite Number.

_.isFinite(-101);
=> true

_.isFinite(-Infinity);
=> false

isBoolean_.isBoolean(object)
Returns true if object is either true or false.

_.isBoolean(null);
=> false

isDate_.isDate(object)
Returns true if object is a Date.

_.isDate(new Date());
=> true

isRegExp_.isRegExp(object)
Returns true if object is a RegExp.

_.isRegExp(/moe/);
=> true

isNaN_.isNaN(object)
Returns true if object is NaN.
Note: this is not the same as the native isNaN function, which will also return true for many other not-number values, such as undefined.

_.isNaN(NaN);
=> true
isNaN(undefined);
=> true
_.isNaN(undefined);
=> false

isNull_.isNull(object)
Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false

isUndefined_.isUndefined(value)
Returns true if value is undefined.

_.isUndefined(window.missingVariable);
=> true

Utility Functions

noConflict_.noConflict()
Give control of the "_" variable back to its previous owner. Returns a reference to the Underscore object.

var underscore = _.noConflict();

identity_.identity(value)
Returns the same value that is used as the argument. In math: f(x) = x
This function looks useless, but is used throughout Underscore as a default iteratee.

var moe = {name: 'moe'};
moe === _.identity(moe);
=> true

constant_.constant(value)
Creates a function that returns the same value that is used as the argument of _.constant.

var moe = {name: 'moe'};
moe === _.constant(moe)();
=> true

noop_.noop()
Returns undefined irrespective of the arguments passed to it. Useful as the default for optional callback arguments.

times_.times(n, iteratee, [context])
Invokes the given iteratee function n times. Each invocation of iteratee is called with an index argument. Produces an array of the returned values.
Note: this example uses the chaining syntax.

_(3).times(function(n){ genie.grantWishNumber(n); });

random_.random(min, max)
Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number.

_.random(0, 100);
=> 42

mixin_.mixin(object)
Allows you to extend Underscore with your own utility functions. Pass a hash of {name: function} definitions to have your functions added to the Underscore object, as well as the OOP wrapper.

_.mixin({
  capitalize: function(string) {
    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  }
});
_("fabio").capitalize();
=> "Fabio"

iteratee_.iteratee(value, [context], [argCount])
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 stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
_.map(stooges, _.iteratee('age'));
=> [25, 21, 23];

uniqueId_.uniqueId([prefix])
Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.

_.uniqueId('contact_');
=> 'contact_104'

escape_.escape(string)
Escapes a string for insertion into HTML, replacing &, <, >, ", and ' characters.

_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"

unescape_.unescape(string)
The opposite of escape, replaces &amp;, &lt;, &gt;, &quot;, and &#x27; with their unescaped counterparts.

_.unescape('Curly, Larry &amp; Moe');
=> "Curly, Larry & Moe"

result_.result(object, property)
If the value of the named property is a function then invoke it with the object as context; otherwise, return it.

var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"

now_.now()
Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions.

_.now();
=> 1392066795351

template_.template(templateString, [settings])
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables. The settings argument should be a hash containing any _.templateSettings that should be overridden.

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

var template = _.template("<b><%- value %></b>");
template({value: '<script>'});
=> "<b>&lt;script&gt;</b>"

You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge"

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string. You may define or omit any combination of the three. For example, to perform Mustache.js style templating:

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name: "Mustache"});
=> "Hello Mustache!"

By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.

_.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'});
=> "Using 'with': no"

Precompiling your templates can be a big help when debugging errors you can't reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. The source property is available on the compiled template function for easy precompilation.

<script>
  JST.project = <%= _.template(jstText).source %>;
</script>

Chaining

You can use Underscore in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers.

_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });

Calling chain will cause all future method calls to return wrapped objects. When you've finished the computation, call value to retrieve the final value. Here's an example of chaining together a map/flatten/reduce, in order to get the word count of every word in a song.

var lyrics = [
  {line: 1, words: "I'm a lumberjack and I'm okay"},
  {line: 2, words: "I sleep all night and I work all day"},
  {line: 3, words: "He's a lumberjack and he's okay"},
  {line: 4, words: "He sleeps all night and he works all day"}
];

_.chain(lyrics)
  .map(function(line) { return line.words.split(' '); })
  .flatten()
  .reduce(function(counts, word) {
    counts[word] = (counts[word] || 0) + 1;
    return counts;
  }, {})
  .value();

=> {lumberjack: 2, all: 4, night: 2 ... }

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

chain_.chain(obj)
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
var youngest = _.chain(stooges)
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  .first()
  .value();
=> "moe is 21"

value_(obj).value()
Extracts the value of a wrapped object.

_([1, 2, 3]).value();
=> [1, 2, 3]

The Underscore documentation is also available in Simplified Chinese.

Underscore.lua, a Lua port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Underscore.m, an Objective-C port of many of the Underscore.js functions, using a syntax that encourages chaining. (source)

_.m, an alternative Objective-C port that tries to stick a little closer to the original Underscore.js API. (source)

Underscore.php, a PHP port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Underscore-perl, a Perl port of many of the Underscore.js functions, aimed at on Perl hashes and arrays. (source)

Underscore.cfc, a Coldfusion port of many of the Underscore.js functions. (source)

Underscore.string, an Underscore extension that adds functions for string-manipulation: trim, startsWith, contains, capitalize, reverse, sprintf, and more.

Ruby's Enumerable module.

Prototype.js, which provides JavaScript with collection functions in the manner closest to Ruby's Enumerable.

Oliver Steele's Functional JavaScript, which includes comprehensive higher-order function support as well as string lambdas.

Michael Aufreiter's Data.js, a data manipulation + persistence library for JavaScript.

Python's itertools.

PyToolz, a Python port that extends itertools and functools to include much of the Underscore API.

Funcy, a practical collection of functional helpers for Python, partially inspired by Underscore.

Change Log

1.7.0August 26, 2014DiffDocs

  • For consistency and speed across browsers, Underscore now ignores native array methods for forEach, map, reduce, reduceRight, filter, every, some, indexOf, and lastIndexOf. "Sparse" arrays are officially dead in Underscore.
  • Added _.iteratee to customize the iterators used by collection functions. Many Underscore methods will take a string argument for easier _.property-style lookups, an object for _.where-style filtering, or a function as a custom callback.
  • Added _.before as a counterpart to _.after.
  • Added _.negate to invert the truth value of the passed-in predicate.
  • Added _.noop as a handy empty placeholder function.
  • _.isEmpty now works with arguments objects.
  • _.has now guards against nullish objects.
  • Override base methods like each and some and they'll be used internally by other Underscore functions too.
  • The escape functions handle backticks (`), to deal with an IE ≤ 8 bug.
  • _.memoize exposes the cache of memoized values as a property on the returned function.
  • _.pick accepts `iteratee` and `context` arguments for a more advanced callback.
  • Underscore templates no longer accept an initial data object. _.template always returns a function now.
  • Optimizations and code cleanup aplenty.

1.6.0February 10, 2014DiffDocs

  • Underscore now registers itself for AMD (Require.js), Bower and Component, as well as being a CommonJS module and a regular (Java)Script. An ugliness, but perhaps a necessary one.
  • Added _.partition, a way to split a collection into two lists of results — those that pass and those that fail a particular predicate.
  • Added _.property, for easy creation of iterators that pull specific properties from objects. Useful in conjunction with other Underscore collection functions.
  • Added _.matches, a function that will give you a predicate that can be used to tell if a given object matches a list of specified key/value properties.
  • Added _.constant, as a higher-order _.identity.
  • Added _.now, an optimized way to get a timestamp — used internally to speed up debounce and throttle.
  • The _.partial function may now be used to partially apply any of its arguments, by passing _ wherever you'd like a placeholder variable, to be filled-in later.
  • The _.each function now returns a reference to the list for chaining.
  • The _.keys function now returns an empty array for non-objects instead of throwing.
  • … and more miscellaneous refactoring.

1.5.2September 7, 2013DiffDocs

  • Added an indexBy function, which fits in alongside its cousins, countBy and groupBy.
  • Added a sample function, for sampling random elements from arrays.
  • Some optimizations relating to functions that can be implemented in terms of _.keys (which includes, significantly, each on objects). Also for debounce in a tight loop.

1.5.1July 8, 2013DiffDocs

  • Removed unzip, as it's simply the application of zip to an array of arguments. Use _.zip.apply(_, list) to transpose instead.

1.5.0July 6, 2013DiffDocs

  • Added a new unzip function, as the inverse of _.zip.
  • The throttle function now takes an options argument, allowing you to disable execution of the throttled function on either the leading or trailing edge.
  • A source map is now supplied for easier debugging of the minified production build of Underscore.
  • The defaults function now only overrides undefined values, not null ones.
  • Removed the ability to call _.bindAll with no method name arguments. It's pretty much always wiser to white-list the names of the methods you'd like to bind.
  • Removed the ability to call _.after with an invocation count of zero. The minimum number of calls is (naturally) now 1.

1.4.4January 30, 2013DiffDocs

  • Added _.findWhere, for finding the first element in a list that matches a particular set of keys and values.
  • Added _.partial, for partially applying a function without changing its dynamic reference to this.
  • Simplified bind by removing some edge cases involving constructor functions. In short: don't _.bind your constructors.
  • A minor optimization to invoke.
  • Fix bug in the minified version due to the minifier incorrectly optimizing-away isFunction.

1.4.3December 4, 2012DiffDocs

  • Improved Underscore compatibility with Adobe's JS engine that can be used to script Illustrator, Photoshop, and friends.
  • Added a default _.identity iterator to countBy and groupBy.
  • The uniq function can now take array, iterator, context as the argument list.
  • The times function now returns the mapped array of iterator results.
  • Simplified and fixed bugs in throttle.

1.4.2October 6, 2012DiffDocs

  • For backwards compatibility, returned to pre-1.4.0 behavior when passing null to iteration functions. They now become no-ops again.

1.4.1October 1, 2012DiffDocs

  • Fixed a 1.4.0 regression in the lastIndexOf function.

1.4.0September 27, 2012DiffDocs

  • Added a pairs function, for turning a JavaScript object into [key, value] pairs ... as well as an object function, for converting an array of [key, value] pairs into an object.
  • Added a countBy function, for counting the number of objects in a list that match a certain criteria.
  • Added an invert function, for performing a simple inversion of the keys and values in an object.
  • Added a where function, for easy cases of filtering a list for objects with specific values.
  • Added an omit function, for filtering an object to remove certain keys.
  • Added a random function, to return a random number in a given range.
  • _.debounce'd functions now return their last updated value, just like _.throttle'd functions do.
  • The sortBy function now runs a stable sort algorithm.
  • Added the optional fromIndex option to indexOf and lastIndexOf.
  • "Sparse" arrays are no longer supported in Underscore iteration functions. Use a for loop instead (or better yet, an object).
  • The min and max functions may now be called on very large arrays.
  • Interpolation in templates now represents null and undefined as the empty string.
  • Underscore iteration functions no longer accept null values as a no-op argument. You'll get an early error instead.
  • A number of edge-cases fixes and tweaks, which you can spot in the diff. Depending on how you're using Underscore, 1.4.0 may be more backwards-incompatible than usual — please test when you upgrade.

1.3.3April 10, 2012DiffDocs

  • Many improvements to _.template, which now provides the source of the template function as a property, for potentially even more efficient pre-compilation on the server-side. You may now also set the variable option when creating a template, which will cause your passed-in data to be made available under the variable you named, instead of using a with statement — significantly improving the speed of rendering the template.
  • Added the pick function, which allows you to filter an object literal with a whitelist of allowed property names.
  • Added the result function, for convenience when working with APIs that allow either functions or raw properties.
  • Added the isFinite function, because sometimes knowing that a value is a number just ain't quite enough.
  • The sortBy function may now also be passed the string name of a property to use as the sort order on each object.
  • Fixed uniq to work with sparse arrays.
  • The difference function now performs a shallow flatten instead of a deep one when computing array differences.
  • The debounce function now takes an immediate parameter, which will cause the callback to fire on the leading instead of the trailing edge.

1.3.1January 23, 2012DiffDocs

  • Added an _.has function, as a safer way to use hasOwnProperty.
  • Added _.collect as an alias for _.map. Smalltalkers, rejoice.
  • Reverted an old change so that _.extend will correctly copy over keys with undefined values again.
  • Bugfix to stop escaping slashes within interpolations in _.template.

1.3.0January 11, 2012DiffDocs

  • Removed AMD (RequireJS) support from Underscore. If you'd like to use Underscore with RequireJS, you can load it as a normal script, wrap or patch your copy, or download a forked version.

1.2.4January 4, 2012DiffDocs

  • You now can (and probably should, as it's simpler) write _.chain(list) instead of _(list).chain().
  • Fix for escaped characters in Underscore templates, and for supporting customizations of _.templateSettings that only define one or two of the required regexes.
  • Fix for passing an array as the first argument to an _.wrap'd function.
  • Improved compatibility with ClojureScript, which adds a call function to String.prototype.

1.2.3December 7, 2011DiffDocs

  • Dynamic scope is now preserved for compiled _.template functions, so you can use the value of this if you like.
  • Sparse array support of _.indexOf, _.lastIndexOf.
  • Both _.reduce and _.reduceRight can now be passed an explicitly undefined value. (There's no reason why you'd want to do this.)

1.2.2November 14, 2011DiffDocs

  • Continued tweaks to _.isEqual semantics. Now JS primitives are considered equivalent to their wrapped versions, and arrays are compared by their numeric properties only (#351).
  • _.escape no longer tries to be smart about not double-escaping already-escaped HTML entities. Now it just escapes regardless (#350).
  • In _.template, you may now leave semicolons out of evaluated statements if you wish: <% }) %> (#369).
  • _.after(callback, 0) will now trigger the callback immediately, making "after" easier to use with asynchronous APIs (#366).

1.2.1October 24, 2011DiffDocs

  • Several important bug fixes for _.isEqual, which should now do better on mutated Arrays, and on non-Array objects with length properties. (#329)
  • James Burke contributed Underscore exporting for AMD module loaders, and Tony Lukasavage for Appcelerator Titanium. (#335, #338)
  • You can now _.groupBy(list, 'property') as a shortcut for grouping values by a particular common property.
  • _.throttle'd functions now fire immediately upon invocation, and are rate-limited thereafter (#170, #266).
  • Most of the _.is[Type] checks no longer ducktype.
  • The _.bind function now also works on constructors, a-la ES5 ... but you would never want to use _.bind on a constructor function.
  • _.clone no longer wraps non-object types in Objects.
  • _.find and _.filter are now the preferred names for _.detect and _.select.

1.2.0October 5, 2011DiffDocs

  • The _.isEqual function now supports true deep equality comparisons, with checks for cyclic structures, thanks to Kit Cambridge.
  • Underscore templates now support HTML escaping interpolations, using <%- ... %> syntax.
  • Ryan Tenney contributed _.shuffle, which uses a modified Fisher-Yates to give you a shuffled copy of an array.
  • _.uniq can now be passed an optional iterator, to determine by what criteria an object should be considered unique.
  • _.last now takes an optional argument which will return the last N elements of the list.
  • A new _.initial function was added, as a mirror of _.rest, which returns all the initial values of a list (except the last N).

1.1.7July 13, 2011DiffDocs
Added _.groupBy, which aggregates a collection into groups of like items. Added _.union and _.difference, to complement the (re-named) _.intersection. Various improvements for support of sparse arrays. _.toArray now returns a clone, if directly passed an array. _.functions now also returns the names of functions that are present in the prototype chain.

1.1.6April 18, 2011DiffDocs
Added _.after, which will return a function that only runs after first being called a specified number of times. _.invoke can now take a direct function reference. _.every now requires an iterator function to be passed, which mirrors the ECMA5 API. _.extend no longer copies keys when the value is undefined. _.bind now errors when trying to bind an undefined value.

1.1.5March 20, 2011DiffDocs
Added an _.defaults function, for use merging together JS objects representing default options. Added an _.once function, for manufacturing functions that should only ever execute a single time. _.bind now delegates to the native ECMAScript 5 version, where available. _.keys now throws an error when used on non-Object values, as in ECMAScript 5. Fixed a bug with _.keys when used over sparse arrays.

1.1.4January 9, 2011DiffDocs
Improved compliance with ES5's Array methods when passing null as a value. _.wrap now correctly sets this for the wrapped function. _.indexOf now takes an optional flag for finding the insertion index in an array that is guaranteed to already be sorted. Avoiding the use of .callee, to allow _.isArray to work properly in ES5's strict mode.

1.1.3December 1, 2010DiffDocs
In CommonJS, Underscore may now be required with just:
var _ = require("underscore"). Added _.throttle and _.debounce functions. Removed _.breakLoop, in favor of an ECMA5-style un-break-able each implementation — this removes the try/catch, and you'll now have better stack traces for exceptions that are thrown within an Underscore iterator. Improved the isType family of functions for better interoperability with Internet Explorer host objects. _.template now correctly escapes backslashes in templates. Improved _.reduce compatibility with the ECMA5 version: if you don't pass an initial value, the first item in the collection is used. _.each no longer returns the iterated collection, for improved consistency with ES5's forEach.

1.1.2October 15, 2010DiffDocs
Fixed _.contains, which was mistakenly pointing at _.intersect instead of _.include, like it should have been. Added _.unique as an alias for _.uniq.

1.1.1October 5, 2010DiffDocs
Improved the speed of _.template, and its handling of multiline interpolations. Ryan Tenney contributed optimizations to many Underscore functions. An annotated version of the source code is now available.

1.1.0August 18, 2010DiffDocs
The method signature of _.reduce has been changed to match the ECMAScript 5 signature, instead of the Ruby/Prototype.js version. This is a backwards-incompatible change. _.template may now be called with no arguments, and preserves whitespace. _.contains is a new alias for _.include.

1.0.4June 22, 2010DiffDocs
Andri Möll contributed the _.memoize function, which can be used to speed up expensive repeated computations by caching the results.

1.0.3June 14, 2010DiffDocs
Patch that makes _.isEqual return false if any property of the compared object has a NaN value. Technically the correct thing to do, but of questionable semantics. Watch out for NaN comparisons.

1.0.2March 23, 2010DiffDocs
Fixes _.isArguments in recent versions of Opera, which have arguments objects as real Arrays.

1.0.1March 19, 2010DiffDocs
Bugfix for _.isEqual, when comparing two objects with the same number of undefined keys, but with different names.

1.0.0March 18, 2010DiffDocs
Things have been stable for many months now, so Underscore is now considered to be out of beta, at 1.0. Improvements since 0.6 include _.isBoolean, and the ability to have _.extend take multiple source objects.

0.6.0February 24, 2010DiffDocs
Major release. Incorporates a number of Mile Frawley's refactors for safer duck-typing on collection functions, and cleaner internals. A new _.mixin method that allows you to extend Underscore with utility functions of your own. Added _.times, which works the same as in Ruby or Prototype.js. Native support for ECMAScript 5's Array.isArray, and Object.keys.

0.5.8January 28, 2010DiffDocs
Fixed Underscore's collection functions to work on NodeLists and HTMLCollections once more, thanks to Justin Tulloss.

0.5.7January 20, 2010DiffDocs
A safer implementation of _.isArguments, and a faster _.isNumber,
thanks to Jed Schmidt.

0.5.6January 18, 2010DiffDocs
Customizable delimiters for _.template, contributed by Noah Sloan.

0.5.5January 9, 2010DiffDocs
Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.

0.5.4January 5, 2010DiffDocs
Fix for multiple single quotes within a template string for _.template. See: Rick Strahl's blog post.

0.5.2January 1, 2010DiffDocs
New implementations of isArray, isDate, isFunction, isNumber, isRegExp, and isString, thanks to a suggestion from Robert Kieffer. Instead of doing Object#toString comparisons, they now check for expected properties, which is less safe, but more than an order of magnitude faster. Most other Underscore functions saw minor speed improvements as a result. Evgeniy Dolzhenko contributed _.tap, similar to Ruby 1.9's, which is handy for injecting side effects (like logging) into chained calls.

0.5.1December 9, 2009DiffDocs
Added an _.isArguments function. Lots of little safety checks and optimizations contributed by Noah Sloan and Andri Möll.

0.5.0December 7, 2009DiffDocs
[API Changes] _.bindAll now takes the context object as its first parameter. If no method names are passed, all of the context object's methods are bound to it, enabling chaining and easier binding. _.functions now takes a single argument and returns the names of its Function properties. Calling _.functions(_) will get you the previous behavior. Added _.isRegExp so that isEqual can now test for RegExp equality. All of the "is" functions have been shrunk down into a single definition. Karl Guertin contributed patches.

0.4.7December 6, 2009DiffDocs
Added isDate, isNaN, and isNull, for completeness. Optimizations for isEqual when checking equality between Arrays or Dates. _.keys is now 25%–2X faster (depending on your browser) which speeds up the functions that rely on it, such as _.each.

0.4.6November 30, 2009DiffDocs
Added the range function, a port of the Python function of the same name, for generating flexibly-numbered lists of integers. Original patch contributed by Kirill Ishanov.

0.4.5November 19, 2009DiffDocs
Added rest for Arrays and arguments objects, and aliased first as head, and rest as tail, thanks to Luke Sutton's patches. Added tests ensuring that all Underscore Array functions also work on arguments objects.

0.4.4November 18, 2009DiffDocs
Added isString, and isNumber, for consistency. Fixed _.isEqual(NaN, NaN) to return true (which is debatable).

0.4.3November 9, 2009DiffDocs
Started using the native StopIteration object in browsers that support it. Fixed Underscore setup for CommonJS environments.

0.4.2November 9, 2009DiffDocs
Renamed the unwrapping function to value, for clarity.

0.4.1November 8, 2009DiffDocs
Chained Underscore objects now support the Array prototype methods, so that you can perform the full range of operations on a wrapped array without having to break your chain. Added a breakLoop method to break in the middle of any Underscore iteration. Added an isEmpty function that works on arrays and objects.

0.4.0November 7, 2009DiffDocs
All Underscore functions can now be called in an object-oriented style, like so: _([1, 2, 3]).map(...);. Original patch provided by Marc-André Cournoyer. Wrapped objects can be chained through multiple method invocations. A functions method was added, providing a sorted list of all the functions in Underscore.

0.3.3October 31, 2009DiffDocs
Added the JavaScript 1.8 function reduceRight. Aliased it as foldr, and aliased reduce as foldl.

0.3.2October 29, 2009DiffDocs
Now runs on stock Rhino interpreters with: load("underscore.js"). Added identity as a utility function.

0.3.1October 29, 2009DiffDocs
All iterators are now passed in the original collection as their third argument, the same as JavaScript 1.6's forEach. Iterating over objects is now called with (value, key, collection), for details see _.each.

0.3.0October 29, 2009DiffDocs
Added Dmitry Baranovskiy's comprehensive optimizations, merged in Kris Kowal's patches to make Underscore CommonJS and Narwhal compliant.

0.2.0October 28, 2009DiffDocs
Added compose and lastIndexOf, renamed inject to reduce, added aliases for inject, filter, every, some, and forEach.

0.1.1October 28, 2009DiffDocs
Added noConflict, so that the "Underscore" object can be assigned to other variables.

0.1.0October 28, 2009Docs
Initial release of Underscore.js.

A DocumentCloud Project

1.7.0~dfsg/LICENSE0000644000000000000000000000213512377203462012275 0ustar rootrootCopyright (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 1.7.0~dfsg/bower.json0000644000000000000000000000036212377203462013301 0ustar rootroot{ "name": "underscore", "version": "1.7.0", "main": "underscore.js", "keywords": ["util", "functional", "server", "client", "browser"], "ignore" : ["docs", "test", "*.yml", "CNAME", "index.html", "favicon.ico", "CONTRIBUTING.md"] } 1.7.0~dfsg/component.json0000644000000000000000000000055312377203462014167 0ustar rootroot{ "name" : "underscore", "description" : "JavaScript's functional programming helper library.", "keywords" : ["util", "functional", "server", "client", "browser"], "repo" : "jashkenas/underscore", "main" : "underscore.js", "scripts" : ["underscore.js"], "version" : "1.7.0", "license" : "MIT" } 1.7.0~dfsg/README.md0000644000000000000000000000231112377203462012543 0ustar rootroot __ /\ \ __ __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____ /\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\ \ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\ \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/ \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/ \ \____/ \/___/ Underscore.js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects. For Docs, License, Tests, and pre-packed downloads, see: http://underscorejs.org Underscore is an open-sourced component of DocumentCloud: https://github.com/documentcloud Many thanks to our contributors: https://github.com/jashkenas/underscore/contributors 1.7.0~dfsg/test/0000755000000000000000000000000012377203462012246 5ustar rootroot1.7.0~dfsg/test/objects.js0000644000000000000000000010025712377203462014242 0ustar rootroot(function() { module('Objects'); /* global iObject, iElement, iArguments, iFunction, iArray, iString, iNumber, iBoolean, iDate, iRegExp, iNaN, iNull, iUndefined, ActiveXObject */ test('keys', function() { deepEqual(_.keys({one : 1, two : 2}), ['one', 'two'], 'can extract the keys from an object'); // the test above is not safe because it relies on for-in enumeration order var a = []; a[1] = 0; deepEqual(_.keys(a), ['1'], 'is not fooled by sparse arrays; see issue #95'); deepEqual(_.keys(null), []); deepEqual(_.keys(void 0), []); deepEqual(_.keys(1), []); deepEqual(_.keys('a'), []); deepEqual(_.keys(true), []); }); test('values', function() { deepEqual(_.values({one: 1, two: 2}), [1, 2], 'can extract the values from an object'); deepEqual(_.values({one: 1, two: 2, length: 3}), [1, 2, 3], '... even when one of them is "length"'); }); test('pairs', function() { deepEqual(_.pairs({one: 1, two: 2}), [['one', 1], ['two', 2]], 'can convert an object into pairs'); deepEqual(_.pairs({one: 1, two: 2, length: 3}), [['one', 1], ['two', 2], ['length', 3]], '... even when one of them is "length"'); }); test('invert', function() { var obj = {first: 'Moe', second: 'Larry', third: 'Curly'}; deepEqual(_.keys(_.invert(obj)), ['Moe', 'Larry', 'Curly'], 'can invert an object'); deepEqual(_.invert(_.invert(obj)), obj, 'two inverts gets you back where you started'); obj = {length: 3}; equal(_.invert(obj)['3'], 'length', 'can invert an object with "length"'); }); test('functions', function() { var obj = {a : 'dash', b : _.map, c : /yo/, d : _.reduce}; deepEqual(['b', 'd'], _.functions(obj), 'can grab the function names of any passed-in object'); var Animal = function(){}; Animal.prototype.run = function(){}; deepEqual(_.functions(new Animal), ['run'], 'also looks up functions on the prototype'); }); test('methods', function() { strictEqual(_.functions, _.methods, 'alias for functions'); }); test('extend', function() { var result; equal(_.extend({}, {a: 'b'}).a, 'b', 'can extend an object with the attributes of another'); equal(_.extend({a: 'x'}, {a: 'b'}).a, 'b', 'properties in source override destination'); equal(_.extend({x: 'x'}, {a: 'b'}).x, 'x', "properties not in source don't get overriden"); result = _.extend({x: 'x'}, {a: 'a'}, {b: 'b'}); deepEqual(result, {x: 'x', a: 'a', b: 'b'}, 'can extend from multiple source objects'); result = _.extend({x: 'x'}, {a: 'a', x: 2}, {a: 'b'}); deepEqual(result, {x: 2, a: 'b'}, 'extending from multiple source objects last property trumps'); result = _.extend({}, {a: void 0, b: null}); deepEqual(_.keys(result), ['a', 'b'], 'extend copies undefined values'); var F = function() {}; F.prototype = {a: 'b'}; var subObj = new F(); subObj.c = 'd'; deepEqual(_.extend({}, subObj), {c: 'd'}, 'extend ignores any properties but own from source'); try { result = {}; _.extend(result, null, undefined, {a: 1}); } catch(ex) {} equal(result.a, 1, 'should not error on `null` or `undefined` sources'); strictEqual(_.extend(null, {a: 1}), null, 'extending null results in null'); strictEqual(_.extend(undefined, {a: 1}), undefined, 'extending undefined results in undefined'); }); test('pick', function() { var result; result = _.pick({a: 1, b: 2, c: 3}, 'a', 'c'); deepEqual(result, {a: 1, c: 3}, 'can restrict properties to those named'); result = _.pick({a: 1, b: 2, c: 3}, ['b', 'c']); deepEqual(result, {b: 2, c: 3}, 'can restrict properties to those named in an array'); result = _.pick({a: 1, b: 2, c: 3}, ['a'], 'b'); deepEqual(result, {a: 1, b: 2}, 'can restrict properties to those named in mixed args'); result = _.pick(['a', 'b'], 1); deepEqual(result, {1: 'b'}, 'can pick numeric properties'); deepEqual(_.pick(null, 'a', 'b'), {}, 'non objects return empty object'); deepEqual(_.pick(undefined, 'toString'), {}, 'null/undefined return empty object'); deepEqual(_.pick(5, 'toString', 'b'), {toString: Number.prototype.toString}, 'can iterate primitives'); var data = {a: 1, b: 2, c: 3}; var callback = function(value, key, object) { strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]); strictEqual(object, data); return value !== this.value; }; result = _.pick(data, callback, {value: 2}); deepEqual(result, {a: 1, c: 3}, 'can accept a predicate and context'); var Obj = function(){}; Obj.prototype = {a: 1, b: 2, c: 3}; var instance = new Obj(); deepEqual(_.pick(instance, 'a', 'c'), {a: 1, c: 3}, 'include prototype props'); deepEqual(_.pick(data, function(val, key) { return this[key] === 3 && this === instance; }, instance), {c: 3}, 'function is given context'); }); test('omit', function() { var result; result = _.omit({a: 1, b: 2, c: 3}, 'b'); deepEqual(result, {a: 1, c: 3}, 'can omit a single named property'); result = _.omit({a: 1, b: 2, c: 3}, 'a', 'c'); deepEqual(result, {b: 2}, 'can omit several named properties'); result = _.omit({a: 1, b: 2, c: 3}, ['b', 'c']); deepEqual(result, {a: 1}, 'can omit properties named in an array'); result = _.omit(['a', 'b'], 0); deepEqual(result, {1: 'b'}, 'can omit numeric properties'); deepEqual(_.omit(null, 'a', 'b'), {}, 'non objects return empty object'); deepEqual(_.omit(undefined, 'toString'), {}, 'null/undefined return empty object'); deepEqual(_.omit(5, 'toString', 'b'), {}, 'returns empty object for primitives'); var data = {a: 1, b: 2, c: 3}; var callback = function(value, key, object) { strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]); strictEqual(object, data); return value !== this.value; }; result = _.omit(data, callback, {value: 2}); deepEqual(result, {b: 2}, 'can accept a predicate'); var Obj = function(){}; Obj.prototype = {a: 1, b: 2, c: 3}; var instance = new Obj(); deepEqual(_.omit(instance, 'b'), {a: 1, c: 3}, 'include prototype props'); deepEqual(_.omit(data, function(val, key) { return this[key] === 3 && this === instance; }, instance), {a: 1, b: 2}, 'function is given context'); }); test('defaults', function() { var options = {zero: 0, one: 1, empty: '', nan: NaN, nothing: null}; _.defaults(options, {zero: 1, one: 10, twenty: 20, nothing: 'str'}); equal(options.zero, 0, 'value exists'); equal(options.one, 1, 'value exists'); equal(options.twenty, 20, 'default applied'); equal(options.nothing, null, "null isn't overridden"); _.defaults(options, {empty: 'full'}, {nan: 'nan'}, {word: 'word'}, {word: 'dog'}); equal(options.empty, '', 'value exists'); ok(_.isNaN(options.nan), "NaN isn't overridden"); equal(options.word, 'word', 'new value is added, first one wins'); try { options = {}; _.defaults(options, null, undefined, {a: 1}); } catch(ex) {} equal(options.a, 1, 'should not error on `null` or `undefined` sources'); strictEqual(_.defaults(null, {a: 1}), null, 'result is null if destination is null'); strictEqual(_.defaults(undefined, {a: 1}), undefined, 'result is undefined if destination is undefined'); }); test('clone', function() { var moe = {name : 'moe', lucky : [13, 27, 34]}; var clone = _.clone(moe); equal(clone.name, 'moe', 'the clone as the attributes of the original'); clone.name = 'curly'; ok(clone.name === 'curly' && moe.name === 'moe', 'clones can change shallow attributes without affecting the original'); clone.lucky.push(101); equal(_.last(moe.lucky), 101, 'changes to deep attributes are shared with the original'); equal(_.clone(undefined), void 0, 'non objects should not be changed by clone'); equal(_.clone(1), 1, 'non objects should not be changed by clone'); equal(_.clone(null), null, 'non objects should not be changed by clone'); }); test('isEqual', function() { function First() { this.value = 1; } First.prototype.value = 1; function Second() { this.value = 1; } Second.prototype.value = 2; // Basic equality and identity comparisons. ok(_.isEqual(null, null), '`null` is equal to `null`'); ok(_.isEqual(), '`undefined` is equal to `undefined`'); ok(!_.isEqual(0, -0), '`0` is not equal to `-0`'); ok(!_.isEqual(-0, 0), 'Commutative equality is implemented for `0` and `-0`'); ok(!_.isEqual(null, undefined), '`null` is not equal to `undefined`'); ok(!_.isEqual(undefined, null), 'Commutative equality is implemented for `null` and `undefined`'); // String object and primitive comparisons. ok(_.isEqual('Curly', 'Curly'), 'Identical string primitives are equal'); ok(_.isEqual(new String('Curly'), new String('Curly')), 'String objects with identical primitive values are equal'); ok(_.isEqual(new String('Curly'), 'Curly'), 'String primitives and their corresponding object wrappers are equal'); ok(_.isEqual('Curly', new String('Curly')), 'Commutative equality is implemented for string objects and primitives'); ok(!_.isEqual('Curly', 'Larry'), 'String primitives with different values are not equal'); ok(!_.isEqual(new String('Curly'), new String('Larry')), 'String objects with different primitive values are not equal'); ok(!_.isEqual(new String('Curly'), {toString: function(){ return 'Curly'; }}), 'String objects and objects with a custom `toString` method are not equal'); // Number object and primitive comparisons. ok(_.isEqual(75, 75), 'Identical number primitives are equal'); ok(_.isEqual(new Number(75), new Number(75)), 'Number objects with identical primitive values are equal'); ok(_.isEqual(75, new Number(75)), 'Number primitives and their corresponding object wrappers are equal'); ok(_.isEqual(new Number(75), 75), 'Commutative equality is implemented for number objects and primitives'); ok(!_.isEqual(new Number(0), -0), '`new Number(0)` and `-0` are not equal'); ok(!_.isEqual(0, new Number(-0)), 'Commutative equality is implemented for `new Number(0)` and `-0`'); ok(!_.isEqual(new Number(75), new Number(63)), 'Number objects with different primitive values are not equal'); ok(!_.isEqual(new Number(63), {valueOf: function(){ return 63; }}), 'Number objects and objects with a `valueOf` method are not equal'); // Comparisons involving `NaN`. ok(_.isEqual(NaN, NaN), '`NaN` is equal to `NaN`'); ok(_.isEqual(new Object(NaN), NaN), 'Object(`NaN`) is equal to `NaN`'); ok(!_.isEqual(61, NaN), 'A number primitive is not equal to `NaN`'); ok(!_.isEqual(new Number(79), NaN), 'A number object is not equal to `NaN`'); ok(!_.isEqual(Infinity, NaN), '`Infinity` is not equal to `NaN`'); // Boolean object and primitive comparisons. ok(_.isEqual(true, true), 'Identical boolean primitives are equal'); ok(_.isEqual(new Boolean, new Boolean), 'Boolean objects with identical primitive values are equal'); ok(_.isEqual(true, new Boolean(true)), 'Boolean primitives and their corresponding object wrappers are equal'); ok(_.isEqual(new Boolean(true), true), 'Commutative equality is implemented for booleans'); ok(!_.isEqual(new Boolean(true), new Boolean), 'Boolean objects with different primitive values are not equal'); // Common type coercions. ok(!_.isEqual(new Boolean(false), true), '`new Boolean(false)` is not equal to `true`'); ok(!_.isEqual('75', 75), 'String and number primitives with like values are not equal'); ok(!_.isEqual(new Number(63), new String(63)), 'String and number objects with like values are not equal'); ok(!_.isEqual(75, '75'), 'Commutative equality is implemented for like string and number values'); ok(!_.isEqual(0, ''), 'Number and string primitives with like values are not equal'); ok(!_.isEqual(1, true), 'Number and boolean primitives with like values are not equal'); ok(!_.isEqual(new Boolean(false), new Number(0)), 'Boolean and number objects with like values are not equal'); ok(!_.isEqual(false, new String('')), 'Boolean primitives and string objects with like values are not equal'); ok(!_.isEqual(12564504e5, new Date(2009, 9, 25)), 'Dates and their corresponding numeric primitive values are not equal'); // Dates. ok(_.isEqual(new Date(2009, 9, 25), new Date(2009, 9, 25)), 'Date objects referencing identical times are equal'); ok(!_.isEqual(new Date(2009, 9, 25), new Date(2009, 11, 13)), 'Date objects referencing different times are not equal'); ok(!_.isEqual(new Date(2009, 11, 13), { getTime: function(){ return 12606876e5; } }), 'Date objects and objects with a `getTime` method are not equal'); ok(!_.isEqual(new Date('Curly'), new Date('Curly')), 'Invalid dates are not equal'); // Functions. ok(!_.isEqual(First, Second), 'Different functions with identical bodies and source code representations are not equal'); // RegExps. ok(_.isEqual(/(?:)/gim, /(?:)/gim), 'RegExps with equivalent patterns and flags are equal'); ok(_.isEqual(/(?:)/gi, /(?:)/ig), 'Flag order is not significant'); ok(!_.isEqual(/(?:)/g, /(?:)/gi), 'RegExps with equivalent patterns and different flags are not equal'); ok(!_.isEqual(/Moe/gim, /Curly/gim), 'RegExps with different patterns and equivalent flags are not equal'); ok(!_.isEqual(/(?:)/gi, /(?:)/g), 'Commutative equality is implemented for RegExps'); ok(!_.isEqual(/Curly/g, {source: 'Larry', global: true, ignoreCase: false, multiline: false}), 'RegExps and RegExp-like objects are not equal'); // Empty arrays, array-like objects, and object literals. ok(_.isEqual({}, {}), 'Empty object literals are equal'); ok(_.isEqual([], []), 'Empty array literals are equal'); ok(_.isEqual([{}], [{}]), 'Empty nested arrays and objects are equal'); ok(!_.isEqual({length: 0}, []), 'Array-like objects and arrays are not equal.'); ok(!_.isEqual([], {length: 0}), 'Commutative equality is implemented for array-like objects'); ok(!_.isEqual({}, []), 'Object literals and array literals are not equal'); ok(!_.isEqual([], {}), 'Commutative equality is implemented for objects and arrays'); // Arrays with primitive and object values. ok(_.isEqual([1, 'Larry', true], [1, 'Larry', true]), 'Arrays containing identical primitives are equal'); ok(_.isEqual([/Moe/g, new Date(2009, 9, 25)], [/Moe/g, new Date(2009, 9, 25)]), 'Arrays containing equivalent elements are equal'); // Multi-dimensional arrays. var a = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}]; var b = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}]; ok(_.isEqual(a, b), 'Arrays containing nested arrays and objects are recursively compared'); // Overwrite the methods defined in ES 5.1 section 15.4.4. a.forEach = a.map = a.filter = a.every = a.indexOf = a.lastIndexOf = a.some = a.reduce = a.reduceRight = null; b.join = b.pop = b.reverse = b.shift = b.slice = b.splice = b.concat = b.sort = b.unshift = null; // Array elements and properties. ok(_.isEqual(a, b), 'Arrays containing equivalent elements and different non-numeric properties are equal'); a.push('White Rocks'); ok(!_.isEqual(a, b), 'Arrays of different lengths are not equal'); a.push('East Boulder'); b.push('Gunbarrel Ranch', 'Teller Farm'); ok(!_.isEqual(a, b), 'Arrays of identical lengths containing different elements are not equal'); // Sparse arrays. ok(_.isEqual(Array(3), Array(3)), 'Sparse arrays of identical lengths are equal'); ok(!_.isEqual(Array(3), Array(6)), 'Sparse arrays of different lengths are not equal when both are empty'); var sparse = []; sparse[1] = 5; ok(_.isEqual(sparse, [undefined, 5]), 'Handles sparse arrays as dense'); // Simple objects. ok(_.isEqual({a: 'Curly', b: 1, c: true}, {a: 'Curly', b: 1, c: true}), 'Objects containing identical primitives are equal'); ok(_.isEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), 'Objects containing equivalent members are equal'); ok(!_.isEqual({a: 63, b: 75}, {a: 61, b: 55}), 'Objects of identical sizes with different values are not equal'); ok(!_.isEqual({a: 63, b: 75}, {a: 61, c: 55}), 'Objects of identical sizes with different property names are not equal'); ok(!_.isEqual({a: 1, b: 2}, {a: 1}), 'Objects of different sizes are not equal'); ok(!_.isEqual({a: 1}, {a: 1, b: 2}), 'Commutative equality is implemented for objects'); ok(!_.isEqual({x: 1, y: undefined}, {x: 1, z: 2}), 'Objects with identical keys and different values are not equivalent'); // `A` contains nested objects and arrays. a = { name: new String('Moe Howard'), age: new Number(77), stooge: true, hobbies: ['acting'], film: { name: 'Sing a Song of Six Pants', release: new Date(1947, 9, 30), stars: [new String('Larry Fine'), 'Shemp Howard'], minutes: new Number(16), seconds: 54 } }; // `B` contains equivalent nested objects and arrays. b = { name: new String('Moe Howard'), age: new Number(77), stooge: true, hobbies: ['acting'], film: { name: 'Sing a Song of Six Pants', release: new Date(1947, 9, 30), stars: [new String('Larry Fine'), 'Shemp Howard'], minutes: new Number(16), seconds: 54 } }; ok(_.isEqual(a, b), 'Objects with nested equivalent members are recursively compared'); // Instances. ok(_.isEqual(new First, new First), 'Object instances are equal'); ok(!_.isEqual(new First, new Second), 'Objects with different constructors and identical own properties are not equal'); ok(!_.isEqual({value: 1}, new First), 'Object instances and objects sharing equivalent properties are not equal'); ok(!_.isEqual({value: 2}, new Second), 'The prototype chain of objects should not be examined'); // Circular Arrays. (a = []).push(a); (b = []).push(b); ok(_.isEqual(a, b), 'Arrays containing circular references are equal'); a.push(new String('Larry')); b.push(new String('Larry')); ok(_.isEqual(a, b), 'Arrays containing circular references and equivalent properties are equal'); a.push('Shemp'); b.push('Curly'); ok(!_.isEqual(a, b), 'Arrays containing circular references and different properties are not equal'); // More circular arrays #767. a = ['everything is checked but', 'this', 'is not']; a[1] = a; b = ['everything is checked but', ['this', 'array'], 'is not']; ok(!_.isEqual(a, b), 'Comparison of circular references with non-circular references are not equal'); // Circular Objects. a = {abc: null}; b = {abc: null}; a.abc = a; b.abc = b; ok(_.isEqual(a, b), 'Objects containing circular references are equal'); a.def = 75; b.def = 75; ok(_.isEqual(a, b), 'Objects containing circular references and equivalent properties are equal'); a.def = new Number(75); b.def = new Number(63); ok(!_.isEqual(a, b), 'Objects containing circular references and different properties are not equal'); // More circular objects #767. a = {everything: 'is checked', but: 'this', is: 'not'}; a.but = a; b = {everything: 'is checked', but: {that: 'object'}, is: 'not'}; ok(!_.isEqual(a, b), 'Comparison of circular references with non-circular object references are not equal'); // Cyclic Structures. a = [{abc: null}]; b = [{abc: null}]; (a[0].abc = a).push(a); (b[0].abc = b).push(b); ok(_.isEqual(a, b), 'Cyclic structures are equal'); a[0].def = 'Larry'; b[0].def = 'Larry'; ok(_.isEqual(a, b), 'Cyclic structures containing equivalent properties are equal'); a[0].def = new String('Larry'); b[0].def = new String('Curly'); ok(!_.isEqual(a, b), 'Cyclic structures containing different properties are not equal'); // Complex Circular References. a = {foo: {b: {foo: {c: {foo: null}}}}}; b = {foo: {b: {foo: {c: {foo: null}}}}}; a.foo.b.foo.c.foo = a; b.foo.b.foo.c.foo = b; ok(_.isEqual(a, b), 'Cyclic structures with nested and identically-named properties are equal'); // Chaining. ok(!_.isEqual(_({x: 1, y: undefined}).chain(), _({x: 1, z: 2}).chain()), 'Chained objects containing different values are not equal'); a = _({x: 1, y: 2}).chain(); b = _({x: 1, y: 2}).chain(); equal(_.isEqual(a.isEqual(b), _(true)), true, '`isEqual` can be chained'); // Objects from another frame. ok(_.isEqual({}, iObject)); // Objects without a `constructor` property if (Object.create) { a = Object.create(null, {x: {value: 1, enumerable: true}}); b = {x: 1}; ok(_.isEqual(a, b), 'Handles objects without a constructor (e.g. from Object.create'); } function Foo() { this.a = 1; } Foo.prototype.constructor = null; var other = {a: 1}; strictEqual(_.isEqual(new Foo, other), false, 'Objects from different constructors are not equal'); }); test('isEmpty', function() { ok(!_([1]).isEmpty(), '[1] is not empty'); ok(_.isEmpty([]), '[] is empty'); ok(!_.isEmpty({one : 1}), '{one : 1} is not empty'); ok(_.isEmpty({}), '{} is empty'); ok(_.isEmpty(new RegExp('')), 'objects with prototype properties are empty'); ok(_.isEmpty(null), 'null is empty'); ok(_.isEmpty(), 'undefined is empty'); ok(_.isEmpty(''), 'the empty string is empty'); ok(!_.isEmpty('moe'), 'but other strings are not'); var obj = {one : 1}; delete obj.one; ok(_.isEmpty(obj), 'deleting all the keys from an object empties it'); var args = function(){ return arguments; }; ok(_.isEmpty(args()), 'empty arguments object is empty'); ok(!_.isEmpty(args('')), 'non-empty arguments object is not empty'); }); // Setup remote variables for iFrame tests. var iframe = document.createElement('iframe'); iframe.frameBorder = iframe.height = iframe.width = 0; document.body.appendChild(iframe); var iDoc = (iDoc = iframe.contentDocument || iframe.contentWindow).document || iDoc; iDoc.write( '' ); iDoc.close(); test('isElement', function() { ok(!_.isElement('div'), 'strings are not dom elements'); ok(_.isElement(document.body), 'the body tag is a DOM element'); ok(_.isElement(iElement), 'even from another frame'); }); test('isArguments', function() { var args = (function(){ return arguments; }(1, 2, 3)); ok(!_.isArguments('string'), 'a string is not an arguments object'); ok(!_.isArguments(_.isArguments), 'a function is not an arguments object'); ok(_.isArguments(args), 'but the arguments object is an arguments object'); ok(!_.isArguments(_.toArray(args)), 'but not when it\'s converted into an array'); ok(!_.isArguments([1, 2, 3]), 'and not vanilla arrays.'); ok(_.isArguments(iArguments), 'even from another frame'); }); test('isObject', function() { ok(_.isObject(arguments), 'the arguments object is object'); ok(_.isObject([1, 2, 3]), 'and arrays'); ok(_.isObject(document.body), 'and DOM element'); ok(_.isObject(iElement), 'even from another frame'); ok(_.isObject(function () {}), 'and functions'); ok(_.isObject(iFunction), 'even from another frame'); ok(!_.isObject(null), 'but not null'); ok(!_.isObject(undefined), 'and not undefined'); ok(!_.isObject('string'), 'and not string'); ok(!_.isObject(12), 'and not number'); ok(!_.isObject(true), 'and not boolean'); ok(_.isObject(new String('string')), 'but new String()'); }); test('isArray', function() { ok(!_.isArray(undefined), 'undefined vars are not arrays'); ok(!_.isArray(arguments), 'the arguments object is not an array'); ok(_.isArray([1, 2, 3]), 'but arrays are'); ok(_.isArray(iArray), 'even from another frame'); }); test('isString', function() { var obj = new String('I am a string object'); ok(!_.isString(document.body), 'the document body is not a string'); ok(_.isString([1, 2, 3].join(', ')), 'but strings are'); ok(_.isString(iString), 'even from another frame'); ok(_.isString('I am a string literal'), 'string literals are'); ok(_.isString(obj), 'so are String objects'); }); test('isNumber', function() { ok(!_.isNumber('string'), 'a string is not a number'); ok(!_.isNumber(arguments), 'the arguments object is not a number'); ok(!_.isNumber(undefined), 'undefined is not a number'); ok(_.isNumber(3 * 4 - 7 / 10), 'but numbers are'); ok(_.isNumber(NaN), 'NaN *is* a number'); ok(_.isNumber(Infinity), 'Infinity is a number'); ok(_.isNumber(iNumber), 'even from another frame'); ok(!_.isNumber('1'), 'numeric strings are not numbers'); }); test('isBoolean', function() { ok(!_.isBoolean(2), 'a number is not a boolean'); ok(!_.isBoolean('string'), 'a string is not a boolean'); ok(!_.isBoolean('false'), 'the string "false" is not a boolean'); ok(!_.isBoolean('true'), 'the string "true" is not a boolean'); ok(!_.isBoolean(arguments), 'the arguments object is not a boolean'); ok(!_.isBoolean(undefined), 'undefined is not a boolean'); ok(!_.isBoolean(NaN), 'NaN is not a boolean'); ok(!_.isBoolean(null), 'null is not a boolean'); ok(_.isBoolean(true), 'but true is'); ok(_.isBoolean(false), 'and so is false'); ok(_.isBoolean(iBoolean), 'even from another frame'); }); test('isFunction', function() { ok(!_.isFunction(undefined), 'undefined vars are not functions'); ok(!_.isFunction([1, 2, 3]), 'arrays are not functions'); ok(!_.isFunction('moe'), 'strings are not functions'); ok(_.isFunction(_.isFunction), 'but functions are'); ok(_.isFunction(iFunction), 'even from another frame'); ok(_.isFunction(function(){}), 'even anonymous ones'); }); test('isDate', function() { ok(!_.isDate(100), 'numbers are not dates'); ok(!_.isDate({}), 'objects are not dates'); ok(_.isDate(new Date()), 'but dates are'); ok(_.isDate(iDate), 'even from another frame'); }); test('isRegExp', function() { ok(!_.isRegExp(_.identity), 'functions are not RegExps'); ok(_.isRegExp(/identity/), 'but RegExps are'); ok(_.isRegExp(iRegExp), 'even from another frame'); }); test('isFinite', function() { ok(!_.isFinite(undefined), 'undefined is not finite'); ok(!_.isFinite(null), 'null is not finite'); ok(!_.isFinite(NaN), 'NaN is not finite'); ok(!_.isFinite(Infinity), 'Infinity is not finite'); ok(!_.isFinite(-Infinity), '-Infinity is not finite'); ok(_.isFinite('12'), 'Numeric strings are numbers'); ok(!_.isFinite('1a'), 'Non numeric strings are not numbers'); ok(!_.isFinite(''), 'Empty strings are not numbers'); var obj = new Number(5); ok(_.isFinite(obj), 'Number instances can be finite'); ok(_.isFinite(0), '0 is finite'); ok(_.isFinite(123), 'Ints are finite'); ok(_.isFinite(-12.44), 'Floats are finite'); }); test('isNaN', function() { ok(!_.isNaN(undefined), 'undefined is not NaN'); ok(!_.isNaN(null), 'null is not NaN'); ok(!_.isNaN(0), '0 is not NaN'); ok(_.isNaN(NaN), 'but NaN is'); ok(_.isNaN(iNaN), 'even from another frame'); ok(_.isNaN(new Number(NaN)), 'wrapped NaN is still NaN'); }); test('isNull', function() { ok(!_.isNull(undefined), 'undefined is not null'); ok(!_.isNull(NaN), 'NaN is not null'); ok(_.isNull(null), 'but null is'); ok(_.isNull(iNull), 'even from another frame'); }); test('isUndefined', function() { ok(!_.isUndefined(1), 'numbers are defined'); ok(!_.isUndefined(null), 'null is defined'); ok(!_.isUndefined(false), 'false is defined'); ok(!_.isUndefined(NaN), 'NaN is defined'); ok(_.isUndefined(), 'nothing is undefined'); ok(_.isUndefined(undefined), 'undefined is undefined'); ok(_.isUndefined(iUndefined), 'even from another frame'); }); if (window.ActiveXObject) { test('IE host objects', function() { var xml = new ActiveXObject('Msxml2.DOMDocument.3.0'); ok(!_.isNumber(xml)); ok(!_.isBoolean(xml)); ok(!_.isNaN(xml)); ok(!_.isFunction(xml)); ok(!_.isNull(xml)); ok(!_.isUndefined(xml)); }); } test('tap', function() { var intercepted = null; var interceptor = function(obj) { intercepted = obj; }; var returned = _.tap(1, interceptor); equal(intercepted, 1, 'passes tapped object to interceptor'); equal(returned, 1, 'returns tapped object'); returned = _([1, 2, 3]).chain(). map(function(n){ return n * 2; }). max(). tap(interceptor). value(); equal(returned, 6, 'can use tapped objects in a chain'); equal(intercepted, returned, 'can use tapped objects in a chain'); }); test('has', function () { var obj = {foo: 'bar', func: function(){}}; ok(_.has(obj, 'foo'), 'has() checks that the object has a property.'); ok(!_.has(obj, 'baz'), "has() returns false if the object doesn't have the property."); ok(_.has(obj, 'func'), 'has() works for functions too.'); obj.hasOwnProperty = null; ok(_.has(obj, 'foo'), 'has() works even when the hasOwnProperty method is deleted.'); var child = {}; child.prototype = obj; ok(!_.has(child, 'foo'), 'has() does not check the prototype chain for a property.'); strictEqual(_.has(null, 'foo'), false, 'has() returns false for null'); strictEqual(_.has(undefined, 'foo'), false, 'has() returns false for undefined'); }); test('matches', function() { var moe = {name: 'Moe Howard', hair: true}; var curly = {name: 'Curly Howard', hair: false}; var stooges = [moe, curly]; equal(_.matches({hair: true})(moe), true, 'Returns a boolean'); equal(_.matches({hair: true})(curly), false, 'Returns a boolean'); equal(_.matches({__x__: undefined})(5), false, 'can match undefined props on primitives'); equal(_.matches({__x__: undefined})({__x__: undefined}), true, 'can match undefined props'); equal(_.matches({})(null), true, 'Empty spec called with null object returns true'); equal(_.matches({a: 1})(null), false, 'Non-empty spec called with null object returns false'); ok(_.find(stooges, _.matches({hair: false})) === curly, 'returns a predicate that can be used by finding functions.'); ok(_.find(stooges, _.matches(moe)) === moe, 'can be used to locate an object exists in a collection.'); deepEqual(_.where([null, undefined], {a: 1}), [], 'Do not throw on null values.'); deepEqual(_.where([null, undefined], null), [null, undefined], 'null matches null'); deepEqual(_.where([null, undefined], {}), [null, undefined], 'null matches {}'); deepEqual(_.where([{b: 1}], {a: undefined}), [], 'handles undefined values (1683)'); _.each([true, 5, NaN, null, undefined], function(item) { deepEqual(_.where([{a: 1}], item), [{a: 1}], 'treats primitives as empty'); }); function Prototest() {} Prototest.prototype.x = 1; var specObj = new Prototest; var protospec = _.matches(specObj); equal(protospec({x: 2}), true, 'spec is restricted to own properties'); specObj.y = 5; protospec = _.matches(specObj); equal(protospec({x: 1, y: 5}), true); equal(protospec({x: 1, y: 4}), false); ok(_.matches({x: 1, y: 5})(specObj), 'inherited and own properties are checked on the test object'); Prototest.x = 5; ok(_.matches(Prototest)({x: 5, y: 1}), 'spec can be a function'); // #1729 var o = {'b': 1}; var m = _.matches(o); equal(m({'b': 1}), true); o.b = 2; o.a = 1; equal(m({'b': 1}), true, 'changing spec object doesnt change matches result'); //null edge cases var oCon = _.matches({'constructor': Object}); deepEqual(_.map([null, undefined, 5, {}], oCon), [false, false, false, true], 'doesnt fasley match constructor on undefined/null'); }); }()); 1.7.0~dfsg/test/index.html0000644000000000000000000000125712377203462014250 0ustar rootroot Underscore Test Suite
1.7.0~dfsg/test/functions.js0000644000000000000000000004433212377203462014622 0ustar rootroot(function() { module('Functions'); test('bind', function() { var context = {name : 'moe'}; var func = function(arg) { return 'name: ' + (this.name || arg); }; var bound = _.bind(func, context); equal(bound(), 'name: moe', 'can bind a function to a context'); bound = _(func).bind(context); equal(bound(), 'name: moe', 'can do OO-style binding'); bound = _.bind(func, null, 'curly'); equal(bound(), 'name: curly', 'can bind without specifying a context'); func = function(salutation, name) { return salutation + ': ' + name; }; func = _.bind(func, this, 'hello'); equal(func('moe'), 'hello: moe', 'the function was partially applied in advance'); func = _.bind(func, this, 'curly'); equal(func(), 'hello: curly', 'the function was completely applied in advance'); func = function(salutation, firstname, lastname) { return salutation + ': ' + firstname + ' ' + lastname; }; func = _.bind(func, this, 'hello', 'moe', 'curly'); equal(func(), 'hello: moe curly', 'the function was partially applied in advance and can accept multiple arguments'); func = function(context, message) { equal(this, context, message); }; _.bind(func, 0, 0, 'can bind a function to `0`')(); _.bind(func, '', '', 'can bind a function to an empty string')(); _.bind(func, false, false, 'can bind a function to `false`')(); // These tests are only meaningful when using a browser without a native bind function // To test this with a modern browser, set underscore's nativeBind to undefined var F = function () { return this; }; var boundf = _.bind(F, {hello: 'moe curly'}); var Boundf = boundf; // make eslint happy. var newBoundf = new Boundf(); equal(newBoundf.hello, undefined, 'function should not be bound to the context, to comply with ECMAScript 5'); equal(boundf().hello, 'moe curly', "When called without the new operator, it's OK to be bound to the context"); ok(newBoundf instanceof F, 'a bound instance is an instance of the original function'); raises(function() { _.bind('notafunction'); }, TypeError, 'throws an error when binding to a non-function'); }); test('partial', function() { var obj = {name: 'moe'}; var func = function() { return this.name + ' ' + _.toArray(arguments).join(' '); }; obj.func = _.partial(func, 'a', 'b'); equal(obj.func('c', 'd'), 'moe a b c d', 'can partially apply'); obj.func = _.partial(func, _, 'b', _, 'd'); equal(obj.func('a', 'c'), 'moe a b c d', 'can partially apply with placeholders'); func = _.partial(function() { return arguments.length; }, _, 'b', _, 'd'); equal(func('a', 'c', 'e'), 5, 'accepts more arguments than the number of placeholders'); equal(func('a'), 4, 'accepts fewer arguments than the number of placeholders'); func = _.partial(function() { return typeof arguments[2]; }, _, 'b', _, 'd'); equal(func('a'), 'undefined', 'unfilled placeholders are undefined'); }); test('bindAll', function() { var curly = {name : 'curly'}, moe = { name : 'moe', getName : function() { return 'name: ' + this.name; }, sayHi : function() { return 'hi: ' + this.name; } }; curly.getName = moe.getName; _.bindAll(moe, 'getName', 'sayHi'); curly.sayHi = moe.sayHi; equal(curly.getName(), 'name: curly', 'unbound function is bound to current object'); equal(curly.sayHi(), 'hi: moe', 'bound function is still bound to original object'); curly = {name : 'curly'}; moe = { name : 'moe', getName : function() { return 'name: ' + this.name; }, sayHi : function() { return 'hi: ' + this.name; }, sayLast : function() { return this.sayHi(_.last(arguments)); } }; raises(function() { _.bindAll(moe); }, Error, 'throws an error for bindAll with no functions named'); raises(function() { _.bindAll(moe, 'sayBye'); }, TypeError, 'throws an error for bindAll if the given key is undefined'); raises(function() { _.bindAll(moe, 'name'); }, TypeError, 'throws an error for bindAll if the given key is not a function'); _.bindAll(moe, 'sayHi', 'sayLast'); curly.sayHi = moe.sayHi; equal(curly.sayHi(), 'hi: moe'); var sayLast = moe.sayLast; equal(sayLast(1, 2, 3, 4, 5, 6, 7, 'Tom'), 'hi: moe', 'createCallback works with any number of arguments'); }); test('memoize', function() { var fib = function(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }; equal(fib(10), 55, 'a memoized version of fibonacci produces identical results'); fib = _.memoize(fib); // Redefine `fib` for memoization equal(fib(10), 55, 'a memoized version of fibonacci produces identical results'); var o = function(str) { return str; }; var fastO = _.memoize(o); equal(o('toString'), 'toString', 'checks hasOwnProperty'); equal(fastO('toString'), 'toString', 'checks hasOwnProperty'); // Expose the cache. var upper = _.memoize(function(s) { return s.toUpperCase(); }); equal(upper('foo'), 'FOO'); equal(upper('bar'), 'BAR'); deepEqual(upper.cache, {foo: 'FOO', bar: 'BAR'}); upper.cache = {foo: 'BAR', bar: 'FOO'}; equal(upper('foo'), 'BAR'); equal(upper('bar'), 'FOO'); var hashed = _.memoize(function(key) { //https://github.com/jashkenas/underscore/pull/1679#discussion_r13736209 ok(/[a-z]+/.test(key), 'hasher doesn\'t change keys'); return key; }, function(key) { return key.toUpperCase(); }); hashed('yep'); deepEqual(hashed.cache, {'YEP': 'yep'}, 'takes a hasher'); // Test that the hash function can be used to swizzle the key. var objCacher = _.memoize(function(value, key) { return {key: key, value: value}; }, function(value, key) { return key; }); var myObj = objCacher('a', 'alpha'); var myObjAlias = objCacher('b', 'alpha'); notStrictEqual(myObj, undefined, 'object is created if second argument used as key'); strictEqual(myObj, myObjAlias, 'object is cached if second argument used as key'); strictEqual(myObj.value, 'a', 'object is not modified if second argument used as key'); }); asyncTest('delay', 2, function() { var delayed = false; _.delay(function(){ delayed = true; }, 100); setTimeout(function(){ ok(!delayed, "didn't delay the function quite yet"); }, 50); setTimeout(function(){ ok(delayed, 'delayed the function'); start(); }, 150); }); asyncTest('defer', 1, function() { var deferred = false; _.defer(function(bool){ deferred = bool; }, true); _.delay(function(){ ok(deferred, 'deferred the function'); start(); }, 50); }); asyncTest('throttle', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr(); equal(counter, 1, 'incr was called immediately'); _.delay(function(){ equal(counter, 2, 'incr was throttled'); start(); }, 64); }); asyncTest('throttle arguments', 2, function() { var value = 0; var update = function(val){ value = val; }; var throttledUpdate = _.throttle(update, 32); throttledUpdate(1); throttledUpdate(2); _.delay(function(){ throttledUpdate(3); }, 64); equal(value, 1, 'updated to latest value'); _.delay(function(){ equal(value, 3, 'updated to latest value'); start(); }, 96); }); asyncTest('throttle once', 2, function() { var counter = 0; var incr = function(){ return ++counter; }; var throttledIncr = _.throttle(incr, 32); var result = throttledIncr(); _.delay(function(){ equal(result, 1, 'throttled functions return their value'); equal(counter, 1, 'incr was called once'); start(); }, 64); }); asyncTest('throttle twice', 1, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr(); _.delay(function(){ equal(counter, 2, 'incr was called twice'); start(); }, 64); }); asyncTest('more throttling', 3, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 30); throttledIncr(); throttledIncr(); equal(counter, 1); _.delay(function(){ equal(counter, 2); throttledIncr(); equal(counter, 3); start(); }, 85); }); asyncTest('throttle repeatedly with results', 6, function() { var counter = 0; var incr = function(){ return ++counter; }; var throttledIncr = _.throttle(incr, 100); var results = []; var saveResult = function() { results.push(throttledIncr()); }; saveResult(); saveResult(); _.delay(saveResult, 50); _.delay(saveResult, 150); _.delay(saveResult, 160); _.delay(saveResult, 230); _.delay(function() { equal(results[0], 1, 'incr was called once'); equal(results[1], 1, 'incr was throttled'); equal(results[2], 1, 'incr was throttled'); equal(results[3], 2, 'incr was called twice'); equal(results[4], 2, 'incr was throttled'); equal(results[5], 3, 'incr was called trailing'); start(); }, 300); }); asyncTest('throttle triggers trailing call when invoked repeatedly', 2, function() { var counter = 0; var limit = 48; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); var stamp = new Date; while (new Date - stamp < limit) { throttledIncr(); } var lastCount = counter; ok(counter > 1); _.delay(function() { ok(counter > lastCount); start(); }, 96); }); asyncTest('throttle does not trigger leading call when leading is set to false', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 60, {leading: false}); throttledIncr(); throttledIncr(); equal(counter, 0); _.delay(function() { equal(counter, 1); start(); }, 96); }); asyncTest('more throttle does not trigger leading call when leading is set to false', 3, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100, {leading: false}); throttledIncr(); _.delay(throttledIncr, 50); _.delay(throttledIncr, 60); _.delay(throttledIncr, 200); equal(counter, 0); _.delay(function() { equal(counter, 1); }, 250); _.delay(function() { equal(counter, 2); start(); }, 350); }); asyncTest('one more throttle with leading: false test', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100, {leading: false}); var time = new Date; while (new Date - time < 350) throttledIncr(); ok(counter <= 3); _.delay(function() { ok(counter <= 4); start(); }, 200); }); asyncTest('throttle does not trigger trailing call when trailing is set to false', 4, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 60, {trailing: false}); throttledIncr(); throttledIncr(); throttledIncr(); equal(counter, 1); _.delay(function() { equal(counter, 1); throttledIncr(); throttledIncr(); equal(counter, 2); _.delay(function() { equal(counter, 2); start(); }, 96); }, 96); }); asyncTest('throttle continues to function after system time is set backwards', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100); var origNowFunc = _.now; throttledIncr(); equal(counter, 1); _.now = function () { return new Date(2013, 0, 1, 1, 1, 1); }; _.delay(function() { throttledIncr(); equal(counter, 2); start(); _.now = origNowFunc; }, 200); }); asyncTest('throttle re-entrant', 2, function() { var sequence = [ ['b1', 'b2'], ['c1', 'c2'] ]; var value = ''; var throttledAppend; var append = function(arg){ value += this + arg; var args = sequence.pop(); if (args) { throttledAppend.call(args[0], args[1]); } }; throttledAppend = _.throttle(append, 32); throttledAppend.call('a1', 'a2'); equal(value, 'a1a2'); _.delay(function(){ equal(value, 'a1a2c1c2b1b2', 'append was throttled successfully'); start(); }, 100); }); asyncTest('debounce', 1, function() { var counter = 0; var incr = function(){ counter++; }; var debouncedIncr = _.debounce(incr, 32); debouncedIncr(); debouncedIncr(); _.delay(debouncedIncr, 16); _.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 96); }); asyncTest('debounce asap', 4, function() { var a, b; var counter = 0; var incr = function(){ return ++counter; }; var debouncedIncr = _.debounce(incr, 64, true); a = debouncedIncr(); b = debouncedIncr(); equal(a, 1); equal(b, 1); equal(counter, 1, 'incr was called immediately'); _.delay(debouncedIncr, 16); _.delay(debouncedIncr, 32); _.delay(debouncedIncr, 48); _.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 128); }); asyncTest('debounce asap recursively', 2, function() { var counter = 0; var debouncedIncr = _.debounce(function(){ counter++; if (counter < 10) debouncedIncr(); }, 32, true); debouncedIncr(); equal(counter, 1, 'incr was called immediately'); _.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 96); }); asyncTest('debounce after system time is set backwards', 2, function() { var counter = 0; var origNowFunc = _.now; var debouncedIncr = _.debounce(function(){ counter++; }, 100, true); debouncedIncr(); equal(counter, 1, 'incr was called immediately'); _.now = function () { return new Date(2013, 0, 1, 1, 1, 1); }; _.delay(function() { debouncedIncr(); equal(counter, 2, 'incr was debounced successfully'); start(); _.now = origNowFunc; }, 200); }); asyncTest('debounce re-entrant', 2, function() { var sequence = [ ['b1', 'b2'] ]; var value = ''; var debouncedAppend; var append = function(arg){ value += this + arg; var args = sequence.pop(); if (args) { debouncedAppend.call(args[0], args[1]); } }; debouncedAppend = _.debounce(append, 32); debouncedAppend.call('a1', 'a2'); equal(value, ''); _.delay(function(){ equal(value, 'a1a2b1b2', 'append was debounced successfully'); start(); }, 100); }); test('once', function() { var num = 0; var increment = _.once(function(){ return ++num; }); increment(); increment(); equal(num, 1); equal(increment(), 1, 'stores a memo to the last value'); }); test('Recursive onced function.', 1, function() { var f = _.once(function(){ ok(true); f(); }); f(); }); test('wrap', function() { var greet = function(name){ return 'hi: ' + name; }; var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); }); equal(backwards('moe'), 'hi: moe eom', 'wrapped the salutation function'); var inner = function(){ return 'Hello '; }; var obj = {name : 'Moe'}; obj.hi = _.wrap(inner, function(fn){ return fn() + this.name; }); equal(obj.hi(), 'Hello Moe'); var noop = function(){}; var wrapped = _.wrap(noop, function(){ return Array.prototype.slice.call(arguments, 0); }); var ret = wrapped(['whats', 'your'], 'vector', 'victor'); deepEqual(ret, [noop, ['whats', 'your'], 'vector', 'victor']); }); test('negate', function() { var isOdd = function(n){ return n & 1; }; equal(_.negate(isOdd)(2), true, 'should return the complement of the given function'); equal(_.negate(isOdd)(3), false, 'should return the complement of the given function'); }); test('compose', function() { var greet = function(name){ return 'hi: ' + name; }; var exclaim = function(sentence){ return sentence + '!'; }; var composed = _.compose(exclaim, greet); equal(composed('moe'), 'hi: moe!', 'can compose a function that takes another'); composed = _.compose(greet, exclaim); equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative'); // f(g(h(x, y, z))) function h(x, y, z) { equal(arguments.length, 3, 'First function called with multiple args'); return z * y; } function g(x) { equal(arguments.length, 1, 'Composed function is called with 1 argument'); return x; } function f(x) { equal(arguments.length, 1, 'Composed function is called with 1 argument'); return x * 2; } composed = _.compose(f, g, h); equal(composed(1, 2, 3), 12); }); test('after', function() { var testAfter = function(afterAmount, timesCalled) { var afterCalled = 0; var after = _.after(afterAmount, function() { afterCalled++; }); while (timesCalled--) after(); return afterCalled; }; equal(testAfter(5, 5), 1, 'after(N) should fire after being called N times'); equal(testAfter(5, 4), 0, 'after(N) should not fire unless called N times'); equal(testAfter(0, 0), 0, 'after(0) should not fire immediately'); equal(testAfter(0, 1), 1, 'after(0) should fire when first invoked'); }); test('before', function() { var testBefore = function(beforeAmount, timesCalled) { var beforeCalled = 0; var before = _.before(beforeAmount, function() { beforeCalled++; }); while (timesCalled--) before(); return beforeCalled; }; equal(testBefore(5, 5), 4, 'before(N) should not fire after being called N times'); equal(testBefore(5, 4), 4, 'before(N) should fire before being called N times'); equal(testBefore(0, 0), 0, 'before(0) should not fire immediately'); equal(testBefore(0, 1), 0, 'before(0) should not fire when first invoked'); var context = {num: 0}; var increment = _.before(3, function(){ return ++this.num; }); _.times(10, increment, context); equal(increment(), 2, 'stores a memo to the last value'); equal(context.num, 2, 'provides context'); }); test('iteratee', function() { var identity = _.iteratee(); equal(identity, _.identity, '_.iteratee is exposed as an external function.'); }); }()); 1.7.0~dfsg/test/arrays.js0000644000000000000000000003650612377203462014117 0ustar rootroot(function() { module('Arrays'); test('first', function() { equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array'); equal(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"'); deepEqual(_.first([1, 2, 3], 0), [], 'can pass an index to first'); deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can pass an index to first'); deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'can pass an index to first'); var result = (function(){ return _.first(arguments); }(4, 3, 2, 1)); equal(result, 4, 'works on an arguments object.'); result = _.map([[1, 2, 3], [1, 2, 3]], _.first); deepEqual(result, [1, 1], 'works well with _.map'); result = (function() { return _.first([1, 2, 3], 2); }()); deepEqual(result, [1, 2]); equal(_.first(null), undefined, 'handles nulls'); strictEqual(_.first([1, 2, 3], -1).length, 0); }); test('head', function() { strictEqual(_.first, _.head, 'alias for first'); }); test('take', function() { strictEqual(_.first, _.take, 'alias for first'); }); test('rest', function() { var numbers = [1, 2, 3, 4]; deepEqual(_.rest(numbers), [2, 3, 4], 'working rest()'); deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'working rest(0)'); deepEqual(_.rest(numbers, 2), [3, 4], 'rest can take an index'); var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4)); deepEqual(result, [2, 3, 4], 'works on arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.rest); deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map'); result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4)); deepEqual(result, [2, 3, 4], 'works on arguments object'); }); test('tail', function() { strictEqual(_.rest, _.tail, 'alias for rest'); }); test('drop', function() { strictEqual(_.rest, _.drop, 'alias for rest'); }); test('initial', function() { deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'working initial()'); deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'initial can take an index'); deepEqual(_.initial([1, 2, 3, 4], 6), [], 'initial can take a large index'); var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4)); deepEqual(result, [1, 2, 3], 'initial works on arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.initial); deepEqual(_.flatten(result), [1, 2, 1, 2], 'initial works with _.map'); }); test('last', function() { equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array'); deepEqual(_.last([1, 2, 3], 0), [], 'can pass an index to last'); deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can pass an index to last'); deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'can pass an index to last'); var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4)); equal(result, 4, 'works on an arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.last); deepEqual(result, [3, 3], 'works well with _.map'); equal(_.last(null), undefined, 'handles nulls'); strictEqual(_.last([1, 2, 3], -1).length, 0); }); test('compact', function() { equal(_.compact([0, 1, false, 2, false, 3]).length, 3, 'can trim out all falsy values'); var result = (function(){ return _.compact(arguments).length; }(0, 1, false, 2, false, 3)); equal(result, 3, 'works on an arguments object'); }); test('flatten', function() { var list = [1, [2], [3, [[[4]]]]]; deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays'); deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays'); var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]])); deepEqual(result, [1, 2, 3, 4], 'works on an arguments object'); list = [[1], [2], [3], [[4]]]; deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays'); }); test('without', function() { var list = [1, 2, 1, 0, 3, 1, 4]; deepEqual(_.without(list, 0, 1), [2, 3, 4], 'can remove all instances of an object'); var result = (function(){ return _.without(arguments, 0, 1); }(1, 2, 1, 0, 3, 1, 4)); deepEqual(result, [2, 3, 4], 'works on an arguments object'); list = [{one : 1}, {two : 2}]; equal(_.without(list, {one : 1}).length, 2, 'uses real object identity for comparisons.'); equal(_.without(list, list[0]).length, 1, 'ditto.'); }); test('uniq', function() { var list = [1, 2, 1, 3, 1, 4]; deepEqual(_.uniq(list), [1, 2, 3, 4], 'can find the unique values of an unsorted array'); list = [1, 1, 1, 2, 2, 3]; deepEqual(_.uniq(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster'); list = [{name: 'moe'}, {name: 'curly'}, {name: 'larry'}, {name: 'curly'}]; var iterator = function(value) { return value.name; }; deepEqual(_.map(_.uniq(list, false, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator'); deepEqual(_.map(_.uniq(list, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator without specifying whether array is sorted'); iterator = function(value) { return value + 1; }; list = [1, 2, 2, 3, 4, 4]; deepEqual(_.uniq(list, true, iterator), [1, 2, 3, 4], 'iterator works with sorted array'); var result = (function(){ return _.uniq(arguments); }(1, 2, 1, 3, 1, 4)); deepEqual(result, [1, 2, 3, 4], 'works on an arguments object'); var a = {}, b = {}, c = {}; deepEqual(_.uniq([a, b, a, b, c]), [a, b, c], 'works on values that can be tested for equivalency but not ordered'); deepEqual(_.uniq(null), []); var context = {}; list = [3]; _.uniq(list, function(value, index, array) { strictEqual(this, context); strictEqual(value, 3); strictEqual(index, 0); strictEqual(array, list); }, context); deepEqual(_.uniq([{a: 1, b: 1}, {a: 1, b: 2}, {a: 1, b: 3}, {a: 2, b: 1}], 'a'), [{a: 1, b: 1}, {a: 2, b: 1}], 'can use pluck like iterator'); deepEqual(_.uniq([{0: 1, b: 1}, {0: 1, b: 2}, {0: 1, b: 3}, {0: 2, b: 1}], 0), [{0: 1, b: 1}, {0: 2, b: 1}], 'can use falsey pluck like iterator'); }); test('unique', function() { strictEqual(_.uniq, _.unique, 'alias for uniq'); }); test('intersection', function() { var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho']; deepEqual(_.intersection(stooges, leaders), ['moe'], 'can take the set intersection of two arrays'); deepEqual(_(stooges).intersection(leaders), ['moe'], 'can perform an OO-style intersection'); var result = (function(){ return _.intersection(arguments, leaders); }('moe', 'curly', 'larry')); deepEqual(result, ['moe'], 'works on an arguments object'); var theSixStooges = ['moe', 'moe', 'curly', 'curly', 'larry', 'larry']; deepEqual(_.intersection(theSixStooges, leaders), ['moe'], 'returns a duplicate-free array'); result = _.intersection([2, 4, 3, 1], [1, 2, 3]); deepEqual(result, [2, 3, 1], 'preserves order of first array'); result = _.intersection(null, [1, 2, 3]); equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as first argument'); equal(result.length, 0, 'returns an empty array when passed null as first argument'); result = _.intersection([1, 2, 3], null); equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as argument beyond the first'); equal(result.length, 0, 'returns an empty array when passed null as argument beyond the first'); }); test('union', function() { var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]); deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays'); result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]); deepEqual(result, [1, 2, 3, 30, 40, [1]], 'takes the union of a list of nested arrays'); var args = null; (function(){ args = arguments; }(1, 2, 3)); result = _.union(args, [2, 30, 1], [1, 40]); deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays'); result = _.union([1, 2, 3], 4); deepEqual(result, [1, 2, 3], 'restrict the union to arrays only'); }); test('difference', function() { var result = _.difference([1, 2, 3], [2, 30, 40]); deepEqual(result, [1, 3], 'takes the difference of two arrays'); result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]); deepEqual(result, [3, 4], 'takes the difference of three arrays'); result = _.difference([1, 2, 3], 1); deepEqual(result, [1, 2, 3], 'restrict the difference to arrays only'); }); test('zip', function() { var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true]; deepEqual(_.zip(names, ages, leaders), [ ['moe', 30, true], ['larry', 40, undefined], ['curly', 50, undefined] ], 'zipped together arrays of different lengths'); var stooges = _.zip(['moe', 30, 'stooge 1'], ['larry', 40, 'stooge 2'], ['curly', 50, 'stooge 3']); deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], ['stooge 1', 'stooge 2', 'stooge 3']], 'zipped pairs'); // In the case of difference lengths of the tuples undefineds // should be used as placeholder stooges = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']); deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], [undefined, undefined, 'extra data']], 'zipped pairs with empties'); var empty = _.zip([]); deepEqual(empty, [], 'unzipped empty'); deepEqual(_.zip(null), [], 'handles null'); deepEqual(_.zip(), [], '_.zip() returns []'); }); test('object', function() { var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]); var shouldBe = {moe: 30, larry: 40, curly: 50}; deepEqual(result, shouldBe, 'two arrays zipped together into an object'); result = _.object([['one', 1], ['two', 2], ['three', 3]]); shouldBe = {one: 1, two: 2, three: 3}; deepEqual(result, shouldBe, 'an array of pairs zipped together into an object'); var stooges = {moe: 30, larry: 40, curly: 50}; deepEqual(_.object(_.pairs(stooges)), stooges, 'an object converted to pairs and back to an object'); deepEqual(_.object(null), {}, 'handles nulls'); }); test('indexOf', function() { var numbers = [1, 2, 3]; equal(_.indexOf(numbers, 2), 1, 'can compute indexOf'); var result = (function(){ return _.indexOf(arguments, 2); }(1, 2, 3)); equal(result, 1, 'works on an arguments object'); equal(_.indexOf(null, 2), -1, 'handles nulls properly'); var num = 35; numbers = [10, 20, 30, 40, 50]; var index = _.indexOf(numbers, num, true); equal(index, -1, '35 is not in the list'); numbers = [10, 20, 30, 40, 50]; num = 40; index = _.indexOf(numbers, num, true); equal(index, 3, '40 is in the list'); numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40; equal(_.indexOf(numbers, num, true), 1, '40 is in the list'); equal(_.indexOf(numbers, 6, true), -1, '6 isnt in the list'); equal(_.indexOf([1, 2, 5, 4, 6, 7], 5, true), -1, 'sorted indexOf doesn\'t uses binary search'); ok(_.every(['1', [], {}, null], function() { return _.indexOf(numbers, num, {}) === 1; }), 'non-nums as fromIndex make indexOf assume sorted'); numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; index = _.indexOf(numbers, 2, 5); equal(index, 7, 'supports the fromIndex argument'); index = _.indexOf([,,,], undefined); equal(index, 0, 'treats sparse arrays as if they were dense'); var array = [1, 2, 3, 1, 2, 3]; strictEqual(_.indexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index'); strictEqual(_.indexOf(array, 1, -2), -1, 'neg `fromIndex` starts at the right index'); strictEqual(_.indexOf(array, 2, -3), 4); _.each([-6, -8, -Infinity], function(fromIndex) { strictEqual(_.indexOf(array, 1, fromIndex), 0); }); strictEqual(_.indexOf([1, 2, 3], 1, true), 0); }); test('lastIndexOf', function() { var numbers = [1, 0, 1]; var falsey = [void 0, '', 0, false, NaN, null, undefined]; equal(_.lastIndexOf(numbers, 1), 2); numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0]; numbers.lastIndexOf = null; equal(_.lastIndexOf(numbers, 1), 5, 'can compute lastIndexOf, even without the native function'); equal(_.lastIndexOf(numbers, 0), 8, 'lastIndexOf the other element'); var result = (function(){ return _.lastIndexOf(arguments, 1); }(1, 0, 1, 0, 0, 1, 0, 0, 0)); equal(result, 5, 'works on an arguments object'); equal(_.lastIndexOf(null, 2), -1, 'handles nulls properly'); numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; var index = _.lastIndexOf(numbers, 2, 2); equal(index, 1, 'supports the fromIndex argument'); var array = [1, 2, 3, 1, 2, 3]; strictEqual(_.lastIndexOf(array, 1, 0), 0, 'starts at the correct from idx'); strictEqual(_.lastIndexOf(array, 3), 5, 'should return the index of the last matched value'); strictEqual(_.lastIndexOf(array, 4), -1, 'should return `-1` for an unmatched value'); strictEqual(_.lastIndexOf(array, 1, 2), 0, 'should work with a positive `fromIndex`'); _.each([6, 8, Math.pow(2, 32), Infinity], function(fromIndex) { strictEqual(_.lastIndexOf(array, undefined, fromIndex), -1); strictEqual(_.lastIndexOf(array, 1, fromIndex), 3); strictEqual(_.lastIndexOf(array, '', fromIndex), -1); }); var expected = _.map(falsey, function(value) { return typeof value == 'number' ? -1 : 5; }); var actual = _.map(falsey, function(fromIndex) { return _.lastIndexOf(array, 3, fromIndex); }); deepEqual(actual, expected, 'should treat falsey `fromIndex` values, except `0` and `NaN`, as `array.length`'); strictEqual(_.lastIndexOf(array, 3, '1'), 5, 'should treat non-number `fromIndex` values as `array.length`'); strictEqual(_.lastIndexOf(array, 3, true), 5, 'should treat non-number `fromIndex` values as `array.length`'); strictEqual(_.lastIndexOf(array, 2, -3), 1, 'should work with a negative `fromIndex`'); strictEqual(_.lastIndexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index'); deepEqual(_.map([-6, -8, -Infinity], function(fromIndex) { return _.lastIndexOf(array, 1, fromIndex); }), [0, -1, -1]); }); test('range', function() { deepEqual(_.range(0), [], 'range with 0 as a first argument generates an empty array'); deepEqual(_.range(4), [0, 1, 2, 3], 'range with a single positive argument generates an array of elements 0,1,2,...,n-1'); deepEqual(_.range(5, 8), [5, 6, 7], 'range with two arguments a & b, a<b generates an array of elements a,a+1,a+2,...,b-2,b-1'); deepEqual(_.range(8, 5), [], 'range with two arguments a & b, b<a generates an empty array'); deepEqual(_.range(3, 10, 3), [3, 6, 9], 'range with three arguments a & b & c, c < b-a, a < b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) < c'); deepEqual(_.range(3, 10, 15), [3], 'range with three arguments a & b & c, c > b-a, a < b generates an array with a single element, equal to a'); deepEqual(_.range(12, 7, -2), [12, 10, 8], 'range with three arguments a & b & c, a > b, c < 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b'); deepEqual(_.range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs'); }); }()); 1.7.0~dfsg/test/chaining.js0000644000000000000000000000373312377203462014372 0ustar rootroot(function() { module('Chaining'); test('map/flatten/reduce', function() { var lyrics = [ 'I\'m a lumberjack and I\'m okay', 'I sleep all night and I work all day', 'He\'s a lumberjack and he\'s okay', 'He sleeps all night and he works all day' ]; var counts = _(lyrics).chain() .map(function(line) { return line.split(''); }) .flatten() .reduce(function(hash, l) { hash[l] = hash[l] || 0; hash[l]++; return hash; }, {}).value(); equal(counts.a, 16, 'counted all the letters in the song'); equal(counts.e, 10, 'counted all the letters in the song'); }); test('select/reject/sortBy', function() { var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers = _(numbers).chain().select(function(n) { return n % 2 === 0; }).reject(function(n) { return n % 4 === 0; }).sortBy(function(n) { return -n; }).value(); deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers'); }); test('select/reject/sortBy in functional style', function() { var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers = _.chain(numbers).select(function(n) { return n % 2 === 0; }).reject(function(n) { return n % 4 === 0; }).sortBy(function(n) { return -n; }).value(); deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers'); }); test('reverse/concat/unshift/pop/map', function() { var numbers = [1, 2, 3, 4, 5]; numbers = _(numbers).chain() .reverse() .concat([5, 5, 5]) .unshift(17) .pop() .map(function(n){ return n * 2; }) .value(); deepEqual(numbers, [34, 10, 8, 6, 4, 2, 10, 10], 'can chain together array functions.'); }); test('chaining works in small stages', function() { var o = _([1, 2, 3, 4]).chain(); deepEqual(o.filter(function(i) { return i < 3; }).value(), [1, 2]); deepEqual(o.filter(function(i) { return i > 2; }).value(), [3, 4]); }); }()); 1.7.0~dfsg/test/.eslintrc0000644000000000000000000000073512377203462014077 0ustar rootroot{ "env": { "browser": true }, "globals": { "_": false, "test": false, "ok": false, "is": false, "equal": false, "deepEqual": false, "strictEqual": false, "notStrictEqual": false, "notEqual": false, "raises": false, "throws": false, "asyncTest": false, "start": false }, "rules": { "brace-style": 0, "dot-notation": 1, "no-new-wrappers": 0, "no-sparse-arrays": 0, "no-extend-native": 0 } } 1.7.0~dfsg/test/collections.js0000644000000000000000000006701412377203462015132 0ustar rootroot(function() { module('Collections'); test('each', function() { _.each([1, 2, 3], function(num, i) { equal(num, i + 1, 'each iterators provide value and iteration count'); }); var answers = []; _.each([1, 2, 3], function(num){ answers.push(num * this.multiplier);}, {multiplier : 5}); deepEqual(answers, [5, 10, 15], 'context object property accessed'); answers = []; _.each([1, 2, 3], function(num){ answers.push(num); }); deepEqual(answers, [1, 2, 3], 'aliased as "forEach"'); answers = []; var obj = {one : 1, two : 2, three : 3}; obj.constructor.prototype.four = 4; _.each(obj, function(value, key){ answers.push(key); }); deepEqual(answers, ['one', 'two', 'three'], 'iterating over objects works, and ignores the object prototype.'); delete obj.constructor.prototype.four; var answer = null; _.each([1, 2, 3], function(num, index, arr){ if (_.include(arr, num)) answer = true; }); ok(answer, 'can reference the original collection from inside the iterator'); answers = 0; _.each(null, function(){ ++answers; }); equal(answers, 0, 'handles a null properly'); _.each(false, function(){}); var a = [1, 2, 3]; strictEqual(_.each(a, function(){}), a); strictEqual(_.each(null, function(){}), null); var b = [1, 2, 3]; b.length = 100; answers = 0; _.each(b, function(){ ++answers; }); equal(answers, 100, 'enumerates [0, length)'); }); test('forEach', function() { strictEqual(_.each, _.forEach, 'alias for each'); }); test('lookupIterator with contexts', function() { _.each([true, false, 'yes', '', 0, 1, {}], function(context) { _.each([1], function() { equal(this, context); }, context); }); }); test('map', function() { var doubled = _.map([1, 2, 3], function(num){ return num * 2; }); deepEqual(doubled, [2, 4, 6], 'doubled numbers'); var tripled = _.map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier : 3}); deepEqual(tripled, [3, 6, 9], 'tripled numbers with context'); doubled = _([1, 2, 3]).map(function(num){ return num * 2; }); deepEqual(doubled, [2, 4, 6], 'OO-style doubled numbers'); if (document.querySelectorAll) { var ids = _.map(document.querySelectorAll('#map-test *'), function(n){ return n.id; }); deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on NodeLists.'); } ids = _.map({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){ return n.id; }); deepEqual(ids, ['1', '2'], 'Can use collection methods on Array-likes.'); deepEqual(_.map(null, _.noop), [], 'handles a null properly'); deepEqual(_.map([1], function() { return this.length; }, [5]), [1], 'called with context'); // Passing a property name like _.pluck. var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}]; deepEqual(_.map(people, 'name'), ['moe', 'curly'], 'predicate string map to object properties'); }); test('collect', function() { strictEqual(_.map, _.collect, 'alias for map'); }); test('reduce', function() { var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }, 0); equal(sum, 6, 'can sum up an array'); var context = {multiplier : 3}; sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num * this.multiplier; }, 0, context); equal(sum, 18, 'can reduce with a context object'); sum = _.inject([1, 2, 3], function(sum, num){ return sum + num; }, 0); equal(sum, 6, 'aliased as "inject"'); sum = _([1, 2, 3]).reduce(function(sum, num){ return sum + num; }, 0); equal(sum, 6, 'OO-style reduce'); sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }); equal(sum, 6, 'default initial value'); var prod = _.reduce([1, 2, 3, 4], function(prod, num){ return prod * num; }); equal(prod, 24, 'can reduce via multiplication'); ok(_.reduce(null, _.noop, 138) === 138, 'handles a null (with initial value) properly'); equal(_.reduce([], _.noop, undefined), undefined, 'undefined can be passed as a special case'); equal(_.reduce([_], _.noop), _, 'collection of length one with no initial value returns the first item'); raises(function() { _.reduce([], _.noop); }, TypeError, 'throws an error for empty arrays with no initial value'); raises(function() {_.reduce(null, _.noop);}, TypeError, 'handles a null (without initial value) properly'); }); test('foldl', function() { strictEqual(_.reduce, _.foldl, 'alias for reduce'); }); test('reduceRight', function() { var list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }, ''); equal(list, 'bazbarfoo', 'can perform right folds'); list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }); equal(list, 'bazbarfoo', 'default initial value'); var sum = _.reduceRight({a: 1, b: 2, c: 3}, function(sum, num){ return sum + num; }); equal(sum, 6, 'default initial value on object'); ok(_.reduceRight(null, _.noop, 138) === 138, 'handles a null (with initial value) properly'); equal(_.reduceRight([_], _.noop), _, 'collection of length one with no initial value returns the first item'); equal(_.reduceRight([], _.noop, undefined), undefined, 'undefined can be passed as a special case'); raises(function() { _.reduceRight([], _.noop); }, TypeError, 'throws an error for empty arrays with no initial value'); raises(function() {_.reduceRight(null, _.noop);}, TypeError, 'handles a null (without initial value) properly'); // Assert that the correct arguments are being passed. var args, memo = {}, object = {a: 1, b: 2}, lastKey = _.keys(object).pop(); var expected = lastKey === 'a' ? [memo, 1, 'a', object] : [memo, 2, 'b', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, memo); deepEqual(args, expected); // And again, with numeric keys. object = {'2': 'a', '1': 'b'}; lastKey = _.keys(object).pop(); args = null; expected = lastKey === '2' ? [memo, 'a', '2', object] : [memo, 'b', '1', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, memo); deepEqual(args, expected); }); test('foldr', function() { strictEqual(_.reduceRight, _.foldr, 'alias for reduceRight'); }); test('find', function() { var array = [1, 2, 3, 4]; strictEqual(_.find(array, function(n) { return n > 2; }), 3, 'should return first found `value`'); strictEqual(_.find(array, function() { return false; }), void 0, 'should return `undefined` if `value` is not found'); // Matching an object like _.findWhere. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; deepEqual(_.find(list, {a: 1}), {a: 1, b: 2}, 'can be used as findWhere'); deepEqual(_.find(list, {b: 4}), {a: 1, b: 4}); ok(!_.find(list, {c: 1}), 'undefined when not found'); ok(!_.find([], {c: 1}), 'undefined when searching empty list'); var result = _.find([1, 2, 3], function(num){ return num * 2 === 4; }); equal(result, 2, 'found the first "2" and broke the loop'); }); test('detect', function() { strictEqual(_.detect, _.find, 'alias for detect'); }); test('filter', function() { var evenArray = [1, 2, 3, 4, 5, 6]; var evenObject = {one: 1, two: 2, three: 3}; var isEven = function(num){ return num % 2 === 0; }; deepEqual(_.filter(evenArray, isEven), [2, 4, 6]); deepEqual(_.filter(evenObject, isEven), [2], 'can filter objects'); deepEqual(_.filter([{}, evenObject, []], 'two'), [evenObject], 'predicate string map to object properties'); _.filter([1], function() { equal(this, evenObject, 'given context'); }, evenObject); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; deepEqual(_.filter(list, {a: 1}), [{a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]); deepEqual(_.filter(list, {b: 2}), [{a: 1, b: 2}, {a: 2, b: 2}]); deepEqual(_.filter(list, {}), list, 'Empty object accepts all items'); deepEqual(_(list).filter({}), list, 'OO-filter'); }); test('select', function() { strictEqual(_.filter, _.select, 'alias for filter'); }); test('reject', function() { var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 === 0; }); deepEqual(odds, [1, 3, 5], 'rejected each even number'); var context = 'obj'; var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){ equal(context, 'obj'); return num % 2 !== 0; }, context); deepEqual(evens, [2, 4, 6], 'rejected each odd number'); deepEqual(_.reject([odds, {one: 1, two: 2, three: 3}], 'two'), [odds], 'predicate string map to object properties'); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; deepEqual(_.reject(list, {a: 1}), [{a: 2, b: 2}]); deepEqual(_.reject(list, {b: 2}), [{a: 1, b: 3}, {a: 1, b: 4}]); deepEqual(_.reject(list, {}), [], 'Returns empty list given empty object'); deepEqual(_.reject(list, []), [], 'Returns empty list given empty array'); }); test('every', function() { ok(_.every([], _.identity), 'the empty set'); ok(_.every([true, true, true], _.identity), 'every true values'); ok(!_.every([true, false, true], _.identity), 'one false value'); ok(_.every([0, 10, 28], function(num){ return num % 2 === 0; }), 'even numbers'); ok(!_.every([0, 11, 28], function(num){ return num % 2 === 0; }), 'an odd number'); ok(_.every([1], _.identity) === true, 'cast to boolean - true'); ok(_.every([0], _.identity) === false, 'cast to boolean - false'); ok(!_.every([undefined, undefined, undefined], _.identity), 'works with arrays of undefined'); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; ok(!_.every(list, {a: 1, b: 2}), 'Can be called with object'); ok(_.every(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; ok(_.every(list, {b: 2}), 'Can be called with object'); ok(!_.every(list, 'c'), 'String mapped to object property'); ok(_.every({a: 1, b: 2, c: 3, d: 4}, _.isNumber), 'takes objects'); ok(!_.every({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); ok(_.every(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); ok(!_.every(['a', 'b', 'c', 'd', 'f'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); test('all', function() { strictEqual(_.all, _.every, 'alias for all'); }); test('some', function() { ok(!_.some([]), 'the empty set'); ok(!_.some([false, false, false]), 'all false values'); ok(_.some([false, false, true]), 'one true value'); ok(_.some([null, 0, 'yes', false]), 'a string'); ok(!_.some([null, 0, '', false]), 'falsy values'); ok(!_.some([1, 11, 29], function(num){ return num % 2 === 0; }), 'all odd numbers'); ok(_.some([1, 10, 29], function(num){ return num % 2 === 0; }), 'an even number'); ok(_.some([1], _.identity) === true, 'cast to boolean - true'); ok(_.some([0], _.identity) === false, 'cast to boolean - false'); ok(_.some([false, false, true])); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; ok(!_.some(list, {a: 5, b: 2}), 'Can be called with object'); ok(_.some(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; ok(_.some(list, {b: 2}), 'Can be called with object'); ok(!_.some(list, 'd'), 'String mapped to object property'); ok(_.some({a: '1', b: '2', c: '3', d: '4', e: 6}, _.isNumber), 'takes objects'); ok(!_.some({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); ok(_.some(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); ok(!_.some(['x', 'y', 'z'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); test('any', function() { strictEqual(_.any, _.some, 'alias for any'); }); test('contains', function() { ok(_.contains([1, 2, 3], 2), 'two is in the array'); ok(!_.contains([1, 3, 9], 2), 'two is not in the array'); ok(_.contains({moe: 1, larry: 3, curly: 9}, 3) === true, '_.contains on objects checks their values'); ok(_([1, 2, 3]).contains(2), 'OO-style contains'); }); test('include', function() { strictEqual(_.contains, _.include, 'alias for contains'); }); test('invoke', function() { var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, 'sort'); deepEqual(result[0], [1, 5, 7], 'first array sorted'); deepEqual(result[1], [1, 2, 3], 'second array sorted'); }); test('invoke w/ function reference', function() { var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, Array.prototype.sort); deepEqual(result[0], [1, 5, 7], 'first array sorted'); deepEqual(result[1], [1, 2, 3], 'second array sorted'); }); // Relevant when using ClojureScript test('invoke when strings have a call method', function() { String.prototype.call = function() { return 42; }; var list = [[5, 1, 7], [3, 2, 1]]; var s = 'foo'; equal(s.call(), 42, 'call function exists'); var result = _.invoke(list, 'sort'); deepEqual(result[0], [1, 5, 7], 'first array sorted'); deepEqual(result[1], [1, 2, 3], 'second array sorted'); delete String.prototype.call; equal(s.call, undefined, 'call function removed'); }); test('pluck', function() { var people = [{name: 'moe', age: 30}, {name: 'curly', age: 50}]; deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'pulls names out of objects'); //compat: most flexible handling of edge cases deepEqual(_.pluck([{'[object Object]': 1}], {}), [1]); }); test('where', function() { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; var result = _.where(list, {a: 1}); equal(result.length, 3); equal(result[result.length - 1].b, 4); result = _.where(list, {b: 2}); equal(result.length, 2); equal(result[0].a, 1); result = _.where(list, {}); equal(result.length, list.length); function test() {} test.map = _.map; deepEqual(_.where([_, {a: 1, b: 2}, _], test), [_, _], 'checks properties given function'); }); test('findWhere', function() { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; var result = _.findWhere(list, {a: 1}); deepEqual(result, {a: 1, b: 2}); result = _.findWhere(list, {b: 4}); deepEqual(result, {a: 1, b: 4}); result = _.findWhere(list, {c: 1}); ok(_.isUndefined(result), 'undefined when not found'); result = _.findWhere([], {c: 1}); ok(_.isUndefined(result), 'undefined when searching empty list'); function test() {} test.map = _.map; equal(_.findWhere([_, {a: 1, b: 2}, _], test), _, 'checks properties given function'); function TestClass() { this.y = 5; this.x = 'foo'; } var expect = {c: 1, x: 'foo', y: 5}; deepEqual(_.findWhere([{y: 5, b: 6}, expect], new TestClass()), expect, 'uses class instance properties'); }); test('max', function() { equal(-Infinity, _.max(null), 'can handle null/undefined'); equal(-Infinity, _.max(undefined), 'can handle null/undefined'); equal(-Infinity, _.max(null, _.identity), 'can handle null/undefined'); equal(3, _.max([1, 2, 3]), 'can perform a regular Math.max'); var neg = _.max([1, 2, 3], function(num){ return -num; }); equal(neg, 1, 'can perform a computation-based max'); equal(-Infinity, _.max({}), 'Maximum value of an empty object'); equal(-Infinity, _.max([]), 'Maximum value of an empty array'); equal(_.max({'a': 'a'}), -Infinity, 'Maximum value of a non-numeric collection'); equal(299999, _.max(_.range(1, 300000)), 'Maximum value of a too-big array'); equal(3, _.max([1, 2, 3, 'test']), 'Finds correct max in array starting with num and containing a NaN'); equal(3, _.max(['test', 1, 2, 3]), 'Finds correct max in array starting with NaN'); var a = {x: -Infinity}; var b = {x: -Infinity}; var iterator = function(o){ return o.x; }; equal(_.max([a, b], iterator), a, 'Respects iterator return value of -Infinity'); deepEqual(_.max([{'a': 1}, {'a': 0, 'b': 3}, {'a': 4}, {'a': 2}], 'a'), {'a': 4}, 'String keys use property iterator'); deepEqual(_.max([0, 2], function(a){ return a * this.x; }, {x: 1}), 2, 'Iterator context'); deepEqual(_.max([[1], [2, 3], [-1, 4], [5]], 0), [5], 'Lookup falsy iterator'); deepEqual(_.max([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: 2}, 'Lookup falsy iterator'); }); test('min', function() { equal(Infinity, _.min(null), 'can handle null/undefined'); equal(Infinity, _.min(undefined), 'can handle null/undefined'); equal(Infinity, _.min(null, _.identity), 'can handle null/undefined'); equal(1, _.min([1, 2, 3]), 'can perform a regular Math.min'); var neg = _.min([1, 2, 3], function(num){ return -num; }); equal(neg, 3, 'can perform a computation-based min'); equal(Infinity, _.min({}), 'Minimum value of an empty object'); equal(Infinity, _.min([]), 'Minimum value of an empty array'); equal(_.min({'a': 'a'}), Infinity, 'Minimum value of a non-numeric collection'); var now = new Date(9999999999); var then = new Date(0); equal(_.min([now, then]), then); equal(1, _.min(_.range(1, 300000)), 'Minimum value of a too-big array'); equal(1, _.min([1, 2, 3, 'test']), 'Finds correct min in array starting with num and containing a NaN'); equal(1, _.min(['test', 1, 2, 3]), 'Finds correct min in array starting with NaN'); var a = {x: Infinity}; var b = {x: Infinity}; var iterator = function(o){ return o.x; }; equal(_.min([a, b], iterator), a, 'Respects iterator return value of Infinity'); deepEqual(_.min([{'a': 1}, {'a': 0, 'b': 3}, {'a': 4}, {'a': 2}], 'a'), {'a': 0, 'b': 3}, 'String keys use property iterator'); deepEqual(_.min([0, 2], function(a){ return a * this.x; }, {x: -1}), 2, 'Iterator context'); deepEqual(_.min([[1], [2, 3], [-1, 4], [5]], 0), [-1, 4], 'Lookup falsy iterator'); deepEqual(_.min([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: -1}, 'Lookup falsy iterator'); }); test('sortBy', function() { var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}]; people = _.sortBy(people, function(person){ return person.age; }); deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'stooges sorted by age'); var list = [undefined, 4, 1, undefined, 3, 2]; deepEqual(_.sortBy(list, _.identity), [1, 2, 3, 4, undefined, undefined], 'sortBy with undefined values'); list = ['one', 'two', 'three', 'four', 'five']; var sorted = _.sortBy(list, 'length'); deepEqual(sorted, ['one', 'two', 'four', 'five', 'three'], 'sorted by length'); function Pair(x, y) { this.x = x; this.y = y; } var collection = [ new Pair(1, 1), new Pair(1, 2), new Pair(1, 3), new Pair(1, 4), new Pair(1, 5), new Pair(1, 6), new Pair(2, 1), new Pair(2, 2), new Pair(2, 3), new Pair(2, 4), new Pair(2, 5), new Pair(2, 6), new Pair(undefined, 1), new Pair(undefined, 2), new Pair(undefined, 3), new Pair(undefined, 4), new Pair(undefined, 5), new Pair(undefined, 6) ]; var actual = _.sortBy(collection, function(pair) { return pair.x; }); deepEqual(actual, collection, 'sortBy should be stable'); deepEqual(_.sortBy(collection, 'x'), collection, 'sortBy accepts property string'); list = ['q', 'w', 'e', 'r', 't', 'y']; deepEqual(_.sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses _.identity if iterator is not specified'); }); test('groupBy', function() { var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; }); ok('0' in parity && '1' in parity, 'created a group for each value'); deepEqual(parity[0], [2, 4, 6], 'put each even number in the right group'); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.groupBy(list, 'length'); deepEqual(grouped['3'], ['one', 'two', 'six', 'ten']); deepEqual(grouped['4'], ['four', 'five', 'nine']); deepEqual(grouped['5'], ['three', 'seven', 'eight']); var context = {}; _.groupBy([{}], function(){ ok(this === context); }, context); grouped = _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); equal(grouped.constructor.length, 1); equal(grouped.hasOwnProperty.length, 2); var array = [{}]; _.groupBy(array, function(value, index, obj){ ok(obj === array); }); array = [1, 2, 1, 2, 3]; grouped = _.groupBy(array); equal(grouped['1'].length, 2); equal(grouped['3'].length, 1); var matrix = [ [1, 2], [1, 3], [2, 3] ]; deepEqual(_.groupBy(matrix, 0), {1: [[1, 2], [1, 3]], 2: [[2, 3]]}); deepEqual(_.groupBy(matrix, 1), {2: [[1, 2]], 3: [[1, 3], [2, 3]]}); }); test('indexBy', function() { var parity = _.indexBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); equal(parity.true, 4); equal(parity.false, 5); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.indexBy(list, 'length'); equal(grouped['3'], 'ten'); equal(grouped['4'], 'nine'); equal(grouped['5'], 'eight'); var array = [1, 2, 1, 2, 3]; grouped = _.indexBy(array); equal(grouped['1'], 1); equal(grouped['2'], 2); equal(grouped['3'], 3); }); test('countBy', function() { var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); equal(parity.true, 2); equal(parity.false, 3); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.countBy(list, 'length'); equal(grouped['3'], 4); equal(grouped['4'], 3); equal(grouped['5'], 3); var context = {}; _.countBy([{}], function(){ ok(this === context); }, context); grouped = _.countBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); equal(grouped.constructor, 1); equal(grouped.hasOwnProperty, 2); var array = [{}]; _.countBy(array, function(value, index, obj){ ok(obj === array); }); array = [1, 2, 1, 2, 3]; grouped = _.countBy(array); equal(grouped['1'], 2); equal(grouped['3'], 1); }); test('sortedIndex', function() { var numbers = [10, 20, 30, 40, 50], num = 35; var indexForNum = _.sortedIndex(numbers, num); equal(indexForNum, 3, '35 should be inserted at index 3'); var indexFor30 = _.sortedIndex(numbers, 30); equal(indexFor30, 2, '30 should be inserted at index 2'); var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}]; var iterator = function(obj){ return obj.x; }; strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2); strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3); var context = {1: 2, 2: 3, 3: 4}; iterator = function(obj){ return this[obj]; }; strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1); }); test('shuffle', function() { var numbers = _.range(10); var shuffled = _.shuffle(numbers); notStrictEqual(numbers, shuffled, 'original object is unmodified'); ok(_.every(_.range(10), function() { //appears consistent? return _.every(numbers, _.partial(_.contains, numbers)); }), 'contains the same members before and after shuffle'); shuffled = _.shuffle({a: 1, b: 2, c: 3, d: 4}); equal(shuffled.length, 4); deepEqual(shuffled.sort(), [1, 2, 3, 4], 'works on objects'); }); test('sample', function() { var numbers = _.range(10); var allSampled = _.sample(numbers, 10).sort(); deepEqual(allSampled, numbers, 'contains the same members before and after sample'); allSampled = _.sample(numbers, 20).sort(); deepEqual(allSampled, numbers, 'also works when sampling more objects than are present'); ok(_.contains(numbers, _.sample(numbers)), 'sampling a single element returns something from the array'); strictEqual(_.sample([]), undefined, 'sampling empty array with no number returns undefined'); notStrictEqual(_.sample([], 5), [], 'sampling empty array with a number returns an empty array'); notStrictEqual(_.sample([1, 2, 3], 0), [], 'sampling an array with 0 picks returns an empty array'); deepEqual(_.sample([1, 2], -1), [], 'sampling a negative number of picks returns an empty array'); ok(_.contains([1, 2, 3], _.sample({a: 1, b: 2, c: 3})), 'sample one value from an object'); }); test('toArray', function() { ok(!_.isArray(arguments), 'arguments object is not an array'); ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array'); var a = [1, 2, 3]; ok(_.toArray(a) !== a, 'array is cloned'); deepEqual(_.toArray(a), [1, 2, 3], 'cloned array contains same elements'); var numbers = _.toArray({one : 1, two : 2, three : 3}); deepEqual(numbers, [1, 2, 3], 'object flattened into array'); // test in IE < 9 try { var actual = _.toArray(document.childNodes); } catch(ex) { } ok(_.isArray(actual), 'should not throw converting a node list'); }); test('size', function() { equal(_.size({one : 1, two : 2, three : 3}), 3, 'can compute the size of an object'); equal(_.size([1, 2, 3]), 3, 'can compute the size of an array'); equal(_.size({length: 3, 0: 0, 1: 0, 2: 0}), 3, 'can compute the size of Array-likes'); var func = function() { return _.size(arguments); }; equal(func(1, 2, 3, 4), 4, 'can test the size of the arguments object'); equal(_.size('hello'), 5, 'can compute the size of a string literal'); equal(_.size(new String('hello')), 5, 'can compute the size of string object'); equal(_.size(null), 0, 'handles nulls'); }); test('partition', function() { var list = [0, 1, 2, 3, 4, 5]; deepEqual(_.partition(list, function(x) { return x < 4; }), [[0, 1, 2, 3], [4, 5]], 'handles bool return values'); deepEqual(_.partition(list, function(x) { return x & 1; }), [[1, 3, 5], [0, 2, 4]], 'handles 0 and 1 return values'); deepEqual(_.partition(list, function(x) { return x - 3; }), [[0, 1, 2, 4, 5], [3]], 'handles other numeric return values'); deepEqual(_.partition(list, function(x) { return x > 1 ? null : true; }), [[0, 1], [2, 3, 4, 5]], 'handles null return values'); deepEqual(_.partition(list, function(x) { if (x < 2) return true; }), [[0, 1], [2, 3, 4, 5]], 'handles undefined return values'); deepEqual(_.partition({a: 1, b: 2, c: 3}, function(x) { return x > 1; }), [[2, 3], [1]], 'handles objects'); deepEqual(_.partition(list, function(x, index) { return index % 2; }), [[1, 3, 5], [0, 2, 4]], 'can reference the array index'); deepEqual(_.partition(list, function(x, index, arr) { return x === arr.length - 1; }), [[5], [0, 1, 2, 3, 4]], 'can reference the collection'); // Default iterator deepEqual(_.partition([1, false, true, '']), [[1, true], [false, '']], 'Default iterator'); deepEqual(_.partition([{x: 1}, {x: 0}, {x: 1}], 'x'), [[{x: 1}, {x: 1}], [{x: 0}]], 'Takes a string'); // Context var predicate = function(x){ return x === this.x; }; deepEqual(_.partition([1, 2, 3], predicate, {x: 2}), [[2], [1, 3]], 'partition takes a context argument'); deepEqual(_.partition([{a: 1}, {b: 2}, {a: 1, b: 2}], {a: 1}), [[{a: 1}, {a: 1, b: 2}], [{b: 2}]], 'predicate can be object'); var object = {a: 1}; _.partition(object, function(val, key, obj) { equal(val, 1); equal(key, 'a'); equal(obj, object); equal(this, predicate); }, predicate); }); }()); 1.7.0~dfsg/test/vendor/0000755000000000000000000000000012377203462013543 5ustar rootroot1.7.0~dfsg/test/vendor/runner.js0000644000000000000000000000622512377203462015417 0ustar rootroot/* * QtWebKit-powered headless test runner using PhantomJS * * PhantomJS binaries: http://phantomjs.org/download.html * Requires PhantomJS 1.6+ (1.7+ recommended) * * Run with: * phantomjs runner.js [url-of-your-qunit-testsuite] * * e.g. * phantomjs runner.js http://localhost/qunit/test/index.html */ /*jshint latedef:false */ /*global phantom:false, require:false, console:false, window:false, QUnit:false */ (function() { 'use strict'; var args = require('system').args; // arg[0]: scriptName, args[1...]: arguments if (args.length !== 2) { console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite]'); phantom.exit(1); } var url = args[1], page = require('webpage').create(); function addLogging() { window.document.addEventListener('DOMContentLoaded', function() { var currentTestAssertions = []; QUnit.log(function(details) { var response; // Ignore passing assertions if (details.result) { return; } response = details.message || ''; if (typeof details.expected !== 'undefined') { if (response) { response += ', '; } response += 'expected: ' + details.expected + ', but was: ' + details.actual; if (details.source) { response += '\n' + details.source; } } currentTestAssertions.push('Failed assertion: ' + response); }); QUnit.testDone(function(result) { var i, len, name = result.module + ': ' + result.name; if (result.failed) { console.log('Test failed: ' + name); for (i = 0, len = currentTestAssertions.length; i < len; i++) { console.log(' ' + currentTestAssertions[i]); } } currentTestAssertions.length = 0; }); QUnit.done(function(result) { console.log('Took ' + result.runtime + 'ms to run ' + result.total + ' tests. ' + result.passed + ' passed, ' + result.failed + ' failed.'); if (typeof window.callPhantom === 'function') { window.callPhantom({ 'name': 'QUnit.done', 'data': result }); } }); }, false); } // Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`) page.onConsoleMessage = function(msg) { console.log(msg); }; page.onInitialized = function() { page.evaluate(addLogging); }; page.onCallback = function(message) { var result, failed; if (message) { if (message.name === 'QUnit.done') { result = message.data; failed = !result || result.failed; phantom.exit(failed ? 1 : 0); } } }; page.open(url, function(status) { if (status !== 'success') { console.error('Unable to access network: ' + status); phantom.exit(1); } else { // Cannot do this verification with the 'DOMContentLoaded' handler because it // will be too late to attach it if a page does not have any script tags. var qunitMissing = page.evaluate(function() { return typeof QUnit === 'undefined' || !QUnit; }); if (qunitMissing) { console.error('The `QUnit` object is not present on this page.'); phantom.exit(1); } // Do nothing... the callback mechanism will handle everything! } }); }()); 1.7.0~dfsg/test/vendor/qunit.js0000644000000000000000000016265412377203462015257 0ustar rootroot/** * QUnit v1.12.0 - A JavaScript Unit Testing Framework * * http://qunitjs.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * https://jquery.org/license/ */ (function( window ) { var QUnit, assert, config, onErrorFnPrev, testId = 0, fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, // Keep a local reference to Date (GH-283) Date = window.Date, setTimeout = window.setTimeout, defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { var x = "qunit-test-string"; try { sessionStorage.setItem( x, x ); sessionStorage.removeItem( x ); return true; } catch( e ) { return false; } }()) }, /** * Provides a normalized error string, correcting an issue * with IE 7 (and prior) where Error.prototype.toString is * not properly implemented * * Based on http://es5.github.com/#x15.11.4.4 * * @param {String|Error} error * @return {String} error message */ errorString = function( error ) { var name, message, errorString = error.toString(); if ( errorString.substring( 0, 7 ) === "[object" ) { name = error.name ? error.name.toString() : "Error"; message = error.message ? error.message.toString() : ""; if ( name && message ) { return name + ": " + message; } else if ( name ) { return name; } else if ( message ) { return message; } else { return "Error"; } } else { return errorString; } }, /** * Makes a clone of an object using only Array or Object as base, * and copies over the own enumerable properties. * * @param {Object} obj * @return {Object} New object with only the own properties (recursively). */ objectValues = function( obj ) { // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. /*jshint newcap: false */ var key, val, vals = QUnit.is( "array", obj ) ? [] : {}; for ( key in obj ) { if ( hasOwn.call( obj, key ) ) { val = obj[key]; vals[key] = val === Object(val) ? objectValues(val) : val; } } return vals; }; function Test( settings ) { extend( this, settings ); this.assertions = []; this.testNumber = ++Test.count; } Test.count = 0; Test.prototype = { init: function() { var a, b, li, tests = id( "qunit-tests" ); if ( tests ) { b = document.createElement( "strong" ); b.innerHTML = this.nameHtml; // `a` initialized at top of scope a = document.createElement( "a" ); a.innerHTML = "Rerun"; a.href = QUnit.url({ testNumber: this.testNumber }); li = document.createElement( "li" ); li.appendChild( b ); li.appendChild( a ); li.className = "running"; li.id = this.id = "qunit-test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if ( // Emit moduleStart when we're switching from one module to another this.module !== config.previousModule || // They could be equal (both undefined) but if the previousModule property doesn't // yet exist it means this is the first test in a suite that isn't wrapped in a // module, in which case we'll just emit a moduleStart event for 'undefined'. // Without this, reporters can get testStart before moduleStart which is a problem. !hasOwn.call( config, "previousModule" ) ) { if ( hasOwn.call( config, "previousModule" ) ) { runLoggingCallbacks( "moduleDone", QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( "moduleStart", QUnit, { name: this.module }); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment ); this.started = +new Date(); runLoggingCallbacks( "testStart", QUnit, { name: this.testName, module: this.module }); /*jshint camelcase:false */ /** * Expose the current test environment. * * @deprecated since 1.12.0: Use QUnit.config.current.testEnvironment instead. */ QUnit.current_testEnvironment = this.testEnvironment; /*jshint camelcase:true */ if ( !config.pollution ) { saveGlobal(); } if ( config.notrycatch ) { this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); return; } try { this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); } catch( e ) { QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); } }, run: function() { config.current = this; var running = id( "qunit-testresult" ); if ( running ) { running.innerHTML = "Running:
" + this.nameHtml; } if ( this.async ) { QUnit.stop(); } this.callbackStarted = +new Date(); if ( config.notrycatch ) { this.callback.call( this.testEnvironment, QUnit.assert ); this.callbackRuntime = +new Date() - this.callbackStarted; return; } try { this.callback.call( this.testEnvironment, QUnit.assert ); this.callbackRuntime = +new Date() - this.callbackStarted; } catch( e ) { this.callbackRuntime = +new Date() - this.callbackStarted; QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; if ( config.notrycatch ) { if ( typeof this.callbackRuntime === "undefined" ) { this.callbackRuntime = +new Date() - this.callbackStarted; } this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); return; } else { try { this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); } catch( e ) { QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); } } checkPollution(); }, finish: function() { config.current = this; if ( config.requireExpects && this.expected === null ) { QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); } else if ( this.expected !== null && this.expected !== this.assertions.length ) { QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); } else if ( this.expected === null && !this.assertions.length ) { QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); } var i, assertion, a, b, time, li, ol, test = this, good = 0, bad = 0, tests = id( "qunit-tests" ); this.runtime = +new Date() - this.started; config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { ol = document.createElement( "ol" ); ol.className = "qunit-assert-list"; for ( i = 0; i < this.assertions.length; i++ ) { assertion = this.assertions[i]; li = document.createElement( "li" ); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if ( QUnit.config.reorder && defined.sessionStorage ) { if ( bad ) { sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); } else { sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); } } if ( bad === 0 ) { addClass( ol, "qunit-collapsed" ); } // `b` initialized at top of scope b = document.createElement( "strong" ); b.innerHTML = this.nameHtml + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; addEvent(b, "click", function() { var next = b.parentNode.lastChild, collapsed = hasClass( next, "qunit-collapsed" ); ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" ); }); addEvent(b, "dblclick", function( e ) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location = QUnit.url({ testNumber: test.testNumber }); } }); // `time` initialized at top of scope time = document.createElement( "span" ); time.className = "runtime"; time.innerHTML = this.runtime + " ms"; // `li` initialized at top of scope li = id( this.id ); li.className = bad ? "fail" : "pass"; li.removeChild( li.firstChild ); a = li.firstChild; li.appendChild( b ); li.appendChild( a ); li.appendChild( time ); li.appendChild( ol ); } else { for ( i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } runLoggingCallbacks( "testDone", QUnit, { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length, duration: this.runtime }); QUnit.reset(); config.current = undefined; }, queue: function() { var bad, test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // `bad` initialized at top of scope // defer when previous test run passed, if storage is available bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); if ( bad ) { run(); } else { synchronize( run, true ); } } }; // Root QUnit object. // `QUnit` initialized at top of scope QUnit = { // call on start of module test to prepend name to all tests module: function( name, testEnvironment ) { config.currentModule = name; config.currentModuleTestEnvironment = testEnvironment; config.modules[name] = true; }, asyncTest: function( testName, expected, callback ) { if ( arguments.length === 2 ) { callback = expected; expected = null; } QUnit.test( testName, expected, callback, true ); }, test: function( testName, expected, callback, async ) { var test, nameHtml = "" + escapeText( testName ) + ""; if ( arguments.length === 2 ) { callback = expected; expected = null; } if ( config.currentModule ) { nameHtml = "" + escapeText( config.currentModule ) + ": " + nameHtml; } test = new Test({ nameHtml: nameHtml, testName: testName, expected: expected, async: async, callback: callback, module: config.currentModule, moduleTestEnvironment: config.currentModuleTestEnvironment, stack: sourceFromStacktrace( 2 ) }); if ( !validTest( test ) ) { return; } test.queue(); }, // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through. expect: function( asserts ) { if (arguments.length === 1) { config.current.expected = asserts; } else { return config.current.expected; } }, start: function( count ) { // QUnit hasn't been initialized yet. // Note: RequireJS (et al) may delay onLoad if ( config.semaphore === undefined ) { QUnit.begin(function() { // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first setTimeout(function() { QUnit.start( count ); }); }); return; } config.semaphore -= count || 1; // don't start until equal number of stop-calls if ( config.semaphore > 0 ) { return; } // ignore if start is called more often then stop if ( config.semaphore < 0 ) { config.semaphore = 0; QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) ); return; } // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { setTimeout(function() { if ( config.semaphore > 0 ) { return; } if ( config.timeout ) { clearTimeout( config.timeout ); } config.blocking = false; process( true ); }, 13); } else { config.blocking = false; process( true ); } }, stop: function( count ) { config.semaphore += count || 1; config.blocking = true; if ( config.testTimeout && defined.setTimeout ) { clearTimeout( config.timeout ); config.timeout = setTimeout(function() { QUnit.ok( false, "Test timed out" ); config.semaphore = 1; QUnit.start(); }, config.testTimeout ); } } }; // `assert` initialized at top of scope // Assert helpers // All of these must either call QUnit.push() or manually do: // - runLoggingCallbacks( "log", .. ); // - config.current.assertions.push({ .. }); // We attach it to the QUnit object *after* we expose the public API, // otherwise `assert` will become a global variable in browsers (#341). assert = { /** * Asserts rough true-ish result. * @name ok * @function * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function( result, msg ) { if ( !config.current ) { throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); } result = !!result; msg = msg || (result ? "okay" : "failed" ); var source, details = { module: config.current.module, name: config.current.testName, result: result, message: msg }; msg = "" + escapeText( msg ) + ""; if ( !result ) { source = sourceFromStacktrace( 2 ); if ( source ) { details.source = source; msg += "
Source:
" + escapeText( source ) + "
"; } } runLoggingCallbacks( "log", QUnit, details ); config.current.assertions.push({ result: result, message: msg }); }, /** * Assert that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * @name equal * @function * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); */ equal: function( actual, expected, message ) { /*jshint eqeqeq:false */ QUnit.push( expected == actual, actual, expected, message ); }, /** * @name notEqual * @function */ notEqual: function( actual, expected, message ) { /*jshint eqeqeq:false */ QUnit.push( expected != actual, actual, expected, message ); }, /** * @name propEqual * @function */ propEqual: function( actual, expected, message ) { actual = objectValues(actual); expected = objectValues(expected); QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name notPropEqual * @function */ notPropEqual: function( actual, expected, message ) { actual = objectValues(actual); expected = objectValues(expected); QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name deepEqual * @function */ deepEqual: function( actual, expected, message ) { QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name notDeepEqual * @function */ notDeepEqual: function( actual, expected, message ) { QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); }, /** * @name strictEqual * @function */ strictEqual: function( actual, expected, message ) { QUnit.push( expected === actual, actual, expected, message ); }, /** * @name notStrictEqual * @function */ notStrictEqual: function( actual, expected, message ) { QUnit.push( expected !== actual, actual, expected, message ); }, "throws": function( block, expected, message ) { var actual, expectedOutput = expected, ok = false; // 'expected' is optional if ( typeof expected === "string" ) { message = expected; expected = null; } config.current.ignoreGlobalErrors = true; try { block.call( config.current.testEnvironment ); } catch (e) { actual = e; } config.current.ignoreGlobalErrors = false; if ( actual ) { // we don't want to validate thrown error if ( !expected ) { ok = true; expectedOutput = null; // expected is a regexp } else if ( QUnit.objectType( expected ) === "regexp" ) { ok = expected.test( errorString( actual ) ); // expected is a constructor } else if ( actual instanceof expected ) { ok = true; // expected is a validation function which returns true is validation passed } else if ( expected.call( {}, actual ) === true ) { expectedOutput = null; ok = true; } QUnit.push( ok, actual, expectedOutput, message ); } else { QUnit.pushFailure( message, null, "No exception was thrown." ); } } }; /** * @deprecated since 1.8.0 * Kept assertion helpers in root for backwards compatibility. */ extend( QUnit, assert ); /** * @deprecated since 1.9.0 * Kept root "raises()" for backwards compatibility. * (Note that we don't introduce assert.raises). */ QUnit.raises = assert[ "throws" ]; /** * @deprecated since 1.0.0, replaced with error pushes since 1.3.0 * Kept to avoid TypeErrors for undefined methods. */ QUnit.equals = function() { QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); }; QUnit.same = function() { QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); }; // We want access to the constructor's prototype (function() { function F() {} F.prototype = QUnit; QUnit = new F(); // Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; }()); /** * Config object: Maintain internal state * Later exposed as QUnit.config * `config` initialized at top of scope */ config = { // The queue of tests to run queue: [], // block until document ready blocking: true, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, // when enabled, all tests must call expect() requireExpects: false, // add checkboxes that are persisted in the query-string // when enabled, the id is set to `true` as a `QUnit.config` property urlConfig: [ { id: "noglobals", label: "Check for Globals", tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." }, { id: "notrycatch", label: "No try-catch", tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." } ], // Set of all modules. modules: {}, // logging callback queues begin: [], done: [], log: [], testStart: [], testDone: [], moduleStart: [], moduleDone: [] }; // Export global variables, unless an 'exports' object exists, // in that case we assume we're in CommonJS (dealt with on the bottom of the script) if ( typeof exports === "undefined" ) { extend( window, QUnit.constructor.prototype ); // Expose QUnit object window.QUnit = QUnit; } // Initialize more QUnit.config and QUnit.urlParams (function() { var i, location = window.location || { search: "", protocol: "file:" }, params = location.search.slice( 1 ).split( "&" ), length = params.length, urlParams = {}, current; if ( params[ 0 ] ) { for ( i = 0; i < length; i++ ) { current = params[ i ].split( "=" ); current[ 0 ] = decodeURIComponent( current[ 0 ] ); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; urlParams[ current[ 0 ] ] = current[ 1 ]; } } QUnit.urlParams = urlParams; // String search anywhere in moduleName+testName config.filter = urlParams.filter; // Exact match of the module name config.module = urlParams.module; config.testNumber = parseInt( urlParams.testNumber, 10 ) || null; // Figure out if we're running the tests from a server or not QUnit.isLocal = location.protocol === "file:"; }()); // Extend QUnit object, // these after set here because they should not be exposed as global functions extend( QUnit, { assert: assert, config: config, // Initialize the configuration options init: function() { extend( config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date(), updateRate: 1000, blocking: false, autostart: true, autorun: false, filter: "", queue: [], semaphore: 1 }); var tests, banner, result, qunit = id( "qunit" ); if ( qunit ) { qunit.innerHTML = "

" + escapeText( document.title ) + "

" + "

" + "
" + "

" + "
    "; } tests = id( "qunit-tests" ); banner = id( "qunit-banner" ); result = id( "qunit-testresult" ); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } if ( tests ) { result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = "Running...
     "; } }, // Resets the test setup. Useful for tests that modify the DOM. /* DEPRECATED: Use multiple tests instead of resetting inside a test. Use testStart or testDone for custom cleanup. This method will throw an error in 2.0, and will be removed in 2.1 */ reset: function() { var fixture = id( "qunit-fixture" ); if ( fixture ) { fixture.innerHTML = config.fixture; } }, // Trigger an event on an element. // @example triggerEvent( document.body, "click" ); triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent( "MouseEvents" ); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent( "on" + type ); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) === type; }, objectType: function( obj ) { if ( typeof obj === "undefined" ) { return "undefined"; // consider: typeof null === object } if ( obj === null ) { return "null"; } var match = toString.call( obj ).match(/^\[object\s(.*)\]$/), type = match && match[1] || ""; switch ( type ) { case "Number": if ( isNaN(obj) ) { return "nan"; } return "number"; case "String": case "Boolean": case "Array": case "Date": case "RegExp": case "Function": return type.toLowerCase(); } if ( typeof obj === "object" ) { return "object"; } return undefined; }, push: function( result, actual, expected, message ) { if ( !config.current ) { throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); } var output, source, details = { module: config.current.module, name: config.current.testName, result: result, message: message, actual: actual, expected: expected }; message = escapeText( message ) || ( result ? "okay" : "failed" ); message = "" + message + ""; output = message; if ( !result ) { expected = escapeText( QUnit.jsDump.parse(expected) ); actual = escapeText( QUnit.jsDump.parse(actual) ); output += ""; if ( actual !== expected ) { output += ""; output += ""; } source = sourceFromStacktrace(); if ( source ) { details.source = source; output += ""; } output += "
    Expected:
    " + expected + "
    Result:
    " + actual + "
    Diff:
    " + QUnit.diff( expected, actual ) + "
    Source:
    " + escapeText( source ) + "
    "; } runLoggingCallbacks( "log", QUnit, details ); config.current.assertions.push({ result: !!result, message: output }); }, pushFailure: function( message, source, actual ) { if ( !config.current ) { throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); } var output, details = { module: config.current.module, name: config.current.testName, result: false, message: message }; message = escapeText( message ) || "error"; message = "" + message + ""; output = message; output += ""; if ( actual ) { output += ""; } if ( source ) { details.source = source; output += ""; } output += "
    Result:
    " + escapeText( actual ) + "
    Source:
    " + escapeText( source ) + "
    "; runLoggingCallbacks( "log", QUnit, details ); config.current.assertions.push({ result: false, message: output }); }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var key, querystring = "?"; for ( key in params ) { if ( hasOwn.call( params, key ) ) { querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } } return window.location.protocol + "//" + window.location.host + window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend, id: id, addEvent: addEvent, addClass: addClass, hasClass: hasClass, removeClass: removeClass // load, equiv, jsDump, diff: Attached later }); /** * @deprecated: Created for backwards compatibility with test runner that set the hook function * into QUnit.{hook}, instead of invoking it and passing the hook function. * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. * Doing this allows us to tell if the following methods have been overwritten on the actual * QUnit object. */ extend( QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback( "begin" ), // done: { failed, passed, total, runtime } done: registerLoggingCallback( "done" ), // log: { result, actual, expected, message } log: registerLoggingCallback( "log" ), // testStart: { name } testStart: registerLoggingCallback( "testStart" ), // testDone: { name, failed, passed, total, duration } testDone: registerLoggingCallback( "testDone" ), // moduleStart: { name } moduleStart: registerLoggingCallback( "moduleStart" ), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback( "moduleDone" ) }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks( "begin", QUnit, {} ); // Initialize the config, saving the execution queue var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, urlConfigCheckboxesContainer, urlConfigCheckboxes, moduleFilter, numModules = 0, moduleNames = [], moduleFilterHtml = "", urlConfigHtml = "", oldconfig = extend( {}, config ); QUnit.init(); extend(config, oldconfig); config.blocking = false; len = config.urlConfig.length; for ( i = 0; i < len; i++ ) { val = config.urlConfig[i]; if ( typeof val === "string" ) { val = { id: val, label: val, tooltip: "[no tooltip available]" }; } config[ val.id ] = QUnit.urlParams[ val.id ]; urlConfigHtml += ""; } for ( i in config.modules ) { if ( config.modules.hasOwnProperty( i ) ) { moduleNames.push(i); } } numModules = moduleNames.length; moduleNames.sort( function( a, b ) { return a.localeCompare( b ); }); moduleFilterHtml += ""; // `userAgent` initialized at top of scope userAgent = id( "qunit-userAgent" ); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } // `banner` initialized at top of scope banner = id( "qunit-header" ); if ( banner ) { banner.innerHTML = "" + banner.innerHTML + " "; } // `toolbar` initialized at top of scope toolbar = id( "qunit-testrunner-toolbar" ); if ( toolbar ) { // `filter` initialized at top of scope filter = document.createElement( "input" ); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { var tmp, ol = document.getElementById( "qunit-tests" ); if ( filter.checked ) { ol.className = ol.className + " hidepass"; } else { tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; ol.className = tmp.replace( / hidepass /, " " ); } if ( defined.sessionStorage ) { if (filter.checked) { sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); } else { sessionStorage.removeItem( "qunit-filter-passed-tests" ); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { filter.checked = true; // `ol` initialized at top of scope ol = document.getElementById( "qunit-tests" ); ol.className = ol.className + " hidepass"; } toolbar.appendChild( filter ); // `label` initialized at top of scope label = document.createElement( "label" ); label.setAttribute( "for", "qunit-filter-pass" ); label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." ); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); urlConfigCheckboxesContainer = document.createElement("span"); urlConfigCheckboxesContainer.innerHTML = urlConfigHtml; urlConfigCheckboxes = urlConfigCheckboxesContainer.getElementsByTagName("input"); // For oldIE support: // * Add handlers to the individual elements instead of the container // * Use "click" instead of "change" // * Fallback from event.target to event.srcElement addEvents( urlConfigCheckboxes, "click", function( event ) { var params = {}, target = event.target || event.srcElement; params[ target.name ] = target.checked ? true : undefined; window.location = QUnit.url( params ); }); toolbar.appendChild( urlConfigCheckboxesContainer ); if (numModules > 1) { moduleFilter = document.createElement( "span" ); moduleFilter.setAttribute( "id", "qunit-modulefilter-container" ); moduleFilter.innerHTML = moduleFilterHtml; addEvent( moduleFilter.lastChild, "change", function() { var selectBox = moduleFilter.getElementsByTagName("select")[0], selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value); window.location = QUnit.url({ module: ( selectedModule === "" ) ? undefined : selectedModule, // Remove any existing filters filter: undefined, testNumber: undefined }); }); toolbar.appendChild(moduleFilter); } } // `main` initialized at top of scope main = id( "qunit-fixture" ); if ( main ) { config.fixture = main.innerHTML; } if ( config.autostart ) { QUnit.start(); } }; addEvent( window, "load", QUnit.load ); // `onErrorFnPrev` initialized at top of scope // Preserve other handlers onErrorFnPrev = window.onerror; // Cover uncaught exceptions // Returning true will suppress the default browser handler, // returning false will let it run. window.onerror = function ( error, filePath, linerNr ) { var ret = false; if ( onErrorFnPrev ) { ret = onErrorFnPrev( error, filePath, linerNr ); } // Treat return value as window.onerror itself does, // Only do our handling if not suppressed. if ( ret !== true ) { if ( QUnit.config.current ) { if ( QUnit.config.current.ignoreGlobalErrors ) { return true; } QUnit.pushFailure( error, filePath + ":" + linerNr ); } else { QUnit.test( "global failure", extend( function() { QUnit.pushFailure( error, filePath + ":" + linerNr ); }, { validTest: validTest } ) ); } return false; } return ret; }; function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { runLoggingCallbacks( "moduleDone", QUnit, { name: config.currentModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } delete config.previousModule; var i, key, banner = id( "qunit-banner" ), tests = id( "qunit-tests" ), runtime = +new Date() - config.started, passed = config.stats.all - config.stats.bad, html = [ "Tests completed in ", runtime, " milliseconds.
    ", "", passed, " assertions of ", config.stats.all, " passed, ", config.stats.bad, " failed." ].join( "" ); if ( banner ) { banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); } if ( tests ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && typeof document !== "undefined" && document.title ) { // show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ ( config.stats.bad ? "\u2716" : "\u2714" ), document.title.replace( /^[\u2714\u2716] /i, "" ) ].join( " " ); } // clear own sessionStorage items if all tests passed if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { // `key` & `i` initialized at top of scope for ( i = 0; i < sessionStorage.length; i++ ) { key = sessionStorage.key( i++ ); if ( key.indexOf( "qunit-test-" ) === 0 ) { sessionStorage.removeItem( key ); } } } // scroll back to top to show results if ( window.scrollTo ) { window.scrollTo(0, 0); } runLoggingCallbacks( "done", QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime }); } /** @return Boolean: true if this test should be ran */ function validTest( test ) { var include, filter = config.filter && config.filter.toLowerCase(), module = config.module && config.module.toLowerCase(), fullName = (test.module + ": " + test.testName).toLowerCase(); // Internally-generated tests are always valid if ( test.callback && test.callback.validTest === validTest ) { delete test.callback.validTest; return true; } if ( config.testNumber ) { return test.testNumber === config.testNumber; } if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { return false; } if ( !filter ) { return true; } include = filter.charAt( 0 ) !== "!"; if ( !include ) { filter = filter.slice( 1 ); } // If the filter matches, we need to honour include if ( fullName.indexOf( filter ) !== -1 ) { return include; } // Otherwise, do the opposite return !include; } // so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) // Later Safari and IE10 are supposed to support error.stack as well // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack function extractStacktrace( e, offset ) { offset = offset === undefined ? 3 : offset; var stack, include, i; if ( e.stacktrace ) { // Opera return e.stacktrace.split( "\n" )[ offset + 3 ]; } else if ( e.stack ) { // Firefox, Chrome stack = e.stack.split( "\n" ); if (/^error$/i.test( stack[0] ) ) { stack.shift(); } if ( fileName ) { include = []; for ( i = offset; i < stack.length; i++ ) { if ( stack[ i ].indexOf( fileName ) !== -1 ) { break; } include.push( stack[ i ] ); } if ( include.length ) { return include.join( "\n" ); } } return stack[ offset ]; } else if ( e.sourceURL ) { // Safari, PhantomJS // hopefully one day Safari provides actual stacktraces // exclude useless self-reference for generated Error objects if ( /qunit.js$/.test( e.sourceURL ) ) { return; } // for actual exceptions, this is useful return e.sourceURL + ":" + e.line; } } function sourceFromStacktrace( offset ) { try { throw new Error(); } catch ( e ) { return extractStacktrace( e, offset ); } } /** * Escape text for attribute or text content. */ function escapeText( s ) { if ( !s ) { return ""; } s = s + ""; // Both single quotes and double quotes (for attributes) return s.replace( /['"<>&]/g, function( s ) { switch( s ) { case "'": return "'"; case "\"": return """; case "<": return "<"; case ">": return ">"; case "&": return "&"; } }); } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process( last ); } } function process( last ) { function next() { process( last ); } var start = new Date().getTime(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { setTimeout( next, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( hasOwn.call( window, key ) ) { // in Opera sometimes DOM element ids show up here, ignore them if ( /^qunit-test-output/.test( key ) ) { continue; } config.pollution.push( key ); } } } } function checkPollution() { var newGlobals, deletedGlobals, old = config.pollution; saveGlobal(); newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); } deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var i, j, result = a.slice(); for ( i = 0; i < result.length; i++ ) { for ( j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice( i, 1 ); i--; break; } } } return result; } function extend( a, b ) { for ( var prop in b ) { if ( hasOwn.call( b, prop ) ) { // Avoid "Member not found" error in IE8 caused by messing with window.constructor if ( !( prop === "constructor" && a === window ) ) { if ( b[ prop ] === undefined ) { delete a[ prop ]; } else { a[ prop ] = b[ prop ]; } } } } return a; } /** * @param {HTMLElement} elem * @param {string} type * @param {Function} fn */ function addEvent( elem, type, fn ) { // Standards-based browsers if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); // IE } else { elem.attachEvent( "on" + type, fn ); } } /** * @param {Array|NodeList} elems * @param {string} type * @param {Function} fn */ function addEvents( elems, type, fn ) { var i = elems.length; while ( i-- ) { addEvent( elems[i], type, fn ); } } function hasClass( elem, name ) { return (" " + elem.className + " ").indexOf(" " + name + " ") > -1; } function addClass( elem, name ) { if ( !hasClass( elem, name ) ) { elem.className += (elem.className ? " " : "") + name; } } function removeClass( elem, name ) { var set = " " + elem.className + " "; // Class name may appear multiple times while ( set.indexOf(" " + name + " ") > -1 ) { set = set.replace(" " + name + " " , " "); } // If possible, trim it for prettiness, but not necessarily elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, ""); } function id( name ) { return !!( typeof document !== "undefined" && document && document.getElementById ) && document.getElementById( name ); } function registerLoggingCallback( key ) { return function( callback ) { config[key].push( callback ); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks( key, scope, args ) { var i, callbacks; if ( QUnit.hasOwnProperty( key ) ) { QUnit[ key ].call(scope, args ); } else { callbacks = config[ key ]; for ( i = 0; i < callbacks.length; i++ ) { callbacks[ i ].call( scope, args ); } } } // Test for equality any JavaScript type. // Author: Philippe Rathé QUnit.equiv = (function() { // Call the o related callback with the given arguments. function bindCallbacks( o, callbacks, args ) { var prop = QUnit.objectType( o ); if ( prop ) { if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { return callbacks[ prop ].apply( callbacks, args ); } else { return callbacks[ prop ]; // or undefined } } } // the real equiv function var innerEquiv, // stack to decide between skip/abort functions callers = [], // stack to avoiding loops from circular referencing parents = [], parentsB = [], getProto = Object.getPrototypeOf || function ( obj ) { /*jshint camelcase:false */ return obj.__proto__; }, callbacks = (function () { // for string, boolean, number and null function useStrictEquality( b, a ) { /*jshint eqeqeq:false */ if ( b instanceof a.constructor || a instanceof b.constructor ) { // to catch short annotation VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function( b ) { return isNaN( b ); }, "date": function( b, a ) { return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function( b, a ) { return QUnit.objectType( b ) === "regexp" && // the regex itself a.source === b.source && // and its modifiers a.global === b.global && // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function() { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function( b, a ) { var i, j, len, loop, aCircular, bCircular; // b could be an object literal here if ( QUnit.objectType( b ) !== "array" ) { return false; } len = a.length; if ( len !== b.length ) { // safe and faster return false; } // track reference to avoid circular references parents.push( a ); parentsB.push( b ); for ( i = 0; i < len; i++ ) { loop = false; for ( j = 0; j < parents.length; j++ ) { aCircular = parents[j] === a[i]; bCircular = parentsB[j] === b[i]; if ( aCircular || bCircular ) { if ( a[i] === b[i] || aCircular && bCircular ) { loop = true; } else { parents.pop(); parentsB.pop(); return false; } } } if ( !loop && !innerEquiv(a[i], b[i]) ) { parents.pop(); parentsB.pop(); return false; } } parents.pop(); parentsB.pop(); return true; }, "object": function( b, a ) { /*jshint forin:false */ var i, j, loop, aCircular, bCircular, // Default to true eq = true, aProperties = [], bProperties = []; // comparing constructors is more strict than using // instanceof if ( a.constructor !== b.constructor ) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { return false; } } // stack constructor before traversing properties callers.push( a.constructor ); // track reference to avoid circular references parents.push( a ); parentsB.push( b ); // be strict: don't ensure hasOwnProperty and go deep for ( i in a ) { loop = false; for ( j = 0; j < parents.length; j++ ) { aCircular = parents[j] === a[i]; bCircular = parentsB[j] === b[i]; if ( aCircular || bCircular ) { if ( a[i] === b[i] || aCircular && bCircular ) { loop = true; } else { eq = false; break; } } } aProperties.push(i); if ( !loop && !innerEquiv(a[i], b[i]) ) { eq = false; break; } } parents.pop(); parentsB.pop(); callers.pop(); // unstack, we are done for ( i in b ) { bProperties.push( i ); // collect b's properties } // Ensures identical properties name return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); } }; }()); innerEquiv = function() { // can take multiple arguments var args = [].slice.apply( arguments ); if ( args.length < 2 ) { return true; // end transition } return (function( a, b ) { if ( a === b ) { return true; // catch the most you can } else if ( a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b) ) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [ b, a ]); } // apply transition with (1..n) arguments }( args[0], args[1] ) && innerEquiv.apply( this, args.splice(1, args.length - 1 )) ); }; return innerEquiv; }()); /** * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | * http://flesler.blogspot.com Licensed under BSD * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 * * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\""; } function literal( o ) { return o + ""; } function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) { arr = arr.join( "," + s + inner ); } if ( !arr ) { return pre + post; } return [ pre, inner + arr, base + post ].join(s); } function array( arr, stack ) { var i = arr.length, ret = new Array(i); this.up(); while ( i-- ) { ret[i] = this.parse( arr[i] , undefined , stack); } this.down(); return join( "[", ret, "]" ); } var reName = /^function (\w+)/, jsDump = { // type is used mostly internally, you can fix a (custom)type in advance parse: function( obj, type, stack ) { stack = stack || [ ]; var inStack, res, parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; inStack = inArray( obj, stack ); if ( inStack !== -1 ) { return "recursion(" + (inStack - stack.length) + ")"; } if ( type === "function" ) { stack.push( obj ); res = parser.call( this, obj, stack ); stack.pop(); return res; } return ( type === "string" ) ? parser : this.parsers.error; }, typeOf: function( obj ) { var type; if ( obj === null ) { type = "null"; } else if ( typeof obj === "undefined" ) { type = "undefined"; } else if ( QUnit.is( "regexp", obj) ) { type = "regexp"; } else if ( QUnit.is( "date", obj) ) { type = "date"; } else if ( QUnit.is( "function", obj) ) { type = "function"; } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { type = "window"; } else if ( obj.nodeType === 9 ) { type = "document"; } else if ( obj.nodeType ) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) ) { type = "array"; } else if ( obj.constructor === Error.prototype.constructor ) { type = "error"; } else { type = typeof obj; } return type; }, separator: function() { return this.multiline ? this.HTML ? "
    " : "\n" : this.HTML ? " " : " "; }, // extra can be a number, shortcut for increasing-calling-decreasing indent: function( extra ) { if ( !this.multiline ) { return ""; } var chr = this.indentChar; if ( this.HTML ) { chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); } return new Array( this.depth + ( extra || 0 ) ).join(chr); }, up: function( a ) { this.depth += a || 1; }, down: function( a ) { this.depth -= a || 1; }, setParser: function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote: quote, literal: literal, join: join, // depth: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers: { window: "[Window]", document: "[Document]", error: function(error) { return "Error(\"" + error.message + "\")"; }, unknown: "[Unknown]", "null": "null", "undefined": "undefined", "function": function( fn ) { var ret = "function", // functions never have name in IE name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1]; if ( name ) { ret += " " + name; } ret += "( "; ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); }, array: array, nodelist: array, "arguments": array, object: function( map, stack ) { /*jshint forin:false */ var ret = [ ], keys, key, val, i; QUnit.jsDump.up(); keys = []; for ( key in map ) { keys.push( key ); } keys.sort(); for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; val = map[ key ]; ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); } QUnit.jsDump.down(); return join( "{", ret, "}" ); }, node: function( node ) { var len, i, val, open = QUnit.jsDump.HTML ? "<" : "<", close = QUnit.jsDump.HTML ? ">" : ">", tag = node.nodeName.toLowerCase(), ret = open + tag, attrs = node.attributes; if ( attrs ) { for ( i = 0, len = attrs.length; i < len; i++ ) { val = attrs[i].nodeValue; // IE6 includes all attributes in .attributes, even ones not explicitly set. // Those have values like undefined, null, 0, false, "" or "inherit". if ( val && val !== "inherit" ) { ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" ); } } } ret += close; // Show content of TextNode or CDATASection if ( node.nodeType === 3 || node.nodeType === 4 ) { ret += node.nodeValue; } return ret + open + "/" + tag + close; }, // function calls it internally, it's the arguments part of the function functionArgs: function( fn ) { var args, l = fn.length; if ( !l ) { return ""; } args = new Array(l); while ( l-- ) { // 97 is 'a' args[l] = String.fromCharCode(97+l); } return " " + args.join( ", " ) + " "; }, // object calls it internally, the key part of an item in a map key: quote, // function calls it internally, it's the content of the function functionCode: "[code]", // node calls it internally, it's an html attribute value attribute: quote, string: quote, date: quote, regexp: literal, number: literal, "boolean": literal }, // if true, entities are escaped ( <, >, \t, space and \n ) HTML: false, // indentation unit indentChar: " ", // if true, items in a collection, are separated by a \n, else just a space. multiline: true }; return jsDump; }()); // from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over" */ QUnit.diff = (function() { /*jshint eqeqeq:false, eqnull:true */ function diff( o, n ) { var i, ns = {}, os = {}; for ( i = 0; i < n.length; i++ ) { if ( !hasOwn.call( ns, n[i] ) ) { ns[ n[i] ] = { rows: [], o: null }; } ns[ n[i] ].rows.push( i ); } for ( i = 0; i < o.length; i++ ) { if ( !hasOwn.call( os, o[i] ) ) { os[ o[i] ] = { rows: [], n: null }; } os[ o[i] ].rows.push( i ); } for ( i in ns ) { if ( hasOwn.call( ns, i ) ) { if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) { n[ ns[i].rows[0] ] = { text: n[ ns[i].rows[0] ], row: os[i].rows[0] }; o[ os[i].rows[0] ] = { text: o[ os[i].rows[0] ], row: ns[i].rows[0] }; } } } for ( i = 0; i < n.length - 1; i++ ) { if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && n[ i + 1 ] == o[ n[i].row + 1 ] ) { n[ i + 1 ] = { text: n[ i + 1 ], row: n[i].row + 1 }; o[ n[i].row + 1 ] = { text: o[ n[i].row + 1 ], row: i + 1 }; } } for ( i = n.length - 1; i > 0; i-- ) { if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && n[ i - 1 ] == o[ n[i].row - 1 ]) { n[ i - 1 ] = { text: n[ i - 1 ], row: n[i].row - 1 }; o[ n[i].row - 1 ] = { text: o[ n[i].row - 1 ], row: i - 1 }; } } return { o: o, n: n }; } return function( o, n ) { o = o.replace( /\s+$/, "" ); n = n.replace( /\s+$/, "" ); var i, pre, str = "", out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), oSpace = o.match(/\s+/g), nSpace = n.match(/\s+/g); if ( oSpace == null ) { oSpace = [ " " ]; } else { oSpace.push( " " ); } if ( nSpace == null ) { nSpace = [ " " ]; } else { nSpace.push( " " ); } if ( out.n.length === 0 ) { for ( i = 0; i < out.o.length; i++ ) { str += "" + out.o[i] + oSpace[i] + ""; } } else { if ( out.n[0].text == null ) { for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { str += "" + out.o[n] + oSpace[n] + ""; } } for ( i = 0; i < out.n.length; i++ ) { if (out.n[i].text == null) { str += "" + out.n[i] + nSpace[i] + ""; } else { // `pre` initialized at top of scope pre = ""; for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { pre += "" + out.o[n] + oSpace[n] + ""; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; }()); // for CommonJS environments, export everything if ( typeof exports !== "undefined" ) { extend( exports, QUnit.constructor.prototype ); } // get at whatever the global object is, like window in browsers }( (function() {return this;}.call()) )); 1.7.0~dfsg/test/vendor/qunit.css0000644000000000000000000001107412377203462015420 0ustar rootroot/** * QUnit v1.12.0 - A JavaScript Unit Testing Framework * * http://qunitjs.com * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ /** Font Family and Sizes */ #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; } #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } #qunit-tests { font-size: smaller; } /** Resets */ #qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter { margin: 0; padding: 0; } /** Header */ #qunit-header { padding: 0.5em 0 0.5em 1em; color: #8699a4; background-color: #0d3349; font-size: 1.5em; line-height: 1em; font-weight: normal; border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; -webkit-border-top-right-radius: 5px; -webkit-border-top-left-radius: 5px; } #qunit-header a { text-decoration: none; color: #c2ccd1; } #qunit-header a:hover, #qunit-header a:focus { color: #fff; } #qunit-testrunner-toolbar label { display: inline-block; padding: 0 .5em 0 .1em; } #qunit-banner { height: 5px; } #qunit-testrunner-toolbar { padding: 0.5em 0 0.5em 2em; color: #5E740B; background-color: #eee; overflow: hidden; } #qunit-userAgent { padding: 0.5em 0 0.5em 2.5em; background-color: #2b81af; color: #fff; text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; } #qunit-modulefilter-container { float: right; } /** Tests: Pass/Fail */ #qunit-tests { list-style-position: inside; } #qunit-tests li { padding: 0.4em 0.5em 0.4em 2.5em; border-bottom: 1px solid #fff; list-style-position: inside; } #qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { display: none; } #qunit-tests li strong { cursor: pointer; } #qunit-tests li a { padding: 0.5em; color: #c2ccd1; text-decoration: none; } #qunit-tests li a:hover, #qunit-tests li a:focus { color: #000; } #qunit-tests li .runtime { float: right; font-size: smaller; } .qunit-assert-list { margin-top: 0.5em; padding: 0.5em; background-color: #fff; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } .qunit-collapsed { display: none; } #qunit-tests table { border-collapse: collapse; margin-top: .2em; } #qunit-tests th { text-align: right; vertical-align: top; padding: 0 .5em 0 0; } #qunit-tests td { vertical-align: top; } #qunit-tests pre { margin: 0; white-space: pre-wrap; word-wrap: break-word; } #qunit-tests del { background-color: #e0f2be; color: #374e0c; text-decoration: none; } #qunit-tests ins { background-color: #ffcaca; color: #500; text-decoration: none; } /*** Test Counts */ #qunit-tests b.counts { color: black; } #qunit-tests b.passed { color: #5E740B; } #qunit-tests b.failed { color: #710909; } #qunit-tests li li { padding: 5px; background-color: #fff; border-bottom: none; list-style-position: inside; } /*** Passing Styles */ #qunit-tests li li.pass { color: #3c510c; background-color: #fff; border-left: 10px solid #C6E746; } #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } #qunit-tests .pass .test-name { color: #366097; } #qunit-tests .pass .test-actual, #qunit-tests .pass .test-expected { color: #999999; } #qunit-banner.qunit-pass { background-color: #C6E746; } /*** Failing Styles */ #qunit-tests li li.fail { color: #710909; background-color: #fff; border-left: 10px solid #EE5757; white-space: pre; } #qunit-tests > li:last-child { border-radius: 0 0 5px 5px; -moz-border-radius: 0 0 5px 5px; -webkit-border-bottom-right-radius: 5px; -webkit-border-bottom-left-radius: 5px; } #qunit-tests .fail { color: #000000; background-color: #EE5757; } #qunit-tests .fail .test-name, #qunit-tests .fail .module-name { color: #000000; } #qunit-tests .fail .test-actual { color: #EE5757; } #qunit-tests .fail .test-expected { color: green; } #qunit-banner.qunit-fail { background-color: #EE5757; } /** Result */ #qunit-testresult { padding: 0.5em 0.5em 0.5em 2.5em; color: #2b81af; background-color: #D2E0E6; border-bottom: 1px solid white; } #qunit-testresult .module-name { font-weight: bold; } /** Fixture */ #qunit-fixture { position: absolute; top: -10000px; left: -10000px; width: 1000px; height: 1000px; } 1.7.0~dfsg/test/utility.js0000644000000000000000000003000712377203462014307 0ustar rootroot(function() { var templateSettings; module('Utility', { setup: function() { templateSettings = _.clone(_.templateSettings); }, teardown: function() { _.templateSettings = templateSettings; } }); test('#750 - Return _ instance.', 2, function() { var instance = _([]); ok(_(instance) === instance); ok(new _(instance) === instance); }); test('identity', function() { var moe = {name : 'moe'}; equal(_.identity(moe), moe, 'moe is the same as his identity'); }); test('constant', function() { var moe = {name : 'moe'}; equal(_.constant(moe)(), moe, 'should create a function that returns moe'); }); test('noop', function() { strictEqual(_.noop('curly', 'larry', 'moe'), undefined, 'should always return undefined'); }); test('property', function() { var moe = {name : 'moe'}; equal(_.property('name')(moe), 'moe', 'should return the property with the given name'); }); test('random', function() { var array = _.range(1000); var min = Math.pow(2, 31); var max = Math.pow(2, 62); ok(_.every(array, function() { return _.random(min, max) >= min; }), 'should produce a random number greater than or equal to the minimum number'); ok(_.some(array, function() { return _.random(Number.MAX_VALUE) > 0; }), 'should produce a random number when passed `Number.MAX_VALUE`'); }); test('now', function() { var diff = _.now() - new Date().getTime(); ok(diff <= 0 && diff > -5, 'Produces the correct time in milliseconds');//within 5ms }); test('uniqueId', function() { var ids = [], i = 0; while (i++ < 100) ids.push(_.uniqueId()); equal(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids'); }); test('times', function() { var vals = []; _.times(3, function (i) { vals.push(i); }); deepEqual(vals, [0, 1, 2], 'is 0 indexed'); // vals = []; _(3).times(function(i) { vals.push(i); }); deepEqual(vals, [0, 1, 2], 'works as a wrapper'); // collects return values deepEqual([0, 1, 2], _.times(3, function(i) { return i; }), 'collects return values'); deepEqual(_.times(0, _.identity), []); deepEqual(_.times(-1, _.identity), []); deepEqual(_.times(parseFloat('-Infinity'), _.identity), []); }); test('mixin', function() { _.mixin({ myReverse: function(string) { return string.split('').reverse().join(''); } }); equal(_.myReverse('panacea'), 'aecanap', 'mixed in a function to _'); equal(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper'); }); test('_.escape', function() { equal(_.escape(null), ''); }); test('_.unescape', function() { var string = 'Curly & Moe'; equal(_.unescape(null), ''); equal(_.unescape(_.escape(string)), string); equal(_.unescape(string), string, 'don\'t unescape unnecessarily'); }); // Don't care what they escape them to just that they're escaped and can be unescaped test('_.escape & unescape', function() { // test & (&) seperately obviously var escapeCharacters = ['<', '>', '"', '\'', '`']; _.each(escapeCharacters, function(escapeChar) { var str = 'a ' + escapeChar + ' string escaped'; var escaped = _.escape(str); notEqual(str, escaped, escapeChar + ' is escaped'); equal(str, _.unescape(escaped), escapeChar + ' can be unescaped'); str = 'a ' + escapeChar + escapeChar + escapeChar + 'some more string' + escapeChar; escaped = _.escape(str); equal(escaped.indexOf(escapeChar), -1, 'can escape multiple occurances of ' + escapeChar); equal(_.unescape(escaped), str, 'multiple occurrences of ' + escapeChar + ' can be unescaped'); }); // handles multiple escape characters at once var joiner = ' other stuff '; var allEscaped = escapeCharacters.join(joiner); allEscaped += allEscaped; ok(_.every(escapeCharacters, function(escapeChar) { return allEscaped.indexOf(escapeChar) !== -1; }), 'handles multiple characters'); ok(allEscaped.indexOf(joiner) >= 0, 'can escape multiple escape characters at the same time'); // test & -> & var str = 'some string & another string & yet another'; var escaped = _.escape(str); ok(escaped.indexOf('&') !== -1, 'handles & aka &'); equal(_.unescape(str), str, 'can unescape &'); }); test('template', function() { var basicTemplate = _.template("<%= thing %> is gettin' on my noives!"); var result = basicTemplate({thing : 'This'}); equal(result, "This is gettin' on my noives!", 'can do basic attribute interpolation'); var sansSemicolonTemplate = _.template('A <% this %> B'); equal(sansSemicolonTemplate(), 'A B'); var backslashTemplate = _.template('<%= thing %> is \\ridanculous'); equal(backslashTemplate({thing: 'This'}), 'This is \\ridanculous'); var escapeTemplate = _.template('<%= a ? "checked=\\"checked\\"" : "" %>'); equal(escapeTemplate({a: true}), 'checked="checked"', 'can handle slash escapes in interpolations.'); var fancyTemplate = _.template(''); result = fancyTemplate({people : {moe : 'Moe', larry : 'Larry', curly : 'Curly'}}); equal(result, '', 'can run arbitrary javascript in templates'); var escapedCharsInJavascriptTemplate = _.template(''); result = escapedCharsInJavascriptTemplate({numbers: 'one\ntwo\nthree\nfour'}); equal(result, '', 'Can use escaped characters (e.g. \\n) in JavaScript'); var namespaceCollisionTemplate = _.template('<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %>
    <% }); %>'); result = namespaceCollisionTemplate({ pageCount: 3, thumbnails: { 1: 'p1-thumbnail.gif', 2: 'p2-thumbnail.gif', 3: 'p3-thumbnail.gif' } }); equal(result, '3 p3-thumbnail.gif
    '); var noInterpolateTemplate = _.template('

    Just some text. Hey, I know this is silly but it aids consistency.

    '); result = noInterpolateTemplate(); equal(result, '

    Just some text. Hey, I know this is silly but it aids consistency.

    '); var quoteTemplate = _.template("It's its, not it's"); equal(quoteTemplate({}), "It's its, not it's"); var quoteInStatementAndBody = _.template('<% ' + " if(foo == 'bar'){ " + "%>Statement quotes and 'quotes'.<% } %>"); equal(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'."); var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.'); equal(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.'); var template = _.template('<%- value %>'); result = template({value: '