Advertisement
Guest User

Untitled

a guest
Jul 31st, 2015
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 64.64 KB | None | 0 0
  1. ## Collection Functions (Arrays or Objects)
  2.  
  3. ###### each
  4. `_.each(list, iteratee, [context])` Alias: **forEach**
  5. 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.
  6.  
  7. _.each([1, 2, 3], alert);
  8. => alerts each number in turn...
  9. _.each({one: 1, two: 2, three: 3}, alert);
  10. => alerts each number value in turn...
  11.  
  12. _ 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. _
  13.  
  14. ###### map
  15. `_.map(list, iteratee, [context])` Alias: **collect**
  16. Produces a new array of values by mapping each value in **list** through a transformation function (**iteratee**). The `iteratee` is passed three arguments: the `value`, then the `index` (or `key`) of the iteration, and finally a reference to the entire `list`.
  17.  
  18. _.map([1, 2, 3], function(num){ return num * 3; });
  19. => [3, 6, 9]
  20. _.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
  21. => [3, 6, 9]
  22. _.map([[1, 2], [3, 4]], _.first);
  23. => [1, 3]
  24.  
  25. ###### reduce
  26. `_.reduce(list, iteratee, [memo], [context])` Aliases: **inject, foldl**
  27. 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`.
  28.  
  29. 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.
  30.  
  31. var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
  32. => 6
  33.  
  34. ###### reduceRight
  35. `_.reduceRight(list, iteratee, memo, [context])` Alias: **foldr**
  36. 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.
  37.  
  38. var list = [[0, 1], [2, 3], [4, 5]];
  39. var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  40. => [4, 5, 2, 3, 0, 1]
  41.  
  42. ###### find
  43. `_.find(list, predicate, [context])` Alias: **detect**
  44. 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.
  45.  
  46. var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  47. => 2
  48.  
  49. ###### filter
  50. `_.filter(list, predicate, [context])` Alias: **select**
  51. Looks through each value in the **list**, returning an array of all the values that pass a truth test (**predicate**).
  52.  
  53. var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  54. => [2, 4, 6]
  55.  
  56. ###### where
  57. `_.where(list, properties)`
  58. 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**.
  59.  
  60. _.where(listOfPlays, {author: "Shakespeare", year: 1611});
  61. => [{title: "Cymbeline", author: "Shakespeare", year: 1611},
  62. {title: "The Tempest", author: "Shakespeare", year: 1611}]
  63.  
  64. ###### findWhere
  65. `_.findWhere(list, properties)`
  66. Looks through the **list** and returns the _first_ value that matches all of the key-value pairs listed in **properties**.
  67.  
  68. If no match is found, or if **list** is empty, _undefined_ will be returned.
  69.  
  70. _.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});
  71. => {year: 1918, newsroom: "The New York Times",
  72. reason: "For its public service in publishing in full so many official reports,
  73. documents and speeches by European statesmen relating to the progress and
  74. conduct of the war."}
  75.  
  76. ###### reject
  77. `_.reject(list, predicate, [context])`
  78. Returns the values in **list** without the elements that the truth test (**predicate**) passes. The opposite of **filter**.
  79.  
  80. var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  81. => [1, 3, 5]
  82.  
  83. ###### every
  84. `_.every(list, [predicate], [context])` Alias: **all**
  85. Returns _true_ if all of the values in the **list** pass the **predicate** truth test.
  86.  
  87. _.every([true, 1, null, 'yes'], _.identity);
  88. => false
  89.  
  90. ###### some
  91. `_.some(list, [predicate], [context])` Alias: **any**
  92. 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.
  93.  
  94. _.some([null, 0, 'yes', false]);
  95. => true
  96.  
  97. ###### contains
  98. `_.contains(list, value, [fromIndex])` Alias: **includes**
  99. Returns _true_ if the **value** is present in the **list**. Uses **indexOf** internally, if **list** is an Array. Use **fromIndex** to start your search at a given index.
  100.  
  101. _.contains([1, 2, 3], 3);
  102. => true
  103.  
  104. ###### invoke
  105. `_.invoke(list, methodName, *arguments)`
  106. 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.
  107.  
  108. _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  109. => [[1, 5, 7], [1, 2, 3]]
  110.  
  111. ###### pluck
  112. `_.pluck(list, propertyName)`
  113. A convenient version of what is perhaps the most common use-case for **map**: extracting a list of property values.
  114.  
  115. var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
  116. _.pluck(stooges, 'name');
  117. => ["moe", "larry", "curly"]
  118.  
  119. ###### max
  120. `_.max(list, [iteratee], [context])`
  121. 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.
  122.  
  123. var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
  124. _.max(stooges, function(stooge){ return stooge.age; });
  125. => {name: 'curly', age: 60};
  126.  
  127. ###### min
  128. `_.min(list, [iteratee], [context])`
  129. 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.
  130.  
  131. var numbers = [10, 5, 100, 2, 1000];
  132. _.min(numbers);
  133. => 2
  134.  
  135. ###### sortBy
  136. `_.sortBy(list, iteratee, [context])`
  137. 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`).
  138.  
  139. _.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
  140. => [5, 4, 6, 3, 1, 2]
  141.  
  142. var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
  143. _.sortBy(stooges, 'name');
  144. => [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];
  145.  
  146. ###### groupBy
  147. `_.groupBy(list, iteratee, [context])`
  148. 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.
  149.  
  150. _.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
  151. => {1: [1.3], 2: [2.1, 2.4]}
  152.  
  153. _.groupBy(['one', 'two', 'three'], 'length');
  154. => {3: ["one", "two"], 5: ["three"]}
  155.  
  156. ###### indexBy
  157. `_.indexBy(list, iteratee, [context])`
  158. 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.
  159.  
  160. var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
  161. _.indexBy(stooges, 'age');
  162. => {
  163. "40": {name: 'moe', age: 40},
  164. "50": {name: 'larry', age: 50},
  165. "60": {name: 'curly', age: 60}
  166. }
  167.  
  168. ###### countBy
  169. `_.countBy(list, iteratee, [context])`
  170. 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.
  171.  
  172. _.countBy([1, 2, 3, 4, 5], function(num) {
  173. return num % 2 == 0 ? 'even': 'odd';
  174. });
  175. => {odd: 3, even: 2}
  176.  
  177. ###### shuffle
  178. `_.shuffle(list)`
  179. Returns a shuffled copy of the **list**, using a version of the [Fisher-Yates shuffle][15].
  180.  
  181. _.shuffle([1, 2, 3, 4, 5, 6]);
  182. => [4, 1, 6, 3, 5, 2]
  183.  
  184. ###### sample
  185. `_.sample(list, [n])`
  186. 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.
  187.  
  188. _.sample([1, 2, 3, 4, 5, 6]);
  189. => 4
  190.  
  191. _.sample([1, 2, 3, 4, 5, 6], 3);
  192. => [1, 6, 2]
  193.  
  194. ###### toArray
  195. `_.toArray(list)`
  196. Creates a real Array from the **list** (anything that can be iterated over). Useful for transmuting the **arguments** object.
  197.  
  198. (function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
  199. => [2, 3, 4]
  200.  
  201. ###### size
  202. `_.size(list)`
  203. Return the number of values in the **list**.
  204.  
  205. _.size({one: 1, two: 2, three: 3});
  206. => 3
  207.  
  208. ###### partition
  209. `_.partition(array, predicate)`
  210. Split **array** into two arrays: one whose elements all satisfy **predicate** and one whose elements all do not satisfy **predicate**.
  211.  
  212. _.partition([0, 1, 2, 3, 4, 5], isOdd);
  213. => [[1, 3, 5], [0, 2, 4]]
  214.  
  215. ## Array Functions
  216.  
  217. _ Note: All array functions will also work on the **arguments** object. However, Underscore functions are not designed to work on "sparse" arrays. _
  218.  
  219. ###### first
  220. `_.first(array, [n])` Alias: **head**, **take**
  221. Returns the first element of an **array**. Passing **n** will return the first **n** elements of the array.
  222.  
  223. _.first([5, 4, 3, 2, 1]);
  224. => 5
  225.  
  226. ###### initial
  227. `_.initial(array, [n])`
  228. 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.
  229.  
  230. _.initial([5, 4, 3, 2, 1]);
  231. => [5, 4, 3, 2]
  232.  
  233. ###### last
  234. `_.last(array, [n])`
  235. Returns the last element of an **array**. Passing **n** will return the last **n** elements of the array.
  236.  
  237. _.last([5, 4, 3, 2, 1]);
  238. => 1
  239.  
  240. ###### rest
  241. `_.rest(array, [index])` Alias: **tail, drop**
  242. Returns the **rest** of the elements in an array. Pass an **index** to return the values of the array from that index onward.
  243.  
  244. _.rest([5, 4, 3, 2, 1]);
  245. => [4, 3, 2, 1]
  246.  
  247. ###### compact
  248. `_.compact(array)`
  249. Returns a copy of the **array** with all falsy values removed. In JavaScript, _false_, _null_, _0_, _""_, _undefined_ and _NaN_ are all falsy.
  250.  
  251. _.compact([0, 1, false, 2, '', 3]);
  252. => [1, 2, 3]
  253.  
  254. ###### flatten
  255. `_.flatten(array, [shallow])`
  256. Flattens a nested **array** (the nesting can be to any depth). If you pass **shallow**, the array will only be flattened a single level.
  257.  
  258. _.flatten([1, [2], [3, [[4]]]]);
  259. => [1, 2, 3, 4];
  260.  
  261. _.flatten([1, [2], [3, [[4]]]], true);
  262. => [1, 2, 3, [[4]]];
  263.  
  264. ###### without
  265. `_.without(array, *values)`
  266. Returns a copy of the **array** with all instances of the **values** removed.
  267.  
  268. _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  269. => [2, 3, 4]
  270.  
  271. ###### union
  272. `_.union(*arrays)`
  273. 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**.
  274.  
  275. _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  276. => [1, 2, 3, 101, 10]
  277.  
  278. ###### intersection
  279. `_.intersection(*arrays)`
  280. 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**.
  281.  
  282. _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  283. => [1, 2]
  284.  
  285. ###### difference
  286. `_.difference(array, *others)`
  287. Similar to **without**, but returns the values from **array** that are not present in the **other** arrays.
  288.  
  289. _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  290. => [1, 3, 4]
  291.  
  292. ###### uniq
  293. `_.uniq(array, [isSorted], [iteratee])` Alias: **unique**
  294. Produces a duplicate-free version of the **array**, using _===_ to test object equality. In particular only the first occurence of each value is kept. 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.
  295.  
  296. _.uniq([1, 2, 1, 4, 1, 3]);
  297. => [1, 2, 4, 3]
  298.  
  299. ###### zip
  300. `_.zip(*arrays)`
  301. 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.
  302.  
  303. _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
  304. => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
  305.  
  306. ###### unzip
  307. `_.unzip(*arrays)`
  308. The opposite of zip. Given a number of **arrays**, returns a series of new arrays, the first of which contains all of the first elements in the input arrays, the second of which contains all of the second elements, and so on. Use with `apply` to pass in an array of arrays.
  309.  
  310. _.unzip(["moe", 30, true], ["larry", 40, false], ["curly", 50, false]);
  311. => [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]]
  312.  
  313. ###### object
  314. `_.object(list, [values])`
  315. 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.
  316.  
  317. _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
  318. => {moe: 30, larry: 40, curly: 50}
  319.  
  320. _.object([['moe', 30], ['larry', 40], ['curly', 50]]);
  321. => {moe: 30, larry: 40, curly: 50}
  322.  
  323. ###### indexOf
  324. `_.indexOf(array, value, [isSorted])`
  325. 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.
  326.  
  327. _.indexOf([1, 2, 3], 2);
  328. => 1
  329.  
  330. ###### lastIndexOf
  331. `_.lastIndexOf(array, value, [fromIndex])`
  332. 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.
  333.  
  334. _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  335. => 4
  336.  
  337. ###### sortedIndex
  338. `_.sortedIndex(list, value, [iteratee], [context])`
  339. 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`).
  340.  
  341. _.sortedIndex([10, 20, 30, 40, 50], 35);
  342. => 3
  343.  
  344. var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];
  345. _.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');
  346. => 1
  347.  
  348. ###### findIndex
  349. `_.findIndex(array, predicate, [context])`
  350. Similar to `_.indexOf`, returns the first index where the **predicate** truth test passes; otherwise returns _-1_.
  351.  
  352. _.findIndex([4, 6, 8, 12], isPrime);
  353. => -1 // not found
  354. _.findIndex([4, 6, 7, 12], isPrime);
  355. => 2
  356.  
  357. ###### findLastIndex
  358. `_.findLastIndex(array, predicate, [context])`
  359. Like `_.findIndex` but iterates the array in reverse, returning the index closest to the end where the **predicate** truth test passes.
  360.  
  361. var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},
  362. {'id': 2, 'name': 'Ted', 'last': 'White'},
  363. {'id': 3, 'name': 'Frank', 'last': 'James'},
  364. {'id': 4, 'name': 'Ted', 'last': 'Jones'}];
  365. _.findLastIndex(users, {
  366. name: 'Ted'
  367. });
  368. => 3
  369.  
  370. ###### range
  371. `_.range([start], stop, [step])`
  372. 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** (inclusive) to **stop** (exclusive), 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**.
  373.  
  374. _.range(10);
  375. => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  376. _.range(1, 11);
  377. => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  378. _.range(0, 30, 5);
  379. => [0, 5, 10, 15, 20, 25]
  380. _.range(0, -10, -1);
  381. => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  382. _.range(0);
  383. => []
  384.  
  385. ## Function (uh, ahem) Functions
  386.  
  387. ###### bind
  388. `_.bind(function, object, *arguments)`
  389. 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.
  390.  
  391. var func = function(greeting){ return greeting + ': ' + this.name };
  392. func = _.bind(func, {name: 'moe'}, 'hi');
  393. func();
  394. => 'hi: moe'
  395.  
  396. ###### bindAll
  397. `_.bindAll(object, *methodNames)`
  398. 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.
  399.  
  400. var buttonView = {
  401. label : 'underscore',
  402. onClick: function(){ alert('clicked: ' + this.label); },
  403. onHover: function(){ console.log('hovering: ' + this.label); }
  404. };
  405. _.bindAll(buttonView, 'onClick', 'onHover');
  406. // When the button is clicked, this.label will have the correct value.
  407. jQuery('#underscore_button').bind('click', buttonView.onClick);
  408.  
  409. ###### partial
  410. `_.partial(function, *arguments)`
  411. 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.
  412.  
  413. var subtract = function(a, b) { return b - a; };
  414. sub5 = _.partial(subtract, 5);
  415. sub5(20);
  416. => 15
  417.  
  418. // Using a placeholder
  419. subFrom20 = _.partial(subtract, _, 20);
  420. subFrom20(5);
  421. => 15
  422.  
  423. ###### memoize
  424. `_.memoize(function, [hashFunction])`
  425. 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. The cache of memoized values is available as the `cache` property on the returned function.
  426.  
  427. var fibonacci = _.memoize(function(n) {
  428. return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
  429. });
  430.  
  431. ###### delay
  432. `_.delay(function, wait, *arguments)`
  433. 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.
  434.  
  435. var log = _.bind(console.log, console);
  436. _.delay(log, 1000, 'logged later');
  437. => 'logged later' // Appears after one second.
  438.  
  439. ###### defer
  440. `_.defer(function, *arguments)`
  441. 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.
  442.  
  443. _.defer(function(){ alert('deferred'); });
  444. // Returns from the function before the alert runs.
  445.  
  446. ###### throttle
  447. `_.throttle(function, wait, [options])`
  448. 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.
  449.  
  450. 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
  451. `{trailing: false}`.
  452.  
  453. var throttled = _.throttle(updatePosition, 100);
  454. $(window).scroll(throttled);
  455.  
  456. ###### debounce
  457. `_.debounce(function, wait, [immediate])`
  458. 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.
  459.  
  460. Pass `true` for the **immediate** argument 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.
  461.  
  462. var lazyLayout = _.debounce(calculateLayout, 300);
  463. $(window).resize(lazyLayout);
  464.  
  465. ###### once
  466. `_.once(function)`
  467. 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.
  468.  
  469. var initialize = _.once(createApplication);
  470. initialize();
  471. initialize();
  472. // Application is only created once.
  473.  
  474. ###### after
  475. `_.after(count, function)`
  476. 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.
  477.  
  478. var renderNotes = _.after(notes.length, render);
  479. _.each(notes, function(note) {
  480. note.asyncSave({success: renderNotes});
  481. });
  482. // renderNotes is run once, after all notes have saved.
  483.  
  484. ###### before
  485. `_.before(count, function)`
  486. 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.
  487.  
  488. var monthlyMeeting = _.before(3, askForRaise);
  489. monthlyMeeting();
  490. monthlyMeeting();
  491. monthlyMeeting();
  492. // the result of any subsequent calls is the same as the second call
  493.  
  494. ###### wrap
  495. `_.wrap(function, wrapper)`
  496. 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.
  497.  
  498. var hello = function(name) { return "hello: " + name; };
  499. hello = _.wrap(hello, function(func) {
  500. return "before, " + func("moe") + ", after";
  501. });
  502. hello();
  503. => 'before, hello: moe, after'
  504.  
  505. ###### negate
  506. `_.negate(predicate)`
  507. Returns a new negated version of the **predicate** function.
  508.  
  509. var isFalsy = _.negate(Boolean);
  510. _.find([-2, -1, 0, 1, 2], isFalsy);
  511. => 0
  512.  
  513. ###### compose
  514. `_.compose(*functions)`
  515. 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()))_.
  516.  
  517. var greet = function(name){ return "hi: " + name; };
  518. var exclaim = function(statement){ return statement.toUpperCase() + "!"; };
  519. var welcome = _.compose(greet, exclaim);
  520. welcome('moe');
  521. => 'hi: MOE!'
  522.  
  523. ## Object Functions
  524.  
  525. ###### keys
  526. `_.keys(object)`
  527. Retrieve all the names of the **object**'s own enumerable properties.
  528.  
  529. _.keys({one: 1, two: 2, three: 3});
  530. => ["one", "two", "three"]
  531.  
  532. ###### allKeys
  533. `_.allKeys(object)`
  534. Retrieve _all_ the names of **object**'s own and inherited properties.
  535.  
  536. function Stooge(name) {
  537. this.name = name;
  538. }
  539. Stooge.prototype.silly = true;
  540. _.allKeys(new Stooge("Moe"));
  541. => ["name", "silly"]
  542.  
  543. ###### values
  544. `_.values(object)`
  545. Return all of the values of the **object**'s own properties.
  546.  
  547. _.values({one: 1, two: 2, three: 3});
  548. => [1, 2, 3]
  549.  
  550. ###### mapObject
  551. `_.mapObject(object, iteratee, [context])`
  552. Like map, but for objects. Transform the value of each property in turn.
  553.  
  554. _.mapObject({start: 5, end: 12}, function(val, key) {
  555. return val + 5;
  556. });
  557. => {start: 10, end: 17}
  558.  
  559. ###### pairs
  560. `_.pairs(object)`
  561. Convert an object into a list of [`key, value]` pairs.
  562.  
  563. _.pairs({one: 1, two: 2, three: 3});
  564. => [["one", 1], ["two", 2], ["three", 3]]
  565.  
  566. ###### invert
  567. `_.invert(object)`
  568. 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.
  569.  
  570. _.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"});
  571. => {Moses: "Moe", Louis: "Larry", Jerome: "Curly"};
  572.  
  573. ###### create
  574. `_.create(prototype, props)`
  575. Creates a new object with the given prototype, optionally attaching **props** as _own_ properties. Basically, `Object.create`, but without all of the property descriptor jazz.
  576.  
  577. var moe = _.create(Stooge.prototype, {name: "Moe"});
  578.  
  579. ###### functions
  580. `_.functions(object)` Alias: **methods**
  581. 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.
  582.  
  583. _.functions(_);
  584. => ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
  585.  
  586. ###### findKey
  587. `_.findKey(object, predicate, [context])`
  588. Similar to `_.findIndex` but for keys in objects. Returns the _key_ where the **predicate** truth test passes or _undefined_.
  589.  
  590. ###### extend
  591. `_.extend(destination, *sources)`
  592. 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.
  593.  
  594. _.extend({name: 'moe'}, {age: 50});
  595. => {name: 'moe', age: 50}
  596.  
  597. ###### extendOwn
  598. `_.extendOwn(destination, *sources)` Alias: **assign**
  599. Like **extend**, but only copies _own_ properties over to the destination object.
  600.  
  601. ###### pick
  602. `_.pick(object, *keys)`
  603. 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.
  604.  
  605. _.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
  606. => {name: 'moe', age: 50}
  607. _.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  608. return _.isNumber(value);
  609. });
  610. => {age: 50}
  611.  
  612. ###### omit
  613. `_.omit(object, *keys)`
  614. 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.
  615.  
  616. _.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
  617. => {name: 'moe', age: 50}
  618. _.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  619. return _.isNumber(value);
  620. });
  621. => {name: 'moe', userid: 'moe1'}
  622.  
  623. ###### defaults
  624. `_.defaults(object, *defaults)`
  625. Fill in `undefined` properties in **object** with the first value present in the following list of **defaults** objects.
  626.  
  627. var iceCream = {flavor: "chocolate"};
  628. _.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});
  629. => {flavor: "chocolate", sprinkles: "lots"}
  630.  
  631. ###### clone
  632. `_.clone(object)`
  633. Create a shallow-copied clone of the provided _plain_ **object**. Any nested objects or arrays will be copied by reference, not duplicated.
  634.  
  635. _.clone({name: 'moe'});
  636. => {name: 'moe'};
  637.  
  638. ###### tap
  639. `_.tap(object, interceptor)`
  640. 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.
  641.  
  642. _.chain([1,2,3,200])
  643. .filter(function(num) { return num % 2 == 0; })
  644. .tap(alert)
  645. .map(function(num) { return num * num })
  646. .value();
  647. => // [2, 200] (alerted)
  648. => [4, 40000]
  649.  
  650. ###### has
  651. `_.has(object, key)`
  652. 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][16].
  653.  
  654. _.has({a: 1, b: 2, c: 3}, "b");
  655. => true
  656.  
  657. ###### property
  658. `_.property(key)`
  659. Returns a function that will itself return the `key` property of any passed-in object.
  660.  
  661. var stooge = {name: 'moe'};
  662. 'moe' === _.property('name')(stooge);
  663. => true
  664.  
  665. ###### propertyOf
  666. `_.propertyOf(object)`
  667. Inverse of `_.property`. Takes an object and returns a function which will return the value of a provided property.
  668.  
  669. var stooge = {name: 'moe'};
  670. _.propertyOf(stooge)('name');
  671. => 'moe'
  672.  
  673. ###### matcher
  674. `_.matcher(attrs)` Alias: **matches**
  675. Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in **attrs**.
  676.  
  677. var ready = _.matcher({selected: true, visible: true});
  678. var readyToGoList = _.filter(list, ready);
  679.  
  680. ###### isEqual
  681. `_.isEqual(object, other)`
  682. Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
  683.  
  684. var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
  685. var clone = {name: 'moe', luckyNumbers: [13, 27, 34]};
  686. stooge == clone;
  687. => false
  688. _.isEqual(stooge, clone);
  689. => true
  690.  
  691. ###### isMatch
  692. `_.isMatch(object, properties)`
  693. Tells you if the keys and values in **properties** are contained in **object**.
  694.  
  695. var stooge = {name: 'moe', age: 32};
  696. _.isMatch(stooge, {age: 32});
  697. => true
  698.  
  699. ###### isEmpty
  700. `_.isEmpty(object)`
  701. 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.
  702.  
  703. _.isEmpty([1, 2, 3]);
  704. => false
  705. _.isEmpty({});
  706. => true
  707.  
  708. ###### isElement
  709. `_.isElement(object)`
  710. Returns _true_ if **object** is a DOM element.
  711.  
  712. _.isElement(jQuery('body')[0]);
  713. => true
  714.  
  715. ###### isArray
  716. `_.isArray(object)`
  717. Returns _true_ if **object** is an Array.
  718.  
  719. (function(){ return _.isArray(arguments); })();
  720. => false
  721. _.isArray([1,2,3]);
  722. => true
  723.  
  724. ###### isObject
  725. `_.isObject(value)`
  726. Returns _true_ if **value** is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings and numbers are not.
  727.  
  728. _.isObject({});
  729. => true
  730. _.isObject(1);
  731. => false
  732.  
  733. ###### isArguments
  734. `_.isArguments(object)`
  735. Returns _true_ if **object** is an Arguments object.
  736.  
  737. (function(){ return _.isArguments(arguments); })(1, 2, 3);
  738. => true
  739. _.isArguments([1,2,3]);
  740. => false
  741.  
  742. ###### isFunction
  743. `_.isFunction(object)`
  744. Returns _true_ if **object** is a Function.
  745.  
  746. _.isFunction(alert);
  747. => true
  748.  
  749. ###### isString
  750. `_.isString(object)`
  751. Returns _true_ if **object** is a String.
  752.  
  753. _.isString("moe");
  754. => true
  755.  
  756. ###### isNumber
  757. `_.isNumber(object)`
  758. Returns _true_ if **object** is a Number (including `NaN`).
  759.  
  760. _.isNumber(8.4 * 5);
  761. => true
  762.  
  763. ###### isFinite
  764. `_.isFinite(object)`
  765. Returns _true_ if **object** is a finite Number.
  766.  
  767. _.isFinite(-101);
  768. => true
  769.  
  770. _.isFinite(-Infinity);
  771. => false
  772.  
  773. ###### isBoolean
  774. `_.isBoolean(object)`
  775. Returns _true_ if **object** is either _true_ or _false_.
  776.  
  777. _.isBoolean(null);
  778. => false
  779.  
  780. ###### isDate
  781. `_.isDate(object)`
  782. Returns _true_ if **object** is a Date.
  783.  
  784. _.isDate(new Date());
  785. => true
  786.  
  787. ###### isRegExp
  788. `_.isRegExp(object)`
  789. Returns _true_ if **object** is a RegExp.
  790.  
  791. _.isRegExp(/moe/);
  792. => true
  793.  
  794. ###### isError
  795. `_.isError(object)`
  796. Returns _true_ if **object** inherrits from an Error.
  797.  
  798. try {
  799. throw new TypeError("Example");
  800. } catch (o_O) {
  801. _.isError(o_O)
  802. }
  803. => true
  804.  
  805. ###### isNaN
  806. `_.isNaN(object)`
  807. Returns _true_ if **object** is _NaN_.
  808. 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`.
  809.  
  810. _.isNaN(NaN);
  811. => true
  812. isNaN(undefined);
  813. => true
  814. _.isNaN(undefined);
  815. => false
  816.  
  817. ###### isNull
  818. `_.isNull(object)`
  819. Returns _true_ if the value of **object** is _null_.
  820.  
  821. _.isNull(null);
  822. => true
  823. _.isNull(undefined);
  824. => false
  825.  
  826. ###### isUndefined
  827. `_.isUndefined(value)`
  828. Returns _true_ if **value** is _undefined_.
  829.  
  830. _.isUndefined(window.missingVariable);
  831. => true
  832.  
  833. ## Utility Functions
  834.  
  835. ###### noConflict
  836. `_.noConflict()`
  837. Give control of the `_` variable back to its previous owner. Returns a reference to the **Underscore** object.
  838.  
  839. var underscore = _.noConflict();
  840.  
  841. ###### identity
  842. `_.identity(value)`
  843. Returns the same value that is used as the argument. In math: `f(x) = x`
  844. This function looks useless, but is used throughout Underscore as a default iteratee.
  845.  
  846. var stooge = {name: 'moe'};
  847. stooge === _.identity(stooge);
  848. => true
  849.  
  850. ###### constant
  851. `_.constant(value)`
  852. Creates a function that returns the same value that is used as the argument of `_.constant`.
  853.  
  854. var stooge = {name: 'moe'};
  855. stooge === _.constant(stooge)();
  856. => true
  857.  
  858. ###### noop
  859. `_.noop()`
  860. Returns `undefined` irrespective of the arguments passed to it. Useful as the default for optional callback arguments.
  861.  
  862. obj.initialize = _.noop;
  863.  
  864. ###### times
  865. `_.times(n, iteratee, [context])`
  866. Invokes the given iteratee function **n** times. Each invocation of **iteratee** is called with an `index` argument. Produces an array of the returned values.
  867. _Note: this example uses the chaining syntax_.
  868.  
  869. _(3).times(function(n){ genie.grantWishNumber(n); });
  870.  
  871. ###### random
  872. `_.random(min, max)`
  873. 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.
  874.  
  875. _.random(0, 100);
  876. => 42
  877.  
  878. ###### mixin
  879. `_.mixin(object)`
  880. 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.
  881.  
  882. _.mixin({
  883. capitalize: function(string) {
  884. return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  885. }
  886. });
  887. _("fabio").capitalize();
  888. => "Fabio"
  889.  
  890. ###### iteratee
  891. `_.iteratee(value, [context])`
  892. 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.
  893. The full list of Underscore methods that transform predicates through `_.iteratee` is `map`, `find`, `filter`, `reject`, `every`, `some`, `max`, `min`, `sortBy`, `groupBy`, `indexBy`, `countBy`, `sortedIndex`, `partition`, and `unique`.
  894.  
  895. var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
  896. _.map(stooges, _.iteratee('age'));
  897. => [25, 21, 23];
  898.  
  899. ###### uniqueId
  900. `_.uniqueId([prefix])`
  901. 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.
  902.  
  903. _.uniqueId('contact_');
  904. => 'contact_104'
  905.  
  906. ###### escape
  907. `_.escape(string)`
  908. Escapes a string for insertion into HTML, replacing `&`, `<`, `>`, `"`, ```, and `'` characters.
  909.  
  910. _.escape('Curly, Larry & Moe');
  911. => "Curly, Larry & Moe"
  912.  
  913. ###### unescape
  914. `_.unescape(string)`
  915. The opposite of **escape**, replaces `&`, `<`, `>`, `"`, ``` and `'` with their unescaped counterparts.
  916.  
  917. _.unescape('Curly, Larry & Moe');
  918. => "Curly, Larry & Moe"
  919.  
  920. ###### result
  921. `_.result(object, property, [defaultValue])`
  922. If the value of the named **property** is a function then invoke it with the **object** as context; otherwise, return it. If a default value is provided and the property doesn't exist or is undefined then the default will be returned. If `defaultValue` is a function its result will be returned.
  923.  
  924. var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
  925. _.result(object, 'cheese');
  926. => "crumpets"
  927. _.result(object, 'stuff');
  928. => "nonsense"
  929. _.result(object, 'meat', 'ham');
  930. => "ham"
  931.  
  932. ###### now
  933. `_.now()`
  934. Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions.
  935.  
  936. _.now();
  937. => 1392066795351
  938.  
  939. ###### template
  940. `_.template(templateString, [settings])`
  941. 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 values, 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.
  942.  
  943. var compiled = _.template("hello: <%= name %>");
  944. compiled({name: 'moe'});
  945. => "hello: moe"
  946.  
  947. var template = _.template("<%- value %>");
  948. template({value: '
  949.  
  950. ## Chaining
  951.  
  952. 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.
  953.  
  954. _.map([1, 2, 3], function(n){ return n * 2; });
  955. _([1, 2, 3]).map(function(n){ return n * 2; });
  956.  
  957. 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.
  958.  
  959. var lyrics = [
  960. {line: 1, words: "I'm a lumberjack and I'm okay"},
  961. {line: 2, words: "I sleep all night and I work all day"},
  962. {line: 3, words: "He's a lumberjack and he's okay"},
  963. {line: 4, words: "He sleeps all night and he works all day"}
  964. ];
  965.  
  966. _.chain(lyrics)
  967. .map(function(line) { return line.words.split(' '); })
  968. .flatten()
  969. .reduce(function(counts, word) {
  970. counts[word] = (counts[word] || 0) + 1;
  971. return counts;
  972. }, {})
  973. .value();
  974.  
  975. => {lumberjack: 2, all: 4, night: 2 ... }
  976.  
  977. In addition, the [Array prototype's methods][18] 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.
  978.  
  979. ###### chain
  980. `_.chain(obj)`
  981. Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until `value` is called.
  982.  
  983. var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
  984. var youngest = _.chain(stooges)
  985. .sortBy(function(stooge){ return stooge.age; })
  986. .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  987. .first()
  988. .value();
  989. => "moe is 21"
  990.  
  991. ###### value
  992. `_(obj).value()`
  993. Extracts the value of a wrapped object.
  994.  
  995. _([1, 2, 3]).value();
  996. => [1, 2, 3]
  997.  
  998.  
  999. ## Change Log
  1000.  
  1001. ###### 1.8.3
  1002. — _April 2, 2015_ — [Diff][44] — [Docs][45]
  1003. * Adds an `_.create` method, as a slimmed down version of `Object.create`.
  1004. * Works around an iOS bug that can improperly cause `isArrayLike` to be JIT-ed. Also fixes a bug when passing `0` to `isArrayLike`.
  1005.  
  1006. ###### 1.8.2
  1007. — _Feb. 22, 2015_ — [Diff][46] — [Docs][47]
  1008. * Restores the previous old-Internet-Explorer edge cases changed in 1.8.1.
  1009. * Adds a `fromIndex` argument to `_.contains`.
  1010.  
  1011. ###### 1.8.1
  1012. — _Feb. 19, 2015_ — [Diff][48] — [Docs][49]
  1013. * Fixes/changes some old-Internet Explorer and related edge case behavior. Test your app with Underscore 1.8.1 in an old IE and let us know how it's doing...
  1014.  
  1015. ###### 1.8.0
  1016. — _Feb. 19, 2015_ — [Diff][50] — [Docs][51]
  1017. * Added `_.mapObject`, which is similar to `_.map`, but just for the values in your object. (A real crowd pleaser.)
  1018. * Added `_.allKeys` which returns _all_ the enumerable property names on an object.
  1019. * Reverted a 1.7.0 change where `_.extend` only copied "own" properties. Hopefully this will un-break you — if it breaks you again, I apologize.
  1020. * Added `_.extendOwn` — a less-useful form of `_.extend` that only copies over "own" properties.
  1021. * Added `_.findIndex` and `_.findLastIndex` functions, which nicely complement their twin-twins `_.indexOf` and `_.lastIndexOf`.
  1022. * Added an `_.isMatch` predicate function that tells you if an object matches key-value properties. A kissing cousin of `_.isEqual` and `_.matcher`.
  1023. * Added an `_.isError` function.
  1024. * Restored the `_.unzip` function as the inverse of `zip`. Flip-flopping. I know.
  1025. * `_.result` now takes an optional fallback value (or function that provides the fallback value).
  1026. * Added the `_.propertyOf` function generator as a mirror-world version of `_.property`.
  1027. * Deprecated `_.matches`. It's now known by a more harmonious name — `_.matcher`.
  1028. * Various and diverse code simplifications, changes for improved cross-platform compatibility, and edge case bug fixes.
  1029.  
  1030. ###### 1.7.0
  1031. — _August 26, 2014_ — [Diff][52] — [Docs][53]
  1032. * 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.
  1033. * 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.
  1034. * Added `_.before` as a counterpart to `_.after`.
  1035. * Added `_.negate` to invert the truth value of a passed-in predicate.
  1036. * Added `_.noop` as a handy empty placeholder function.
  1037. * `_.isEmpty` now works with `arguments` objects.
  1038. * `_.has` now guards against nullish objects.
  1039. * `_.omit` can now take an iteratee function.
  1040. * `_.partition` is now called with `index` and `object`.
  1041. * `_.matches` creates a shallow clone of your object and only iterates over own properties.
  1042. * Aligning better with the forthcoming ECMA6 `Object.assign`, `_.extend` only iterates over the object's own properties.
  1043. * Falsey guards are no longer needed in `_.extend` and `_.defaults`—if the passed in argument isn't a JavaScript object it's just returned.
  1044. * Fixed a few edge cases in `_.max` and `_.min` to handle arrays containing `NaN` (like strings or other objects) and `Infinity` and `-Infinity`.
  1045. * Override base methods like `each` and `some` and they'll be used internally by other Underscore functions too.
  1046. * The escape functions handle backticks (```), to deal with an IE ≤ 8 bug.
  1047. * For consistency, `_.union` and `_.difference` now only work with arrays and not variadic args.
  1048. * `_.memoize` exposes the cache of memoized values as a property on the returned function.
  1049. * `_.pick` accepts `iteratee` and `context` arguments for a more advanced callback.
  1050. * Underscore templates no longer accept an initial `data` object. `_.template` always returns a function now.
  1051. * Optimizations and code cleanup aplenty.
  1052.  
  1053. ###### 1.6.0
  1054. — _February 10, 2014_ — [Diff][54] — [Docs][55]
  1055. * 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.
  1056. * Added `_.partition`, a way to split a collection into two lists of results — those that pass and those that fail a particular predicate.
  1057. * Added `_.property`, for easy creation of iterators that pull specific properties from objects. Useful in conjunction with other Underscore collection functions.
  1058. * 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.
  1059. * Added `_.constant`, as a higher-order `_.identity`.
  1060. * Added `_.now`, an optimized way to get a timestamp — used internally to speed up `debounce` and `throttle`.
  1061. * 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.
  1062. * The `_.each` function now returns a reference to the list for chaining.
  1063. * The `_.keys` function now returns an empty array for non-objects instead of throwing.
  1064. * … and more miscellaneous refactoring.
  1065.  
  1066. ###### 1.5.2
  1067. — _September 7, 2013_ — [Diff][56] — [Docs][57]
  1068. * Added an `indexBy` function, which fits in alongside its cousins, `countBy` and `groupBy`.
  1069. * Added a `sample` function, for sampling random elements from arrays.
  1070. * 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.
  1071. * The `_.escape` function no longer escapes '/'.
  1072.  
  1073. ###### 1.5.1
  1074. — _July 8, 2013_ — [Diff][58] — [Docs][59]
  1075. * Removed `unzip`, as it's simply the application of `zip` to an array of arguments. Use `_.zip.apply(_, list)` to transpose instead.
  1076.  
  1077. ###### 1.5.0
  1078. — _July 6, 2013_ — [Diff][60] — [Docs][61]
  1079. * Added a new `unzip` function, as the inverse of `_.zip`.
  1080. * The `throttle` function now takes an `options` argument, allowing you to disable execution of the throttled function on either the **leading** or **trailing** edge.
  1081. * A source map is now supplied for easier debugging of the minified production build of Underscore.
  1082. * The `defaults` function now only overrides `undefined` values, not `null` ones.
  1083. * 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.
  1084. * Removed the ability to call `_.after` with an invocation count of zero. The minimum number of calls is (naturally) now `1`.
  1085.  
  1086. ###### 1.4.4
  1087. — _January 30, 2013_ — [Diff][62] — [Docs][63]
  1088. * Added `_.findWhere`, for finding the first element in a list that matches a particular set of keys and values.
  1089. * Added `_.partial`, for partially applying a function _without_ changing its dynamic reference to `this`.
  1090. * Simplified `bind` by removing some edge cases involving constructor functions. In short: don't `_.bind` your constructors.
  1091. * A minor optimization to `invoke`.
  1092. * Fix bug in the minified version due to the minifier incorrectly optimizing-away `isFunction`.
  1093.  
  1094. ###### 1.4.3
  1095. — _December 4, 2012_ — [Diff][64] — [Docs][65]
  1096. * Improved Underscore compatibility with Adobe's JS engine that can be used to script Illustrator, Photoshop, and friends.
  1097. * Added a default `_.identity` iterator to `countBy` and `groupBy`.
  1098. * The `uniq` function can now take `array, iterator, context` as the argument list.
  1099. * The `times` function now returns the mapped array of iterator results.
  1100. * Simplified and fixed bugs in `throttle`.
  1101.  
  1102. ###### 1.4.2
  1103. — _October 6, 2012_ — [Diff][66] — [Docs][67]
  1104. * For backwards compatibility, returned to pre-1.4.0 behavior when passing `null` to iteration functions. They now become no-ops again.
  1105.  
  1106. ###### 1.4.1
  1107. — _October 1, 2012_ — [Diff][68] — [Docs][69]
  1108. * Fixed a 1.4.0 regression in the `lastIndexOf` function.
  1109.  
  1110. ###### 1.4.0
  1111. — _September 27, 2012_ — [Diff][70] — [Docs][71]
  1112. * 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.
  1113. * Added a `countBy` function, for counting the number of objects in a list that match a certain criteria.
  1114. * Added an `invert` function, for performing a simple inversion of the keys and values in an object.
  1115. * Added a `where` function, for easy cases of filtering a list for objects with specific values.
  1116. * Added an `omit` function, for filtering an object to remove certain keys.
  1117. * Added a `random` function, to return a random number in a given range.
  1118. * `_.debounce`'d functions now return their last updated value, just like `_.throttle`'d functions do.
  1119. * The `sortBy` function now runs a stable sort algorithm.
  1120. * Added the optional `fromIndex` option to `indexOf` and `lastIndexOf`.
  1121. * "Sparse" arrays are no longer supported in Underscore iteration functions. Use a `for` loop instead (or better yet, an object).
  1122. * The `min` and `max` functions may now be called on _very_ large arrays.
  1123. * Interpolation in templates now represents `null` and `undefined` as the empty string.
  1124. * Underscore iteration functions no longer accept `null` values as a no-op argument. You'll get an early error instead.
  1125. * A number of edge-cases fixes and tweaks, which you can spot in the [diff][70]. Depending on how you're using Underscore, **1.4.0** may be more backwards-incompatible than usual — please test when you upgrade.
  1126.  
  1127. ###### 1.3.3
  1128. — _April 10, 2012_ — [Diff][72] — [Docs][73]
  1129. * 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.
  1130. * Added the `pick` function, which allows you to filter an object literal with a whitelist of allowed property names.
  1131. * Added the `result` function, for convenience when working with APIs that allow either functions or raw properties.
  1132. * Added the `isFinite` function, because sometimes knowing that a value is a number just ain't quite enough.
  1133. * The `sortBy` function may now also be passed the string name of a property to use as the sort order on each object.
  1134. * Fixed `uniq` to work with sparse arrays.
  1135. * The `difference` function now performs a shallow flatten instead of a deep one when computing array differences.
  1136. * The `debounce` function now takes an `immediate` parameter, which will cause the callback to fire on the leading instead of the trailing edge.
  1137.  
  1138. ###### 1.3.1
  1139. — _January 23, 2012_ — [Diff][74] — [Docs][75]
  1140. * Added an `_.has` function, as a safer way to use `hasOwnProperty`.
  1141. * Added `_.collect` as an alias for `_.map`. Smalltalkers, rejoice.
  1142. * Reverted an old change so that `_.extend` will correctly copy over keys with undefined values again.
  1143. * Bugfix to stop escaping slashes within interpolations in `_.template`.
  1144.  
  1145. ###### 1.3.0
  1146. — _January 11, 2012_ — [Diff][76] — [Docs][77]
  1147. * 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.
  1148.  
  1149. ###### 1.2.4
  1150. — _January 4, 2012_ — [Diff][78] — [Docs][79]
  1151. * You now can (and probably should, as it's simpler) write `_.chain(list)` instead of `_(list).chain()`.
  1152. * Fix for escaped characters in Underscore templates, and for supporting customizations of `_.templateSettings` that only define one or two of the required regexes.
  1153. * Fix for passing an array as the first argument to an `_.wrap`'d function.
  1154. * Improved compatibility with ClojureScript, which adds a `call` function to `String.prototype`.
  1155.  
  1156. ###### 1.2.3
  1157. — _December 7, 2011_ — [Diff][80] — [Docs][81]
  1158. * Dynamic scope is now preserved for compiled `_.template` functions, so you can use the value of `this` if you like.
  1159. * Sparse array support of `_.indexOf`, `_.lastIndexOf`.
  1160. * Both `_.reduce` and `_.reduceRight` can now be passed an explicitly `undefined` value. (There's no reason why you'd want to do this.)
  1161.  
  1162. ###### 1.2.2
  1163. — _November 14, 2011_ — [Diff][82] — [Docs][83]
  1164. * 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).
  1165. * `_.escape` no longer tries to be smart about not double-escaping already-escaped HTML entities. Now it just escapes regardless (#350).
  1166. * In `_.template`, you may now leave semicolons out of evaluated statements if you wish: `<% }) %>` (#369).
  1167. * `_.after(callback, 0)` will now trigger the callback immediately, making "after" easier to use with asynchronous APIs (#366).
  1168.  
  1169. ###### 1.2.1
  1170. — _October 24, 2011_ — [Diff][84] — [Docs][83]
  1171. * Several important bug fixes for `_.isEqual`, which should now do better on mutated Arrays, and on non-Array objects with `length` properties. (#329)
  1172. * [James Burke][85] contributed Underscore exporting for AMD module loaders, and [Tony Lukasavage][86] for Appcelerator Titanium. (#335, #338)
  1173. * You can now `_.groupBy(list, 'property')` as a shortcut for grouping values by a particular common property.
  1174. * `_.throttle`'d functions now fire immediately upon invocation, and are rate-limited thereafter (#170, #266).
  1175. * Most of the `_.is[Type]` checks no longer ducktype.
  1176. * The `_.bind` function now also works on constructors, a-la ES5 ... but you would never want to use `_.bind` on a constructor function.
  1177. * `_.clone` no longer wraps non-object types in Objects.
  1178. * `_.find` and `_.filter` are now the preferred names for `_.detect` and `_.select`.
  1179.  
  1180. ###### 1.2.0
  1181. — _October 5, 2011_ — [Diff][87] — [Docs][88]
  1182. * The `_.isEqual` function now supports true deep equality comparisons, with checks for cyclic structures, thanks to Kit Cambridge.
  1183. * Underscore templates now support HTML escaping interpolations, using `<%- ... %>` syntax.
  1184. * Ryan Tenney contributed `_.shuffle`, which uses a modified Fisher-Yates to give you a shuffled copy of an array.
  1185. * `_.uniq` can now be passed an optional iterator, to determine by what criteria an object should be considered unique.
  1186. * `_.last` now takes an optional argument which will return the last N elements of the list.
  1187. * A new `_.initial` function was added, as a mirror of `_.rest`, which returns all the initial values of a list (except the last N).
  1188.  
  1189. ###### 1.1.7
  1190. — _July 13, 2011_ — [Diff][89] — [Docs][90]
  1191. 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.
  1192.  
  1193. ###### 1.1.6
  1194. — _April 18, 2011_ — [Diff][91] — [Docs][92]
  1195. 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 ES5 API. `_.extend` no longer copies keys when the value is undefined. `_.bind` now errors when trying to bind an undefined value.
  1196.  
  1197. ###### 1.1.5
  1198. — _March 20, 2011_ — [Diff][93] — [Docs][94]
  1199. 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 ES5 version, where available. `_.keys` now throws an error when used on non-Object values, as in ES5. Fixed a bug with `_.keys` when used over sparse arrays.
  1200.  
  1201. ###### 1.1.4
  1202. — _January 9, 2011_ — [Diff][95] — [Docs][96]
  1203. 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.
  1204.  
  1205. ###### 1.1.3
  1206. — _December 1, 2010_ — [Diff][97] — [Docs][98]
  1207. In CommonJS, Underscore may now be required with just:
  1208. `var _ = require("underscore")`. Added `_.throttle` and `_.debounce` functions. Removed `_.breakLoop`, in favor of an ES5-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 ES5 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`.
  1209.  
  1210. ###### 1.1.2
  1211. — _October 15, 2010_ — [Diff][99] — [Docs][100]
  1212. Fixed `_.contains`, which was mistakenly pointing at `_.intersect` instead of `_.include`, like it should have been. Added `_.unique` as an alias for `_.uniq`.
  1213.  
  1214. ###### 1.1.1
  1215. — _October 5, 2010_ — [Diff][101] — [Docs][102]
  1216. 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.
  1217.  
  1218. ###### 1.1.0
  1219. — _August 18, 2010_ — [Diff][103] — [Docs][104]
  1220. The method signature of `_.reduce` has been changed to match the ES5 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`.
  1221.  
  1222. ###### 1.0.4
  1223. — _June 22, 2010_ — [Diff][105] — [Docs][106]
  1224. [Andri Möll][107] contributed the `_.memoize` function, which can be used to speed up expensive repeated computations by caching the results.
  1225.  
  1226. ###### 1.0.3
  1227. — _June 14, 2010_ — [Diff][108] — [Docs][109]
  1228. 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.
  1229.  
  1230. ###### 1.0.2
  1231. — _March 23, 2010_ — [Diff][110] — [Docs][111]
  1232. Fixes `_.isArguments` in recent versions of Opera, which have arguments objects as real Arrays.
  1233.  
  1234. ###### 1.0.1
  1235. — _March 19, 2010_ — [Diff][112] — [Docs][113]
  1236. Bugfix for `_.isEqual`, when comparing two objects with the same number of undefined keys, but with different names.
  1237.  
  1238. ###### 1.0.0
  1239. — _March 18, 2010_ — [Diff][114] — [Docs][115]
  1240. 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.
  1241.  
  1242. ###### 0.6.0
  1243. — _February 24, 2010_ — [Diff][116] — [Docs][117]
  1244. Major release. Incorporates a number of [Mile Frawley's][118] 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 ES5's `Array.isArray`, and `Object.keys`.
  1245.  
  1246. ###### 0.5.8
  1247. — _January 28, 2010_ — [Diff][119] — [Docs][120]
  1248. Fixed Underscore's collection functions to work on [NodeLists][121] and [HTMLCollections][122] once more, thanks to [Justin Tulloss][123].
  1249.  
  1250. ###### 0.5.7
  1251. — _January 20, 2010_ — [Diff][124] — [Docs][125]
  1252. A safer implementation of `_.isArguments`, and a faster `_.isNumber`,
  1253. thanks to [Jed Schmidt][126].
  1254.  
  1255. ###### 0.5.6
  1256. — _January 18, 2010_ — [Diff][127] — [Docs][128]
  1257. Customizable delimiters for `_.template`, contributed by [Noah Sloan][129].
  1258.  
  1259. ###### 0.5.5
  1260. — _January 9, 2010_ — [Diff][130] — [Docs][131]
  1261. Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.
  1262.  
  1263. ###### 0.5.4
  1264. — _January 5, 2010_ — [Diff][132] — [Docs][133]
  1265. Fix for multiple single quotes within a template string for `_.template`. See: [Rick Strahl's blog post][134].
  1266.  
  1267. ###### 0.5.2
  1268. — _January 1, 2010_ — [Diff][135] — [Docs][136]
  1269. New implementations of `isArray`, `isDate`, `isFunction`, `isNumber`, `isRegExp`, and `isString`, thanks to a suggestion from [Robert Kieffer][137]. 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][138] contributed `_.tap`, [similar to Ruby 1.9's][139], which is handy for injecting side effects (like logging) into chained calls.
  1270.  
  1271. ###### 0.5.1
  1272. — _December 9, 2009_ — [Diff][140] — [Docs][141]
  1273. Added an `_.isArguments` function. Lots of little safety checks and optimizations contributed by [Noah Sloan][129] and [Andri Möll][107].
  1274.  
  1275. ###### 0.5.0
  1276. — _December 7, 2009_ — [Diff][142] — [Docs][143]
  1277. [**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][144] contributed patches.
  1278.  
  1279. ###### 0.4.7
  1280. — _December 6, 2009_ — [Diff][145] — [Docs][146]
  1281. 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`.
  1282.  
  1283. ###### 0.4.6
  1284. — _November 30, 2009_ — [Diff][147] — [Docs][148]
  1285. Added the `range` function, a port of the [Python function of the same name][149], for generating flexibly-numbered lists of integers. Original patch contributed by [Kirill Ishanov][150].
  1286.  
  1287. ###### 0.4.5
  1288. — _November 19, 2009_ — [Diff][151] — [Docs][152]
  1289. Added `rest` for Arrays and arguments objects, and aliased `first` as `head`, and `rest` as `tail`, thanks to [Luke Sutton][153]'s patches. Added tests ensuring that all Underscore Array functions also work on _arguments_ objects.
  1290.  
  1291. ###### 0.4.4
  1292. — _November 18, 2009_ — [Diff][154] — [Docs][155]
  1293. Added `isString`, and `isNumber`, for consistency. Fixed `_.isEqual(NaN, NaN)` to return _true_ (which is debatable).
  1294.  
  1295. ###### 0.4.3
  1296. — _November 9, 2009_ — [Diff][156] — [Docs][157]
  1297. Started using the native `StopIteration` object in browsers that support it. Fixed Underscore setup for CommonJS environments.
  1298.  
  1299. ###### 0.4.2
  1300. — _November 9, 2009_ — [Diff][158] — [Docs][159]
  1301. Renamed the unwrapping function to `value`, for clarity.
  1302.  
  1303. ###### 0.4.1
  1304. — _November 8, 2009_ — [Diff][160] — [Docs][161]
  1305. 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.
  1306.  
  1307. ###### 0.4.0
  1308. — _November 7, 2009_ — [Diff][162] — [Docs][163]
  1309. 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][164]. Wrapped objects can be chained through multiple method invocations. A `functions` method was added, providing a sorted list of all the functions in Underscore.
  1310.  
  1311. ###### 0.3.3
  1312. — _October 31, 2009_ — [Diff][165] — [Docs][166]
  1313. Added the JavaScript 1.8 function `reduceRight`. Aliased it as `foldr`, and aliased `reduce` as `foldl`.
  1314.  
  1315. ###### 0.3.2
  1316. — _October 29, 2009_ — [Diff][167] — [Docs][168]
  1317. Now runs on stock [Rhino][169] interpreters with: `load("underscore.js")`. Added `identity` as a utility function.
  1318.  
  1319. ###### 0.3.1
  1320. — _October 29, 2009_ — [Diff][170] — [Docs][171]
  1321. 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`.
  1322.  
  1323. ###### 0.3.0
  1324. — _October 29, 2009_ — [Diff][172] — [Docs][173]
  1325. Added [Dmitry Baranovskiy][174]'s comprehensive optimizations, merged in [Kris Kowal][175]'s patches to make Underscore [CommonJS][176] and [Narwhal][177] compliant.
  1326.  
  1327. ###### 0.2.0
  1328. — _October 28, 2009_ — [Diff][178] — [Docs][179]
  1329. Added `compose` and `lastIndexOf`, renamed `inject` to `reduce`, added aliases for `inject`, `filter`, `every`, `some`, and `forEach`.
  1330.  
  1331. ###### 0.1.1
  1332. — _October 28, 2009_ — [Diff][180] — [Docs][181]
  1333. Added `noConflict`, so that the "Underscore" object can be assigned to other variables.
  1334.  
  1335. ###### 0.1.0
  1336. — _October 28, 2009_ — [Docs][181]
  1337. Initial release of Underscore.js.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement