PageRenderTime 63ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/node_modules/underscore/index.html

http://github.com/ifandelse/postal.js
HTML | 2133 lines | 1918 code | 215 blank | 0 comment | 0 complexity | 7ae5d00cd2f1c9833b3bb601ee81ee97 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
  5. <meta http-equiv="X-UA-Compatible" content="chrome=1">
  6. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
  7. <title>Underscore.js</title>
  8. <style>
  9. body {
  10. font-size: 14px;
  11. line-height: 22px;
  12. background: #f4f4f4 url(docs/images/background.png);
  13. color: #000;
  14. font-family: Helvetica Neue, Helvetica, Arial;
  15. }
  16. .interface {
  17. font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
  18. }
  19. div#sidebar {
  20. background: #fff;
  21. position: fixed;
  22. top: 0;
  23. left: 0;
  24. bottom: 0;
  25. width: 200px;
  26. overflow-y: auto;
  27. overflow-x: hidden;
  28. -webkit-overflow-scrolling: touch;
  29. padding: 15px 0 30px 30px;
  30. border-right: 1px solid #bbb;
  31. box-shadow: 0 0 20px #ccc;
  32. -webkit-box-shadow: 0 0 20px #ccc;
  33. -moz-box-shadow: 0 0 20px #ccc;
  34. }
  35. a.toc_title, a.toc_title:visited {
  36. display: block;
  37. color: black;
  38. font-weight: bold;
  39. margin-top: 15px;
  40. }
  41. a.toc_title:hover {
  42. text-decoration: underline;
  43. }
  44. #sidebar .version {
  45. font-size: 10px;
  46. font-weight: normal;
  47. }
  48. ul.toc_section {
  49. font-size: 11px;
  50. line-height: 14px;
  51. margin: 5px 0 0 0;
  52. padding-left: 0px;
  53. list-style-type: none;
  54. font-family: Lucida Grande;
  55. }
  56. .toc_section li {
  57. cursor: pointer;
  58. margin: 0 0 3px 0;
  59. }
  60. .toc_section li a {
  61. text-decoration: none;
  62. color: black;
  63. }
  64. .toc_section li a:hover {
  65. text-decoration: underline;
  66. }
  67. div.container {
  68. width: 550px;
  69. margin: 40px 0 50px 260px;
  70. }
  71. div.warning {
  72. margin-top: 15px;
  73. font: bold 11px Arial;
  74. color: #770000;
  75. }
  76. p {
  77. margin: 20px 0;
  78. width: 550px;
  79. }
  80. a, a:visited {
  81. color: #444;
  82. }
  83. a:active, a:hover {
  84. color: #000;
  85. }
  86. h1, h2, h3, h4, h5, h6 {
  87. padding-top: 20px;
  88. }
  89. h2 {
  90. font-size: 20px;
  91. }
  92. b.header {
  93. font-size: 16px;
  94. line-height: 30px;
  95. }
  96. span.alias {
  97. font-size: 14px;
  98. font-style: italic;
  99. margin-left: 20px;
  100. }
  101. table, tr, td {
  102. margin: 0;
  103. padding: 0;
  104. }
  105. td {
  106. padding: 2px 12px 2px 0;
  107. }
  108. ul {
  109. list-style-type: circle;
  110. padding: 0 0 0 20px;
  111. }
  112. li {
  113. width: 500px;
  114. margin-bottom: 10px;
  115. }
  116. code, pre, tt {
  117. font-family: Monaco, Consolas, "Lucida Console", monospace;
  118. font-size: 12px;
  119. line-height: 18px;
  120. font-style: normal;
  121. }
  122. tt {
  123. padding: 0px 3px;
  124. background: #fff;
  125. border: 1px solid #ddd;
  126. zoom: 1;
  127. }
  128. code {
  129. margin-left: 20px;
  130. }
  131. pre {
  132. font-size: 12px;
  133. padding: 2px 0 2px 15px;
  134. border-left: 5px solid #bbb;
  135. margin: 0px 0 30px;
  136. }
  137. </style>
  138. </head>
  139. <body>
  140. <div id="sidebar" class="interface">
  141. <a class="toc_title" href="#">
  142. Underscore.js <span class="version">(1.3.3)</span>
  143. </a>
  144. <a class="toc_title" href="#">
  145. Introduction
  146. </a>
  147. <a class="toc_title" href="#collections">
  148. Collections
  149. </a>
  150. <ul class="toc_section">
  151. <li>- <a href="#each">each</a></li>
  152. <li>- <a href="#map">map</a></li>
  153. <li>- <a href="#reduce">reduce</a></li>
  154. <li>- <a href="#reduceRight">reduceRight</a></li>
  155. <li>- <a href="#find">find</a></li>
  156. <li>- <a href="#filter">filter</a></li>
  157. <li>- <a href="#reject">reject</a></li>
  158. <li>- <a href="#all">all</a></li>
  159. <li>- <a href="#any">any</a></li>
  160. <li>- <a href="#include">include</a></li>
  161. <li>- <a href="#invoke">invoke</a></li>
  162. <li>- <a href="#pluck">pluck</a></li>
  163. <li>- <a href="#max">max</a></li>
  164. <li>- <a href="#min">min</a></li>
  165. <li>- <a href="#sortBy">sortBy</a></li>
  166. <li>- <a href="#groupBy">groupBy</a></li>
  167. <li>- <a href="#sortedIndex">sortedIndex</a></li>
  168. <li>- <a href="#shuffle">shuffle</a></li>
  169. <li>- <a href="#toArray">toArray</a></li>
  170. <li>- <a href="#size">size</a></li>
  171. </ul>
  172. <a class="toc_title" href="#arrays">
  173. Arrays
  174. </a>
  175. <ul class="toc_section">
  176. <li>- <a href="#first">first</a></li>
  177. <li>- <a href="#initial">initial</a></li>
  178. <li>- <a href="#last">last</a></li>
  179. <li>- <a href="#rest">rest</a></li>
  180. <li>- <a href="#compact">compact</a></li>
  181. <li>- <a href="#flatten">flatten</a></li>
  182. <li>- <a href="#without">without</a></li>
  183. <li>- <a href="#union">union</a></li>
  184. <li>- <a href="#intersection">intersection</a></li>
  185. <li>- <a href="#difference">difference</a></li>
  186. <li>- <a href="#uniq">uniq</a></li>
  187. <li>- <a href="#zip">zip</a></li>
  188. <li>- <a href="#indexOf">indexOf</a></li>
  189. <li>- <a href="#lastIndexOf">lastIndexOf</a></li>
  190. <li>- <a href="#range">range</a></li>
  191. </ul>
  192. <a class="toc_title" href="#functions">
  193. Functions
  194. </a>
  195. <ul class="toc_section">
  196. <li>- <a href="#bind">bind</a></li>
  197. <li>- <a href="#bindAll">bindAll</a></li>
  198. <li>- <a href="#memoize">memoize</a></li>
  199. <li>- <a href="#delay">delay</a></li>
  200. <li>- <a href="#defer">defer</a></li>
  201. <li>- <a href="#throttle">throttle</a></li>
  202. <li>- <a href="#debounce">debounce</a></li>
  203. <li>- <a href="#once">once</a></li>
  204. <li>- <a href="#after">after</a></li>
  205. <li>- <a href="#wrap">wrap</a></li>
  206. <li>- <a href="#compose">compose</a></li>
  207. </ul>
  208. <a class="toc_title" href="#objects">
  209. Objects
  210. </a>
  211. <ul class="toc_section">
  212. <li>- <a href="#keys">keys</a></li>
  213. <li>- <a href="#values">values</a></li>
  214. <li>- <a href="#object-functions">functions</a></li>
  215. <li>- <a href="#extend">extend</a></li>
  216. <li>- <a href="#pick">pick</a></li>
  217. <li>- <a href="#defaults">defaults</a></li>
  218. <li>- <a href="#clone">clone</a></li>
  219. <li>- <a href="#tap">tap</a></li>
  220. <li>- <a href="#has">has</a></li>
  221. <li>- <a href="#isEqual">isEqual</a></li>
  222. <li>- <a href="#isEmpty">isEmpty</a></li>
  223. <li>- <a href="#isElement">isElement</a></li>
  224. <li>- <a href="#isArray">isArray</a></li>
  225. <li>- <a href="#isObject">isObject</a></li>
  226. <li>- <a href="#isArguments">isArguments</a></li>
  227. <li>- <a href="#isFunction">isFunction</a></li>
  228. <li>- <a href="#isString">isString</a></li>
  229. <li>- <a href="#isNumber">isNumber</a></li>
  230. <li>- <a href="#isFinite">isFinite</a></li>
  231. <li>- <a href="#isBoolean">isBoolean</a></li>
  232. <li>- <a href="#isDate">isDate</a></li>
  233. <li>- <a href="#isRegExp">isRegExp</a></li>
  234. <li>- <a href="#isNaN">isNaN</a></li>
  235. <li>- <a href="#isNull">isNull</a></li>
  236. <li>- <a href="#isUndefined">isUndefined</a></li>
  237. </ul>
  238. <a class="toc_title" href="#utility">
  239. Utility
  240. </a>
  241. <ul class="toc_section">
  242. <li>- <a href="#noConflict">noConflict</a></li>
  243. <li>- <a href="#identity">identity</a></li>
  244. <li>- <a href="#times">times</a></li>
  245. <li>- <a href="#mixin">mixin</a></li>
  246. <li>- <a href="#uniqueId">uniqueId</a></li>
  247. <li>- <a href="#escape">escape</a></li>
  248. <li>- <a href="#result">result</a></li>
  249. <li>- <a href="#template">template</a></li>
  250. </ul>
  251. <a class="toc_title" href="#chaining">
  252. Chaining
  253. </a>
  254. <ul class="toc_section">
  255. <li>- <a href="#chain">chain</a></li>
  256. <li>- <a href="#value">value</a></li>
  257. </ul>
  258. <a class="toc_title" href="#links">
  259. Links
  260. </a>
  261. <a class="toc_title" href="#changelog">
  262. Change Log
  263. </a>
  264. </div>
  265. <div class="container">
  266. <p id="introduction">
  267. <img style="width: 396px; height: 69px;" src="docs/images/underscore.png" alt="Underscore.js"/>
  268. </p>
  269. <p>
  270. <a href="http://github.com/documentcloud/underscore/">Underscore</a> is a
  271. utility-belt library for JavaScript that provides a lot of the
  272. functional programming support that you would expect in
  273. <a href="http://prototypejs.org/api">Prototype.js</a>
  274. (or <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">Ruby</a>),
  275. but without extending any of the built-in JavaScript objects. It's the
  276. tie to go along with <a href="http://docs.jquery.com">jQuery</a>'s tux,
  277. and <a href="http://backbonejs.org">Backbone.js</a>'s suspenders.
  278. </p>
  279. <p>
  280. Underscore provides 60-odd functions that support both the usual
  281. functional suspects: <b>map</b>, <b>select</b>, <b>invoke</b> &mdash;
  282. as well as more specialized helpers: function binding, javascript
  283. templating, deep equality testing, and so on. It delegates to built-in
  284. functions, if present, so modern browsers will use the
  285. native implementations of <b>forEach</b>, <b>map</b>, <b>reduce</b>,
  286. <b>filter</b>, <b>every</b>, <b>some</b> and <b>indexOf</b>.
  287. </p>
  288. <p>
  289. A complete <a href="test/test.html">Test &amp; Benchmark Suite</a>
  290. is included for your perusal.
  291. </p>
  292. <p>
  293. You may also read through the <a href="docs/underscore.html">annotated source code</a>.
  294. </p>
  295. <p>
  296. The project is
  297. <a href="http://github.com/documentcloud/underscore/">hosted on GitHub</a>.
  298. You can report bugs and discuss features on the
  299. <a href="http://github.com/documentcloud/underscore/issues">issues page</a>,
  300. on Freenode in the <tt>#documentcloud</tt> channel,
  301. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  302. </p>
  303. <p>
  304. <i>Underscore is an open-source component of <a href="http://documentcloud.org/">DocumentCloud</a>.</i>
  305. </p>
  306. <h2>Downloads <i style="padding-left: 12px; font-size:12px;">(Right-click, and use "Save As")</i></h2>
  307. <table>
  308. <tr>
  309. <td><a href="underscore.js">Development Version (1.3.3)</a></td>
  310. <td><i>37kb, Uncompressed with Plentiful Comments</i></td>
  311. </tr>
  312. <tr>
  313. <td><a href="underscore-min.js">Production Version (1.3.3)</a></td>
  314. <td><i>4kb, Minified and Gzipped</i></td>
  315. </tr>
  316. </table>
  317. <div class="warning">Upgrade warning: versions 1.3.0 and higher remove AMD (RequireJS) support.</div>
  318. <div id="documentation">
  319. <h2 id="collections">Collection Functions (Arrays or Objects)</h2>
  320. <p id="each">
  321. <b class="header">each</b><code>_.each(list, iterator, [context])</code>
  322. <span class="alias">Alias: <b>forEach</b></span>
  323. <br/>
  324. Iterates over a <b>list</b> of elements, yielding each in turn to an <b>iterator</b>
  325. function. The <b>iterator</b> is bound to the <b>context</b> object, if one is
  326. passed. Each invocation of <b>iterator</b> is called with three arguments:
  327. <tt>(element, index, list)</tt>. If <b>list</b> is a JavaScript object, <b>iterator</b>'s
  328. arguments will be <tt>(value, key, list)</tt>. Delegates to the native
  329. <b>forEach</b> function if it exists.
  330. </p>
  331. <pre>
  332. _.each([1, 2, 3], function(num){ alert(num); });
  333. =&gt; alerts each number in turn...
  334. _.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });
  335. =&gt; alerts each number in turn...</pre>
  336. <p id="map">
  337. <b class="header">map</b><code>_.map(list, iterator, [context])</code>
  338. <span class="alias">Alias: <b>collect</b></span>
  339. <br/>
  340. Produces a new array of values by mapping each value in <b>list</b>
  341. through a transformation function (<b>iterator</b>). If the native <b>map</b> method
  342. exists, it will be used instead. If <b>list</b> is a JavaScript object,
  343. <b>iterator</b>'s arguments will be <tt>(value, key, list)</tt>.
  344. </p>
  345. <pre>
  346. _.map([1, 2, 3], function(num){ return num * 3; });
  347. =&gt; [3, 6, 9]
  348. _.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; });
  349. =&gt; [3, 6, 9]</pre>
  350. <p id="reduce">
  351. <b class="header">reduce</b><code>_.reduce(list, iterator, memo, [context])</code>
  352. <span class="alias">Aliases: <b>inject, foldl</b></span>
  353. <br/>
  354. Also known as <b>inject</b> and <b>foldl</b>, <b>reduce</b> boils down a
  355. <b>list</b> of values into a single value. <b>Memo</b> is the initial state
  356. of the reduction, and each successive step of it should be returned by
  357. <b>iterator</b>.
  358. </p>
  359. <pre>
  360. var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
  361. =&gt; 6
  362. </pre>
  363. <p id="reduceRight">
  364. <b class="header">reduceRight</b><code>_.reduceRight(list, iterator, memo, [context])</code>
  365. <span class="alias">Alias: <b>foldr</b></span>
  366. <br/>
  367. The right-associative version of <b>reduce</b>. Delegates to the
  368. JavaScript 1.8 version of <b>reduceRight</b>, if it exists. <b>Foldr</b>
  369. is not as useful in JavaScript as it would be in a language with lazy
  370. evaluation.
  371. </p>
  372. <pre>
  373. var list = [[0, 1], [2, 3], [4, 5]];
  374. var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
  375. =&gt; [4, 5, 2, 3, 0, 1]
  376. </pre>
  377. <p id="find">
  378. <b class="header">find</b><code>_.find(list, iterator, [context])</code>
  379. <span class="alias">Alias: <b>detect</b></span>
  380. <br/>
  381. Looks through each value in the <b>list</b>, returning the first one that
  382. passes a truth test (<b>iterator</b>). The function returns as
  383. soon as it finds an acceptable element, and doesn't traverse the
  384. entire list.
  385. </p>
  386. <pre>
  387. var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  388. =&gt; 2
  389. </pre>
  390. <p id="filter">
  391. <b class="header">filter</b><code>_.filter(list, iterator, [context])</code>
  392. <span class="alias">Alias: <b>select</b></span>
  393. <br/>
  394. Looks through each value in the <b>list</b>, returning an array of all
  395. the values that pass a truth test (<b>iterator</b>). Delegates to the
  396. native <b>filter</b> method, if it exists.
  397. </p>
  398. <pre>
  399. var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  400. =&gt; [2, 4, 6]
  401. </pre>
  402. <p id="reject">
  403. <b class="header">reject</b><code>_.reject(list, iterator, [context])</code>
  404. <br/>
  405. Returns the values in <b>list</b> without the elements that the truth
  406. test (<b>iterator</b>) passes. The opposite of <b>filter</b>.
  407. </p>
  408. <pre>
  409. var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  410. =&gt; [1, 3, 5]
  411. </pre>
  412. <p id="all">
  413. <b class="header">all</b><code>_.all(list, iterator, [context])</code>
  414. <span class="alias">Alias: <b>every</b></span>
  415. <br/>
  416. Returns <i>true</i> if all of the values in the <b>list</b> pass the <b>iterator</b>
  417. truth test. Delegates to the native method <b>every</b>, if present.
  418. </p>
  419. <pre>
  420. _.all([true, 1, null, 'yes'], _.identity);
  421. =&gt; false
  422. </pre>
  423. <p id="any">
  424. <b class="header">any</b><code>_.any(list, [iterator], [context])</code>
  425. <span class="alias">Alias: <b>some</b></span>
  426. <br/>
  427. Returns <i>true</i> if any of the values in the <b>list</b> pass the
  428. <b>iterator</b> truth test. Short-circuits and stops traversing the list
  429. if a true element is found. Delegates to the native method <b>some</b>,
  430. if present.
  431. </p>
  432. <pre>
  433. _.any([null, 0, 'yes', false]);
  434. =&gt; true
  435. </pre>
  436. <p id="include">
  437. <b class="header">include</b><code>_.include(list, value)</code>
  438. <span class="alias">Alias: <b>contains</b></span>
  439. <br/>
  440. Returns <i>true</i> if the <b>value</b> is present in the <b>list</b>, using
  441. <i>===</i> to test equality. Uses <b>indexOf</b> internally, if <b>list</b>
  442. is an Array.
  443. </p>
  444. <pre>
  445. _.include([1, 2, 3], 3);
  446. =&gt; true
  447. </pre>
  448. <p id="invoke">
  449. <b class="header">invoke</b><code>_.invoke(list, methodName, [*arguments])</code>
  450. <br/>
  451. Calls the method named by <b>methodName</b> on each value in the <b>list</b>.
  452. Any extra arguments passed to <b>invoke</b> will be forwarded on to the
  453. method invocation.
  454. </p>
  455. <pre>
  456. _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
  457. =&gt; [[1, 5, 7], [1, 2, 3]]
  458. </pre>
  459. <p id="pluck">
  460. <b class="header">pluck</b><code>_.pluck(list, propertyName)</code>
  461. <br/>
  462. A convenient version of what is perhaps the most common use-case for
  463. <b>map</b>: extracting a list of property values.
  464. </p>
  465. <pre>
  466. var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
  467. _.pluck(stooges, 'name');
  468. =&gt; ["moe", "larry", "curly"]
  469. </pre>
  470. <p id="max">
  471. <b class="header">max</b><code>_.max(list, [iterator], [context])</code>
  472. <br/>
  473. Returns the maximum value in <b>list</b>. If <b>iterator</b> is passed,
  474. it will be used on each value to generate the criterion by which the
  475. value is ranked.
  476. </p>
  477. <pre>
  478. var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
  479. _.max(stooges, function(stooge){ return stooge.age; });
  480. =&gt; {name : 'curly', age : 60};
  481. </pre>
  482. <p id="min">
  483. <b class="header">min</b><code>_.min(list, [iterator], [context])</code>
  484. <br/>
  485. Returns the minimum value in <b>list</b>. If <b>iterator</b> is passed,
  486. it will be used on each value to generate the criterion by which the
  487. value is ranked.
  488. </p>
  489. <pre>
  490. var numbers = [10, 5, 100, 2, 1000];
  491. _.min(numbers);
  492. =&gt; 2
  493. </pre>
  494. <p id="sortBy">
  495. <b class="header">sortBy</b><code>_.sortBy(list, iterator, [context])</code>
  496. <br/>
  497. Returns a sorted copy of <b>list</b>, ranked in ascending order by the
  498. results of running each value through <b>iterator</b>. Iterator may
  499. also be the string name of the property to sort by (eg. <tt>length</tt>).
  500. </p>
  501. <pre>
  502. _.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
  503. =&gt; [5, 4, 6, 3, 1, 2]
  504. </pre>
  505. <p id="groupBy">
  506. <b class="header">groupBy</b><code>_.groupBy(list, iterator)</code>
  507. <br/>
  508. Splits a collection into sets, grouped by the result of running each
  509. value through <b>iterator</b>. If <b>iterator</b> is a string instead of
  510. a function, groups by the property named by <b>iterator</b> on each of
  511. the values.
  512. </p>
  513. <pre>
  514. _.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
  515. =&gt; {1: [1.3], 2: [2.1, 2.4]}
  516. _.groupBy(['one', 'two', 'three'], 'length');
  517. =&gt; {3: ["one", "two"], 5: ["three"]}
  518. </pre>
  519. <p id="sortedIndex">
  520. <b class="header">sortedIndex</b><code>_.sortedIndex(list, value, [iterator])</code>
  521. <br/>
  522. Uses a binary search to determine the index at which the <b>value</b>
  523. <i>should</i> be inserted into the <b>list</b> in order to maintain the <b>list</b>'s
  524. sorted order. If an <b>iterator</b> is passed, it will be used to compute
  525. the sort ranking of each value.
  526. </p>
  527. <pre>
  528. _.sortedIndex([10, 20, 30, 40, 50], 35);
  529. =&gt; 3
  530. </pre>
  531. <p id="shuffle">
  532. <b class="header">shuffle</b><code>_.shuffle(list)</code>
  533. <br/>
  534. Returns a shuffled copy of the <b>list</b>, using a version of the
  535. <a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle">Fisher-Yates shuffle</a>.
  536. </p>
  537. <pre>
  538. _.shuffle([1, 2, 3, 4, 5, 6]);
  539. =&gt; [4, 1, 6, 3, 5, 2]
  540. </pre>
  541. <p id="toArray">
  542. <b class="header">toArray</b><code>_.toArray(list)</code>
  543. <br/>
  544. Converts the <b>list</b> (anything that can be iterated over), into a
  545. real Array. Useful for transmuting the <b>arguments</b> object.
  546. </p>
  547. <pre>
  548. (function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
  549. =&gt; [2, 3, 4]
  550. </pre>
  551. <p id="size">
  552. <b class="header">size</b><code>_.size(list)</code>
  553. <br/>
  554. Return the number of values in the <b>list</b>.
  555. </p>
  556. <pre>
  557. _.size({one : 1, two : 2, three : 3});
  558. =&gt; 3
  559. </pre>
  560. <h2 id="arrays">Array Functions</h2>
  561. <p>
  562. <i>Note: All array functions will also work on the <b>arguments</b> object.</i>
  563. </p>
  564. <p id="first">
  565. <b class="header">first</b><code>_.first(array, [n])</code>
  566. <span class="alias">Alias: <b>head</b></span>
  567. <br/>
  568. Returns the first element of an <b>array</b>. Passing <b>n</b> will
  569. return the first <b>n</b> elements of the array.
  570. </p>
  571. <pre>
  572. _.first([5, 4, 3, 2, 1]);
  573. =&gt; 5
  574. </pre>
  575. <p id="initial">
  576. <b class="header">initial</b><code>_.initial(array, [n])</code>
  577. <br/>
  578. Returns everything but the last entry of the array. Especially useful on
  579. the arguments object. Pass <b>n</b> to exclude the last <b>n</b> elements
  580. from the result.
  581. </p>
  582. <pre>
  583. _.initial([5, 4, 3, 2, 1]);
  584. =&gt; [5, 4, 3, 2]
  585. </pre>
  586. <p id="last">
  587. <b class="header">last</b><code>_.last(array, [n])</code>
  588. <br/>
  589. Returns the last element of an <b>array</b>. Passing <b>n</b> will return
  590. the last <b>n</b> elements of the array.
  591. </p>
  592. <pre>
  593. _.last([5, 4, 3, 2, 1]);
  594. =&gt; 1
  595. </pre>
  596. <p id="rest">
  597. <b class="header">rest</b><code>_.rest(array, [index])</code>
  598. <span class="alias">Alias: <b>tail</b></span>
  599. <br/>
  600. Returns the <b>rest</b> of the elements in an array. Pass an <b>index</b>
  601. to return the values of the array from that index onward.
  602. </p>
  603. <pre>
  604. _.rest([5, 4, 3, 2, 1]);
  605. =&gt; [4, 3, 2, 1]
  606. </pre>
  607. <p id="compact">
  608. <b class="header">compact</b><code>_.compact(array)</code>
  609. <br/>
  610. Returns a copy of the <b>array</b> with all falsy values removed.
  611. In JavaScript, <i>false</i>, <i>null</i>, <i>0</i>, <i>""</i>,
  612. <i>undefined</i> and <i>NaN</i> are all falsy.
  613. </p>
  614. <pre>
  615. _.compact([0, 1, false, 2, '', 3]);
  616. =&gt; [1, 2, 3]
  617. </pre>
  618. <p id="flatten">
  619. <b class="header">flatten</b><code>_.flatten(array, [shallow])</code>
  620. <br/>
  621. Flattens a nested <b>array</b> (the nesting can be to any depth). If you
  622. pass <b>shallow</b>, the array will only be flattened a single level.
  623. </p>
  624. <pre>
  625. _.flatten([1, [2], [3, [[4]]]]);
  626. =&gt; [1, 2, 3, 4];
  627. _.flatten([1, [2], [3, [[4]]]], true);
  628. =&gt; [1, 2, 3, [[4]]];
  629. </pre>
  630. <p id="without">
  631. <b class="header">without</b><code>_.without(array, [*values])</code>
  632. <br/>
  633. Returns a copy of the <b>array</b> with all instances of the <b>values</b>
  634. removed. <i>===</i> is used for the equality test.
  635. </p>
  636. <pre>
  637. _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
  638. =&gt; [2, 3, 4]
  639. </pre>
  640. <p id="union">
  641. <b class="header">union</b><code>_.union(*arrays)</code>
  642. <br/>
  643. Computes the union of the passed-in <b>arrays</b>: the list of unique items,
  644. in order, that are present in one or more of the <b>arrays</b>.
  645. </p>
  646. <pre>
  647. _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  648. =&gt; [1, 2, 3, 101, 10]
  649. </pre>
  650. <p id="intersection">
  651. <b class="header">intersection</b><code>_.intersection(*arrays)</code>
  652. <br/>
  653. Computes the list of values that are the intersection of all the <b>arrays</b>.
  654. Each value in the result is present in each of the <b>arrays</b>.
  655. </p>
  656. <pre>
  657. _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
  658. =&gt; [1, 2]
  659. </pre>
  660. <p id="difference">
  661. <b class="header">difference</b><code>_.difference(array, *others)</code>
  662. <br/>
  663. Similar to <b>without</b>, but returns the values from <b>array</b> that
  664. are not present in the <b>other</b> arrays.
  665. </p>
  666. <pre>
  667. _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
  668. =&gt; [1, 3, 4]
  669. </pre>
  670. <p id="uniq">
  671. <b class="header">uniq</b><code>_.uniq(array, [isSorted], [iterator])</code>
  672. <span class="alias">Alias: <b>unique</b></span>
  673. <br/>
  674. Produces a duplicate-free version of the <b>array</b>, using <i>===</i> to test
  675. object equality. If you know in advance that the <b>array</b> is sorted,
  676. passing <i>true</i> for <b>isSorted</b> will run a much faster algorithm.
  677. If you want to compute unique items based on a transformation, pass an
  678. <b>iterator</b> function.
  679. </p>
  680. <pre>
  681. _.uniq([1, 2, 1, 3, 1, 4]);
  682. =&gt; [1, 2, 3, 4]
  683. </pre>
  684. <p id="zip">
  685. <b class="header">zip</b><code>_.zip(*arrays)</code>
  686. <br/>
  687. Merges together the values of each of the <b>arrays</b> with the
  688. values at the corresponding position. Useful when you have separate
  689. data sources that are coordinated through matching array indexes.
  690. If you're working with a matrix of nested arrays, <b>zip.apply</b>
  691. can transpose the matrix in a similar fashion.
  692. </p>
  693. <pre>
  694. _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
  695. =&gt; [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
  696. </pre>
  697. <p id="indexOf">
  698. <b class="header">indexOf</b><code>_.indexOf(array, value, [isSorted])</code>
  699. <br/>
  700. Returns the index at which <b>value</b> can be found in the <b>array</b>,
  701. or <i>-1</i> if value is not present in the <b>array</b>. Uses the native
  702. <b>indexOf</b> function unless it's missing. If you're working with a
  703. large array, and you know that the array is already sorted, pass <tt>true</tt>
  704. for <b>isSorted</b> to use a faster binary search.
  705. </p>
  706. <pre>
  707. _.indexOf([1, 2, 3], 2);
  708. =&gt; 1
  709. </pre>
  710. <p id="lastIndexOf">
  711. <b class="header">lastIndexOf</b><code>_.lastIndexOf(array, value)</code>
  712. <br/>
  713. Returns the index of the last occurrence of <b>value</b> in the <b>array</b>,
  714. or <i>-1</i> if value is not present. Uses the native <b>lastIndexOf</b>
  715. function if possible.
  716. </p>
  717. <pre>
  718. _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
  719. =&gt; 4
  720. </pre>
  721. <p id="range">
  722. <b class="header">range</b><code>_.range([start], stop, [step])</code>
  723. <br/>
  724. A function to create flexibly-numbered lists of integers, handy for
  725. <tt>each</tt> and <tt>map</tt> loops. <b>start</b>, if omitted, defaults
  726. to <i>0</i>; <b>step</b> defaults to <i>1</i>. Returns a list of integers
  727. from <b>start</b> to <b>stop</b>, incremented (or decremented) by <b>step</b>,
  728. exclusive.
  729. </p>
  730. <pre>
  731. _.range(10);
  732. =&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  733. _.range(1, 11);
  734. =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  735. _.range(0, 30, 5);
  736. =&gt; [0, 5, 10, 15, 20, 25]
  737. _.range(0, -10, -1);
  738. =&gt; [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  739. _.range(0);
  740. =&gt; []
  741. </pre>
  742. <h2 id="functions">Function (uh, ahem) Functions</h2>
  743. <p id="bind">
  744. <b class="header">bind</b><code>_.bind(function, object, [*arguments])</code>
  745. <br/>
  746. Bind a <b>function</b> to an <b>object</b>, meaning that whenever
  747. the function is called, the value of <i>this</i> will be the <b>object</b>.
  748. Optionally, bind <b>arguments</b> to the <b>function</b> to pre-fill them,
  749. also known as <b>partial application</b>.
  750. </p>
  751. <pre>
  752. var func = function(greeting){ return greeting + ': ' + this.name };
  753. func = _.bind(func, {name : 'moe'}, 'hi');
  754. func();
  755. =&gt; 'hi: moe'
  756. </pre>
  757. <p id="bindAll">
  758. <b class="header">bindAll</b><code>_.bindAll(object, [*methodNames])</code>
  759. <br/>
  760. Binds a number of methods on the <b>object</b>, specified by
  761. <b>methodNames</b>, to be run in the context of that object whenever they
  762. are invoked. Very handy for binding functions that are going to be used
  763. as event handlers, which would otherwise be invoked with a fairly useless
  764. <i>this</i>. If no <b>methodNames</b> are provided, all of the object's
  765. function properties will be bound to it.
  766. </p>
  767. <pre>
  768. var buttonView = {
  769. label : 'underscore',
  770. onClick : function(){ alert('clicked: ' + this.label); },
  771. onHover : function(){ console.log('hovering: ' + this.label); }
  772. };
  773. _.bindAll(buttonView);
  774. jQuery('#underscore_button').bind('click', buttonView.onClick);
  775. =&gt; When the button is clicked, this.label will have the correct value...
  776. </pre>
  777. <p id="memoize">
  778. <b class="header">memoize</b><code>_.memoize(function, [hashFunction])</code>
  779. <br/>
  780. Memoizes a given <b>function</b> by caching the computed result. Useful
  781. for speeding up slow-running computations. If passed an optional
  782. <b>hashFunction</b>, it will be used to compute the hash key for storing
  783. the result, based on the arguments to the original function. The default
  784. <b>hashFunction</b> just uses the first argument to the memoized function
  785. as the key.
  786. </p>
  787. <pre>
  788. var fibonacci = _.memoize(function(n) {
  789. return n &lt; 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  790. });
  791. </pre>
  792. <p id="delay">
  793. <b class="header">delay</b><code>_.delay(function, wait, [*arguments])</code>
  794. <br/>
  795. Much like <b>setTimeout</b>, invokes <b>function</b> after <b>wait</b>
  796. milliseconds. If you pass the optional <b>arguments</b>, they will be
  797. forwarded on to the <b>function</b> when it is invoked.
  798. </p>
  799. <pre>
  800. var log = _.bind(console.log, console);
  801. _.delay(log, 1000, 'logged later');
  802. =&gt; 'logged later' // Appears after one second.
  803. </pre>
  804. <p id="defer">
  805. <b class="header">defer</b><code>_.defer(function)</code>
  806. <br/>
  807. Defers invoking the <b>function</b> until the current call stack has cleared,
  808. similar to using <b>setTimeout</b> with a delay of 0. Useful for performing
  809. expensive computations or HTML rendering in chunks without blocking the UI thread
  810. from updating.
  811. </p>
  812. <pre>
  813. _.defer(function(){ alert('deferred'); });
  814. // Returns from the function before the alert runs.
  815. </pre>
  816. <p id="throttle">
  817. <b class="header">throttle</b><code>_.throttle(function, wait)</code>
  818. <br/>
  819. Creates and returns a new, throttled version of the passed function,
  820. that, when invoked repeatedly, will only actually call the original function
  821. at most once per every <b>wait</b>
  822. milliseconds. Useful for rate-limiting events that occur faster than you
  823. can keep up with.
  824. </p>
  825. <pre>
  826. var throttled = _.throttle(updatePosition, 100);
  827. $(window).scroll(throttled);
  828. </pre>
  829. <p id="debounce">
  830. <b class="header">debounce</b><code>_.debounce(function, wait, [immediate])</code>
  831. <br/>
  832. Creates and returns a new debounced version of the passed function that
  833. will postpone its execution until after
  834. <b>wait</b> milliseconds have elapsed since the last time it
  835. was invoked. Useful for implementing behavior that should only happen
  836. <i>after</i> the input has stopped arriving. For example: rendering a
  837. preview of a Markdown comment, recalculating a layout after the window
  838. has stopped being resized, and so on.
  839. </p>
  840. <p>
  841. Pass <tt>true</tt> for the <b>immediate</b> parameter to cause
  842. <b>debounce</b> to trigger the function on the leading intead of the
  843. trailing edge of the <b>wait</b> interval. Useful in circumstances like
  844. preventing accidental double-clicks on a "submit" button from firing a
  845. second time.
  846. </p>
  847. <pre>
  848. var lazyLayout = _.debounce(calculateLayout, 300);
  849. $(window).resize(lazyLayout);
  850. </pre>
  851. <p id="once">
  852. <b class="header">once</b><code>_.once(function)</code>
  853. <br/>
  854. Creates a version of the function that can only be called one time.
  855. Repeated calls to the modified function will have no effect, returning
  856. the value from the original call. Useful for initialization functions,
  857. instead of having to set a boolean flag and then check it later.
  858. </p>
  859. <pre>
  860. var initialize = _.once(createApplication);
  861. initialize();
  862. initialize();
  863. // Application is only created once.
  864. </pre>
  865. <p id="after">
  866. <b class="header">after</b><code>_.after(count, function)</code>
  867. <br/>
  868. Creates a version of the function that will only be run after first
  869. being called <b>count</b> times. Useful for grouping asynchronous responses,
  870. where you want to be sure that all the async calls have finished, before
  871. proceeding.
  872. </p>
  873. <pre>
  874. var renderNotes = _.after(notes.length, render);
  875. _.each(notes, function(note) {
  876. note.asyncSave({success: renderNotes});
  877. });
  878. // renderNotes is run once, after all notes have saved.
  879. </pre>
  880. <p id="wrap">
  881. <b class="header">wrap</b><code>_.wrap(function, wrapper)</code>
  882. <br/>
  883. Wraps the first <b>function</b> inside of the <b>wrapper</b> function,
  884. passing it as the first argument. This allows the <b>wrapper</b> to
  885. execute code before and after the <b>function</b> runs, adjust the arguments,
  886. and execute it conditionally.
  887. </p>
  888. <pre>
  889. var hello = function(name) { return "hello: " + name; };
  890. hello = _.wrap(hello, function(func) {
  891. return "before, " + func("moe") + ", after";
  892. });
  893. hello();
  894. =&gt; 'before, hello: moe, after'
  895. </pre>
  896. <p id="compose">
  897. <b class="header">compose</b><code>_.compose(*functions)</code>
  898. <br/>
  899. Returns the composition of a list of <b>functions</b>, where each function
  900. consumes the return value of the function that follows. In math terms,
  901. composing the functions <i>f()</i>, <i>g()</i>, and <i>h()</i> produces
  902. <i>f(g(h()))</i>.
  903. </p>
  904. <pre>
  905. var greet = function(name){ return "hi: " + name; };
  906. var exclaim = function(statement){ return statement + "!"; };
  907. var welcome = _.compose(exclaim, greet);
  908. welcome('moe');
  909. =&gt; 'hi: moe!'
  910. </pre>
  911. <h2 id="objects">Object Functions</h2>
  912. <p id="keys">
  913. <b class="header">keys</b><code>_.keys(object)</code>
  914. <br/>
  915. Retrieve all the names of the <b>object</b>'s properties.
  916. </p>
  917. <pre>
  918. _.keys({one : 1, two : 2, three : 3});
  919. =&gt; ["one", "two", "three"]
  920. </pre>
  921. <p id="values">
  922. <b class="header">values</b><code>_.values(object)</code>
  923. <br/>
  924. Return all of the values of the <b>object</b>'s properties.
  925. </p>
  926. <pre>
  927. _.values({one : 1, two : 2, three : 3});
  928. =&gt; [1, 2, 3]
  929. </pre>
  930. <p id="object-functions">
  931. <b class="header">functions</b><code>_.functions(object)</code>
  932. <span class="alias">Alias: <b>methods</b></span>
  933. <br/>
  934. Returns a sorted list of the names of every method in an object &mdash;
  935. that is to say, the name of every function property of the object.
  936. </p>
  937. <pre>
  938. _.functions(_);
  939. =&gt; ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
  940. </pre>
  941. <p id="extend">
  942. <b class="header">extend</b><code>_.extend(destination, *sources)</code>
  943. <br/>
  944. Copy all of the properties in the <b>source</b> objects over to the
  945. <b>destination</b> object, and return the <b>destination</b> object.
  946. It's in-order, so the last source will override properties of the same
  947. name in previous arguments.
  948. </p>
  949. <pre>
  950. _.extend({name : 'moe'}, {age : 50});
  951. =&gt; {name : 'moe', age : 50}
  952. </pre>
  953. <p id="pick">
  954. <b class="header">pick</b><code>_.pick(object, *keys)</code>
  955. <br/>
  956. Return a copy of the <b>object</b>, filtered to only have values for
  957. the whitelisted <b>keys</b> (or array of valid keys).
  958. </p>
  959. <pre>
  960. _.pick({name : 'moe', age: 50, userid : 'moe1'}, 'name', 'age');
  961. =&gt; {name : 'moe', age : 50}
  962. </pre>
  963. <p id="defaults">
  964. <b class="header">defaults</b><code>_.defaults(object, *defaults)</code>
  965. <br/>
  966. Fill in missing properties in <b>object</b> with default values from the
  967. <b>defaults</b> objects, and return the <b>object</b>. As soon as the
  968. property is filled, further defaults will have no effect.
  969. </p>
  970. <pre>
  971. var iceCream = {flavor : "chocolate"};
  972. _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"});
  973. =&gt; {flavor : "chocolate", sprinkles : "lots"}
  974. </pre>
  975. <p id="clone">
  976. <b class="header">clone</b><code>_.clone(object)</code>
  977. <br/>
  978. Create a shallow-copied clone of the <b>object</b>. Any nested objects
  979. or arrays will be copied by reference, not duplicated.
  980. </p>
  981. <pre>
  982. _.clone({name : 'moe'});
  983. =&gt; {name : 'moe'};
  984. </pre>
  985. <p id="tap">
  986. <b class="header">tap</b><code>_.tap(object, interceptor)</code>
  987. <br/>
  988. Invokes <b>interceptor</b> with the <b>object</b>, and then returns <b>object</b>.
  989. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate
  990. results within the chain.
  991. </p>
  992. <pre>
  993. _.chain([1,2,3,200])
  994. .filter(function(num) { return num % 2 == 0; })
  995. .tap(alert)
  996. .map(function(num) { return num * num })
  997. .value();
  998. =&gt; // [2, 200] (alerted)
  999. =&gt; [4, 40000]
  1000. </pre>
  1001. <p id="has">
  1002. <b class="header">has</b><code>_.has(object, key)</code>
  1003. <br/>
  1004. Does the object contain the given key? Identical to
  1005. <tt>object.hasOwnProperty(key)</tt>, but uses a safe reference to the
  1006. <tt>hasOwnProperty</tt> function, in case it's been
  1007. <a href="http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/">overridden accidentally</a>.
  1008. </p>
  1009. <pre>
  1010. _.has({a: 1, b: 2, c: 3}, "b");
  1011. =&gt; true
  1012. </pre>
  1013. <p id="isEqual">
  1014. <b class="header">isEqual</b><code>_.isEqual(object, other)</code>
  1015. <br/>
  1016. Performs an optimized deep comparison between the two objects, to determine
  1017. if they should be considered equal.
  1018. </p>
  1019. <pre>
  1020. var moe = {name : 'moe', luckyNumbers : [13, 27, 34]};
  1021. var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
  1022. moe == clone;
  1023. =&gt; false
  1024. _.isEqual(moe, clone);
  1025. =&gt; true
  1026. </pre>
  1027. <p id="isEmpty">
  1028. <b class="header">isEmpty</b><code>_.isEmpty(object)</code>
  1029. <br/>
  1030. Returns <i>true</i> if <b>object</b> contains no values.
  1031. </p>
  1032. <pre>
  1033. _.isEmpty([1, 2, 3]);
  1034. =&gt; false
  1035. _.isEmpty({});
  1036. =&gt; true
  1037. </pre>
  1038. <p id="isElement">
  1039. <b class="header">isElement</b><code>_.isElement(object)</code>
  1040. <br/>
  1041. Returns <i>true</i> if <b>object</b> is a DOM element.
  1042. </p>
  1043. <pre>
  1044. _.isElement(jQuery('body')[0]);
  1045. =&gt; true
  1046. </pre>
  1047. <p id="isArray">
  1048. <b class="header">isArray</b><code>_.isArray(object)</code>
  1049. <br/>
  1050. Returns <i>true</i> if <b>object</b> is an Array.
  1051. </p>
  1052. <pre>
  1053. (function(){ return _.isArray(arguments); })();
  1054. =&gt; false
  1055. _.isArray([1,2,3]);
  1056. =&gt; true
  1057. </pre>
  1058. <p id="isObject">
  1059. <b class="header">isObject</b><code>_.isObject(value)</code>
  1060. <br/>
  1061. Returns <i>true</i> if <b>value</b> is an Object.
  1062. </p>
  1063. <pre>
  1064. _.isObject({});
  1065. =&gt; true
  1066. _.isObject(1);
  1067. =&gt; false
  1068. </pre>
  1069. <p id="isArguments">
  1070. <b class="header">isArguments</b><code>_.isArguments(object)</code>
  1071. <br/>
  1072. Returns <i>true</i> if <b>object</b> is an Arguments object.
  1073. </p>
  1074. <pre>
  1075. (function(){ return _.isArguments(arguments); })(1, 2, 3);
  1076. =&gt; true
  1077. _.isArguments([1,2,3]);
  1078. =&gt; false
  1079. </pre>
  1080. <p id="isFunction">
  1081. <b class="header">isFunction</b><code>_.isFunction(object)</code>
  1082. <br/>
  1083. Returns <i>true</i> if <b>object</b> is a Function.
  1084. </p>
  1085. <pre>
  1086. _.isFunction(alert);
  1087. =&gt; true
  1088. </pre>
  1089. <p id="isString">
  1090. <b class="header">isString</b><code>_.isString(object)</code>
  1091. <br/>
  1092. Returns <i>true</i> if <b>object</b> is a String.
  1093. </p>
  1094. <pre>
  1095. _.isString("moe");
  1096. =&gt; true
  1097. </pre>
  1098. <p id="isNumber">
  1099. <b class="header">isNumber</b><code>_.isNumber(object)</code>
  1100. <br/>
  1101. Returns <i>true</i> if <b>object</b> is a Number (including <tt>NaN</tt>).
  1102. </p>
  1103. <pre>
  1104. _.isNumber(8.4 * 5);
  1105. =&gt; true
  1106. </pre>
  1107. <p id="isFinite">
  1108. <b class="header">isFinite</b><code>_.isFinite(object)</code>
  1109. <br/>
  1110. Returns <i>true</i> if <b>object</b> is a finite Number.
  1111. </p>
  1112. <pre>
  1113. _.isFinite(-101);
  1114. =&gt; true
  1115. _.isFinite(-Infinity);
  1116. =&gt; false
  1117. </pre>
  1118. <p id="isBoolean">
  1119. <b class="header">isBoolean</b><code>_.isBoolean(object)</code>
  1120. <br/>
  1121. Returns <i>true</i> if <b>object</b> is either <i>true</i> or <i>false</i>.
  1122. </p>
  1123. <pre>
  1124. _.isBoolean(null);
  1125. =&gt; false
  1126. </pre>
  1127. <p id="isDate">
  1128. <b class="header">isDate</b><code>_.isDate(object)</code>
  1129. <br/>
  1130. Returns <i>true</i> if <b>object</b> is a Date.
  1131. </p>
  1132. <pre>
  1133. _.isDate(new Date());
  1134. =&gt; true
  1135. </pre>
  1136. <p id="isRegExp">
  1137. <b class="header">isRegExp</b><code>_.isRegExp(object)</code>
  1138. <br/>
  1139. Returns <i>true</i> if <b>object</b> is a RegExp.
  1140. </p>
  1141. <pre>
  1142. _.isRegExp(/moe/);
  1143. =&gt; true
  1144. </pre>
  1145. <p id="isNaN">
  1146. <b class="header">isNaN</b><code>_.isNaN(object)</code>
  1147. <br/>
  1148. Returns <i>true</i> if <b>object</b> is <i>NaN</i>.<br/> Note: this is not
  1149. the same as the native <b>isNaN</b> function, which will also return
  1150. true if the variable is <i>undefined</i>.
  1151. </p>
  1152. <pre>
  1153. _.isNaN(NaN);
  1154. =&gt; true
  1155. isNaN(undefined);
  1156. =&gt; true
  1157. _.isNaN(undefined);
  1158. =&gt; false
  1159. </pre>
  1160. <p id="isNull">
  1161. <b class="header">isNull</b><code>_.isNull(object)</code>
  1162. <br/>
  1163. Returns <i>true</i> if the value of <b>object</b> is <i>null</i>.
  1164. </p>
  1165. <pre>
  1166. _.isNull(null);
  1167. =&gt; true
  1168. _.isNull(undefined);
  1169. =&gt; false
  1170. </pre>
  1171. <p id="isUndefined">
  1172. <b class="header">isUndefined</b><code>_.isUndefined(variable)</code>
  1173. <br/>
  1174. Returns <i>true</i> if <b>variable</b> is <i>undefined</i>.
  1175. </p>
  1176. <pre>
  1177. _.isUndefined(window.missingVariable);
  1178. =&gt; true
  1179. </pre>
  1180. <h2 id="utility">Utility Functions</h2>
  1181. <p id="noConflict">
  1182. <b class="header">noConflict</b><code>_.noConflict()</code>
  1183. <br/>
  1184. Give control of the "_" variable back to its previous owner. Returns
  1185. a reference to the <b>Underscore</b> object.
  1186. </p>
  1187. <pre>
  1188. var underscore = _.noConflict();</pre>
  1189. <p id="identity">
  1190. <b class="header">identity</b><code>_.identity(value)</code>
  1191. <br/>
  1192. Returns the same value that is used as the argument. In math:
  1193. <tt>f(x) = x</tt><br/>
  1194. This function looks useless, but is used throughout Underscore as
  1195. a default iterator.
  1196. </p>
  1197. <pre>
  1198. var moe = {name : 'moe'};
  1199. moe === _.identity(moe);
  1200. =&gt; true</pre>
  1201. <p id="times">
  1202. <b class="header">times</b><code>_.times(n, iterator)</code>
  1203. <br/>
  1204. Invokes the given iterator function <b>n</b> times.
  1205. </p>
  1206. <pre>
  1207. _(3).times(function(){ genie.grantWish(); });</pre>
  1208. <p id="mixin">
  1209. <b class="header">mixin</b><code>_.mixin(object)</code>
  1210. <br/>
  1211. Allows you to extend Underscore with your own utility functions. Pass
  1212. a hash of <tt>{name: function}</tt> definitions to have your functions
  1213. added to the Underscore object, as well as the OOP wrapper.
  1214. </p>
  1215. <pre>
  1216. _.mixin({
  1217. capitalize : function(string) {
  1218. return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  1219. }
  1220. });
  1221. _("fabio").capitalize();
  1222. =&gt; "Fabio"
  1223. </pre>
  1224. <p id="uniqueId">
  1225. <b class="header">uniqueId</b><code>_.uniqueId([prefix])</code>
  1226. <br/>
  1227. Generate a globally-unique id for client-side models or DOM elements
  1228. that need one. If <b>prefix</b> is passed, the id will be appended to it.
  1229. Without <b>prefix</b>, returns an integer.
  1230. </p>
  1231. <pre>
  1232. _.uniqueId('contact_');
  1233. =&gt; 'contact_104'</pre>
  1234. <p id="escape">
  1235. <b class="header">escape</b><code>_.escape(string)</code>
  1236. <br/>
  1237. Escapes a string for insertion into HTML, replacing
  1238. <tt>&amp;</tt>, <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&quot;</tt>, <tt>&#x27;</tt>, and <tt>&#x2F;</tt> characters.
  1239. </p>
  1240. <pre>
  1241. _.escape('Curly, Larry &amp; Moe');
  1242. =&gt; "Curly, Larry &amp;amp; Moe"</pre>
  1243. <p id="result">
  1244. <b class="header">result</b><code>_.result(object, property)</code>
  1245. <br/>
  1246. If the value of the named property is a function then invoke it; otherwise, return it.
  1247. </p>
  1248. <pre>
  1249. var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
  1250. _.result(object, 'cheese');
  1251. =&gt; "crumpets"
  1252. _.result(object, 'stuff');
  1253. =&gt; "nonsense"</pre>
  1254. <p id="template">
  1255. <b class="header">template</b><code>_.template(templateString, [data], [settings])</code>
  1256. <br/>
  1257. Compiles JavaScript templates into functions that can be evaluated
  1258. for rendering. Useful for rendering complicated bits of HTML from JSON
  1259. data sources. Template functions can both interpolate variables, using
  1260. <tt>&lt;%= &hellip; %&gt;</tt>, as well as execute arbitrary JavaScript code, with
  1261. <tt>&lt;% &hellip; %&gt;</tt>. If you wish to interpolate a value, and have
  1262. it be HTML-escaped, use <tt>&lt;%- &hellip; %&gt;</tt> When you evaluate a template function, pass in a
  1263. <b>data</b> object that has properties corresponding to the template's free
  1264. variables. If you're writing a one-off, you can pass the <b>data</b>
  1265. object as the second parameter to <b>template</b> in order to render
  1266. immediately instead of returning a template function. The <b>settings</b> argument
  1267. should be a hash containing any <tt>_.templateSettings</tt> that should be overriden.
  1268. </p>
  1269. <pre>
  1270. var compiled = _.template("hello: &lt;%= name %&gt;");
  1271. compiled({name : 'moe'});
  1272. =&gt; "hello: moe"
  1273. var list = "&lt;% _.each(people, function(name) { %&gt; &lt;li&gt;&lt;%= name %&gt;&lt;/li&gt; &lt;% }); %&gt;";
  1274. _.template(list, {people : ['moe', 'curly', 'larry']});
  1275. =&gt; "&lt;li&gt;moe&lt;/li&gt;&lt;li&gt;curly&lt;/li&gt;&lt;li&gt;larry&lt;/li&gt;"
  1276. var template = _.template("&lt;b&gt;&lt;%- value %&gt;&lt;/b&gt;");
  1277. template({value : '&lt;script&gt;'});
  1278. =&gt; "&lt;b&gt;&amp;lt;script&amp;gt;&lt;/b&gt;"</pre>
  1279. <p>
  1280. You can also use <tt>print</tt> from within JavaScript code. This is
  1281. sometimes more convenient than using <tt>&lt;%= ... %&gt;</tt>.
  1282. </p>
  1283. <pre>
  1284. var compiled = _.template("&lt;% print('Hello ' + epithet); %&gt;");
  1285. compiled({epithet: "stooge"});
  1286. =&gt; "Hello stooge."</pre>
  1287. <p>
  1288. If ERB-style delimiters aren't your cup of tea, you can change Underscore's
  1289. template settings to use different symbols to set off interpolated code.
  1290. Define an <b>interpolate</b> regex to match expressions that should be
  1291. interpolated verbatim, an <b>escape</b> regex to match expressions that should
  1292. be inserted after being HTML escaped, and an <b>evaluate</b> regex to match
  1293. expressions that should be evaluated without insertion into the resulting
  1294. string. You may define or omit any combination of the three.
  1295. For example, to perform
  1296. <a href="http://github.com/janl/mustache.js#readme">Mustache.js</a>
  1297. style templating:
  1298. </p>
  1299. <pre>
  1300. _.templateSettings = {
  1301. interpolate : /\{\{(.+?)\}\}/g
  1302. };
  1303. var template = _.template("Hello {{ name }}!");
  1304. template({name : "Mustache"});
  1305. =&gt; "Hello Mustache!"</pre>
  1306. <p>
  1307. By default, <b>template</b> places the values from your data in the local scope
  1308. via the <tt>with</tt> statement. However, you can specify a single variable name
  1309. with the <b>variable</b> setting. This can significantly improve the speed
  1310. at which a template is able to render.
  1311. </p>
  1312. <pre>
  1313. _.template("<%= data.hasWith %>", {hasWith: 'no'}, {variable: 'data'});
  1314. =&gt; "no"</pre>
  1315. <p>
  1316. Precompiling your templates can be a big help when debugging errors you can't
  1317. reproduce. This is because precompiled templates can provide line numbers and
  1318. a stack trace, something that is not possible when compiling templates on the client.
  1319. The <b>source</b> property is available on the compiled template
  1320. function for easy precompilation.
  1321. </p>
  1322. <pre>&lt;script&gt;
  1323. JST.project = <%= _.template(jstText).source %>;
  1324. &lt;/script&gt;</pre>
  1325. <h2 id="chaining">Chaining</h2>
  1326. <p>
  1327. You can use Underscore in either an object-oriented or a functional style,
  1328. depending on your preference. The following two lines of code are
  1329. identical ways to double a list of numbers.
  1330. </p>
  1331. <pre>
  1332. _.map([1, 2, 3], function(n){ return n * 2; });
  1333. _([1, 2, 3]).map(function(n){ return n * 2; });</pre>
  1334. <p>
  1335. Calling <tt>chain</tt> on a wrapped object will cause all future method calls to
  1336. return wrapped objects as well. When you've finished the computation,
  1337. use <tt>value</tt> to retrieve the final value. Here's an example of chaining
  1338. together a <b>map/flatten/reduce</b>, in order to get the word count of
  1339. every word in a song.
  1340. </p>
  1341. <pre>
  1342. var lyrics = [
  1343. {line : 1, words : "I'm a lumberjack and I'm okay"},
  1344. {line : 2, words : "I sleep all night and I work all day"},
  1345. {line : 3, words : "He's a lumberjack and he's okay"},
  1346. {line : 4, words : "He sleeps all night and he works all day"}
  1347. ];
  1348. _.chain(lyrics)
  1349. .map(function(line) { return line.words.split(' '); })
  1350. .flatten()
  1351. .reduce(function(counts, word) {
  1352. counts[word] = (counts[word] || 0) + 1;
  1353. return counts;
  1354. }, {}).value();
  1355. =&gt; {lumberjack : 2, all : 4, night : 2 ... }</pre>
  1356. <p>
  1357. In addition, the
  1358. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/prototype">Array prototype's
  1359. methods</a>
  1360. are proxied through the chained Underscore object, so you can slip a
  1361. <tt>reverse</tt> or a <tt>push</tt> into your chain, and continue to
  1362. modify the array.
  1363. </p>
  1364. <p id="chain">
  1365. <b class="header">chain</b><code>_.chain(obj)</code>
  1366. <br/>
  1367. Returns a wrapped object. Calling methods on this object will continue
  1368. to return wrapped objects until <tt>value</tt> is used.
  1369. </p>
  1370. <pre>
  1371. var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
  1372. var youngest = _.chain(stooges)
  1373. .sortBy(function(stooge){ return stooge.age; })
  1374. .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  1375. .first()
  1376. .value();
  1377. =&gt; "moe is 21"
  1378. </pre>
  1379. <p id="value">
  1380. <b class="header">value</b><code>_(obj).value()</code>
  1381. <br/>
  1382. Extracts the value of a wrapped object.
  1383. </p>
  1384. <pre>
  1385. _([1, 2, 3]).value();
  1386. =&gt; [1, 2, 3]
  1387. </pre>
  1388. <h2 id="links">Links &amp; Suggested Reading</h2>
  1389. <p>
  1390. <a href="http://mirven.github.com/underscore.lua/">Underscore.lua</a>,
  1391. a Lua port of the functions that are applicable in both languages.
  1392. Includes OOP-wrapping and chaining.
  1393. The <a href="http://github.com/mirven/underscore.lua">source</a> is
  1394. available on GitHub.
  1395. </p>
  1396. <p>
  1397. <a href="http://brianhaveri.github.com/Underscore.php/">Underscore.php</a>,
  1398. a PHP port of the functions that are applicable in both languages.
  1399. Includes OOP-wrapping and chaining.
  1400. The <a href="http://github.com/brianhaveri/Underscore.php">source</a> is
  1401. available on GitHub.
  1402. </p>
  1403. <p>
  1404. <a href="http://vti.github.com/underscore-perl/">Underscore-perl</a>,
  1405. a Perl port of many of the Underscore.js functions,
  1406. aimed at on Perl hashes and arrays, also
  1407. <a href="https://github.com/vti/underscore-perl/">available on GitHub</a>.
  1408. </p>
  1409. <p>
  1410. <a href="https://github.com/edtsech/underscore.string">Underscore.string</a>,
  1411. an Underscore extension that adds functions for string-manipulation:
  1412. <tt>trim</tt>, <tt>startsWith</tt>, <tt>contains</tt>, <tt>capitalize</tt>,
  1413. <tt>reverse</tt>, <tt>sprintf</tt>, and more.
  1414. </p>
  1415. <p>
  1416. Ruby's <a href="http://ruby-doc.org/core/classes/Enumerable.html">Enumerable</a> module.
  1417. </p>
  1418. <p>
  1419. <a href="http://www.prototypejs.org/">Prototype.js</a>, which provides
  1420. JavaScript with collection functions in the manner closest to Ruby's Enumerable.
  1421. </p>
  1422. <p>
  1423. Oliver Steele's
  1424. <a href="http://osteele.com/sources/javascript/functional/">Functional JavaScript</a>,
  1425. which includes comprehensive higher-order function support as well as string lambdas.
  1426. </p>
  1427. <p>
  1428. Michael Aufreiter's <a href="http://substance.io/#michael/data-js">Data.js</a>,
  1429. a data manipulation + persistence library for JavaScript.
  1430. </p>
  1431. <p>
  1432. Python's <a href="http://docs.python.org/library/itertools.html">itertools</a>.
  1433. </p>
  1434. <h2 id="changelog">Change Log</h2>
  1435. <p>
  1436. <b class="header">1.3.3</b> &mdash;
  1437. <small><i>April 10, 2012</i></small>
  1438. <br/>
  1439. <ul>
  1440. <li>
  1441. Many improvements to <tt>_.template</tt>, which now provides the
  1442. <tt>source</tt> of the template function as a property, for potentially
  1443. even more efficient pre-compilation on the server-side. You may now
  1444. also set the <tt>variable</tt> option when creating a template,
  1445. which will cause your passed-in data to be made available under the
  1446. variable you named, instead of using a <tt>with</tt> statement &mdash;
  1447. significantly improving the speed of rendering the template.
  1448. </li>
  1449. <li>
  1450. Added the <tt>pick</tt> function, which allows you to filter an
  1451. object literal with a whitelist of allowed property names.
  1452. </li>
  1453. <li>
  1454. Added the <tt>result</tt> function, for convenience when working
  1455. with APIs that allow either functions or raw properties.
  1456. </li>
  1457. <li>
  1458. Added the <tt>isFinite</tt> function, because sometimes knowing that
  1459. a value is a number just ain't quite enough.
  1460. </li>
  1461. <li>
  1462. The <tt>sortBy</tt> function may now also be passed the string name
  1463. of a property to use as the sort order on each object.
  1464. </li>
  1465. <li>
  1466. Fixed <tt>uniq</tt> to work with sparse arrays.
  1467. </li>
  1468. <li>
  1469. The <tt>difference</tt> function now performs a shallow flatten
  1470. instead of a deep one when computing array differences.
  1471. </li>
  1472. <li>
  1473. The <tt>debounce</tt> function now takes an <tt>immediate</tt>
  1474. parameter, which will cause the callback to fire on the leading
  1475. instead of the trailing edge.
  1476. </li>
  1477. </ul>
  1478. </p>
  1479. <p>
  1480. <b class="header">1.3.1</b> &mdash;
  1481. <small><i>Jan. 23, 2012</i></small>
  1482. <br/>
  1483. <ul>
  1484. <li>
  1485. Added an <tt>_.has</tt> function, as a safer way to use <tt>hasOwnProperty</tt>.
  1486. </li>
  1487. <li>
  1488. Added <tt>_.collect</tt> as an alias for <tt>_.map</tt>. Smalltalkers, rejoice.
  1489. </li>
  1490. <li>
  1491. Reverted an old change so that <tt>_.extend</tt> will correctly copy
  1492. over keys with undefined values again.
  1493. </li>
  1494. <li>
  1495. Bugfix to stop escapi

Large files files are truncated, but you can click here to view the full file