underscore-1.8.3/000077500000000000000000000000001250726036100136765ustar00rootroot00000000000000underscore-1.8.3/.eslintrc000066400000000000000000000014101250726036100155160ustar00rootroot00000000000000{ "env": { "browser": true, "node": true, "amd": true }, "rules": { "brace-style": [1, "1tbs"], "curly": [0, "multi"], "eqeqeq": [1, "smart"], "max-depth": [1, 4], "max-params": [1, 5], "new-cap": 2, "new-parens": 0, "no-constant-condition": 0, "no-div-regex": 1, "no-else-return": 1, "no-extra-parens": 1, "no-floating-decimal": 2, "no-inner-declarations": 2, "no-lonely-if": 1, "no-nested-ternary": 2, "no-new-object": 0, "no-new-func": 0, "no-underscore-dangle": 0, "quotes": [2, "single", "avoid-escape"], "radix": 2, "space-after-keywords": [2, "always"], "space-in-brackets": [2, "never"], "space-unary-word-ops": 2, "strict": 0, "wrap-iife": 2 } } underscore-1.8.3/.gitignore000066400000000000000000000000441250726036100156640ustar00rootroot00000000000000raw node_modules *.log *.idea *.swp underscore-1.8.3/.travis.yml000066400000000000000000000030121250726036100160030ustar00rootroot00000000000000language: node_js node_js: - "0.8" - "0.12" - "io.js" matrix: include: - node_js: "0.10" env: BROWSER=true before_install: - npm install -g npm@2.6 - npm install -g karma-cli before_script: - npm install karma-sauce-launcher - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start script: - npm test - "[ $BROWSER == false ] || npm run test-browser" # Karma sauce is limited to running about 5-7 browsers (or it will tiemout) at a time so we just run vendor by vendor here - "[ $BROWSER == false ] || karma start karma.conf-sauce.js --browsers FIREFOX_V4,FIREFOX_V11,FIREFOX_V20,FIREFOX_V30,FIREFOX_V35" - "[ $BROWSER == false ] || karma start karma.conf-sauce.js --browsers CHROME_V28,CHROME_V35,CHROME_V40,ANDROID_V4.0,ANDROID_V4.3" - "[ $BROWSER == false ] || karma start karma.conf-sauce.js --browsers INTERNET_EXPLORER_V9,INTERNET_EXPLORER_V10,INTERNET_EXPLORER_V11" - "[ $BROWSER == false ] || karma start karma.conf-sauce.js --browsers SAFARI_V5,SAFARI_V6,SAFARI_V7" - "[ $BROWSER == false ] || karma start karma.conf-sauce.js --browsers OPERA_V11,OPERA_V12" notifications: email: false env: global: - secure: bDZSBQfqr21hCayjcZ20IxrV6+XGhxQPFIfwWqEKLrF93Gu8LLVjZRxXE/mE8I8N4Z5WtDNb4ZHrm/TTzmcPa5MuHgIxEdknQCncobH8oimwc83SHwEPk6okeNKl39VlCjvvnmoe/V/KpnknuYn3Rqghtl/Uv9KLpCwskwjTtcw= - secure: SRECgXuwcZTcD3GVxTS2bYNgRyye4vq6BLrV2PH9FyNenowsKQR2EwlC/dppc1Q8NWMgv79J/R96q9JOFh+mEH9L5dlBb2yhnGH8amVeM/ChAJHT/F8YktKM453uVpz5fR00QcCQDDUOx6Pvx374ID0OKNpWKAkQBWA9mPTsLnE= matrix: BROWSER=falseunderscore-1.8.3/CNAME000066400000000000000000000000211250726036100144350ustar00rootroot00000000000000underscorejs.org underscore-1.8.3/CONTRIBUTING.md000066400000000000000000000014231250726036100161270ustar00rootroot00000000000000## How to contribute to Underscore.js * Before you open a ticket or send a pull request, [search](https://github.com/jashkenas/underscore/issues) for previous discussions about the same feature or issue. Add to the earlier ticket if you find one. * If you're proposing a new feature, make sure it isn't already implemented in [Underscore-Contrib](https://github.com/documentcloud/underscore-contrib). * Before sending a pull request for a feature, be sure to have [tests](http://underscorejs.org/test/). * Use the same coding style as the rest of the [codebase](https://github.com/jashkenas/underscore/blob/master/underscore.js). * In your pull request, do not add documentation or re-build the minified `underscore-min.js` file. We'll do those things before cutting a new release. underscore-1.8.3/LICENSE000066400000000000000000000021351250726036100147040ustar00rootroot00000000000000Copyright (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. underscore-1.8.3/README.md000066400000000000000000000023111250726036100151520ustar00rootroot00000000000000 __ /\ \ __ __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____ /\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\ \ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\ \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/ \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/ \ \____/ \/___/ Underscore.js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects. For Docs, License, Tests, and pre-packed downloads, see: http://underscorejs.org Underscore is an open-sourced component of DocumentCloud: https://github.com/documentcloud Many thanks to our contributors: https://github.com/jashkenas/underscore/contributors underscore-1.8.3/bower.json000066400000000000000000000004451250726036100157120ustar00rootroot00000000000000{ "name": "underscore", "version": "1.8.3", "main": "underscore.js", "keywords": ["util", "functional", "server", "client", "browser"], "ignore" : ["docs", "test", "*.yml", "CNAME", "index.html", "favicon.ico", "CONTRIBUTING.md", ".*", "component.json", "package.json", "karma.*"] } underscore-1.8.3/component.json000066400000000000000000000005531250726036100165760ustar00rootroot00000000000000{ "name" : "underscore", "description" : "JavaScript's functional programming helper library.", "keywords" : ["util", "functional", "server", "client", "browser"], "repo" : "jashkenas/underscore", "main" : "underscore.js", "scripts" : ["underscore.js"], "version" : "1.8.3", "license" : "MIT" } underscore-1.8.3/docs/000077500000000000000000000000001250726036100146265ustar00rootroot00000000000000underscore-1.8.3/docs/docco.css000066400000000000000000000233011250726036100164260ustar00rootroot00000000000000/*--------------------- Typography ----------------------------*/ @font-face { font-family: 'aller-light'; src: url('public/fonts/aller-light.eot'); src: url('public/fonts/aller-light.eot?#iefix') format('embedded-opentype'), url('public/fonts/aller-light.woff') format('woff'), url('public/fonts/aller-light.ttf') format('truetype'); font-weight: normal; font-style: normal; } @font-face { font-family: 'aller-bold'; src: url('public/fonts/aller-bold.eot'); src: url('public/fonts/aller-bold.eot?#iefix') format('embedded-opentype'), url('public/fonts/aller-bold.woff') format('woff'), url('public/fonts/aller-bold.ttf') format('truetype'); font-weight: normal; font-style: normal; } @font-face { font-family: 'roboto-black'; src: url('public/fonts/roboto-black.eot'); src: url('public/fonts/roboto-black.eot?#iefix') format('embedded-opentype'), url('public/fonts/roboto-black.woff') format('woff'), url('public/fonts/roboto-black.ttf') format('truetype'); font-weight: normal; font-style: normal; } /*--------------------- Layout ----------------------------*/ html { height: 100%; } body { font-family: "aller-light"; font-size: 14px; line-height: 18px; color: #30404f; margin: 0; padding: 0; height:100%; } #container { min-height: 100%; } a { color: #000; } b, strong { font-weight: normal; font-family: "aller-bold"; } p { margin: 15px 0 0px; } .annotation ul, .annotation ol { margin: 25px 0; } .annotation ul li, .annotation ol li { font-size: 14px; line-height: 18px; margin: 10px 0; } h1, h2, h3, h4, h5, h6 { color: #112233; line-height: 1em; font-weight: normal; font-family: "roboto-black"; text-transform: uppercase; margin: 30px 0 15px 0; } h1 { margin-top: 40px; } h2 { font-size: 1.26em; } hr { border: 0; background: 1px #ddd; height: 1px; margin: 20px 0; } pre, tt, code { font-size: 12px; line-height: 16px; font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; margin: 0; padding: 0; } .annotation pre { display: block; margin: 0; padding: 7px 10px; background: #fcfcfc; -moz-box-shadow: inset 0 0 10px rgba(0,0,0,0.1); -webkit-box-shadow: inset 0 0 10px rgba(0,0,0,0.1); box-shadow: inset 0 0 10px rgba(0,0,0,0.1); overflow-x: auto; } .annotation pre code { border: 0; padding: 0; background: transparent; } blockquote { border-left: 5px solid #ccc; margin: 0; padding: 1px 0 1px 1em; } .sections blockquote p { font-family: Menlo, Consolas, Monaco, monospace; font-size: 12px; line-height: 16px; color: #999; margin: 10px 0 0; white-space: pre-wrap; } ul.sections { list-style: none; padding:0 0 5px 0;; margin:0; } /* Force border-box so that % widths fit the parent container without overlap because of margin/padding. More Info : http://www.quirksmode.org/css/box.html */ ul.sections > li > div { -moz-box-sizing: border-box; /* firefox */ -ms-box-sizing: border-box; /* ie */ -webkit-box-sizing: border-box; /* webkit */ -khtml-box-sizing: border-box; /* konqueror */ box-sizing: border-box; /* css3 */ } /*---------------------- Jump Page -----------------------------*/ #jump_to, #jump_page { margin: 0; background: white; -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; font: 16px Arial; cursor: pointer; text-align: right; list-style: none; } #jump_to a { text-decoration: none; } #jump_to a.large { display: none; } #jump_to a.small { font-size: 22px; font-weight: bold; color: #676767; } #jump_to, #jump_wrapper { position: fixed; right: 0; top: 0; padding: 10px 15px; margin:0; } #jump_wrapper { display: none; padding:0; } #jump_to:hover #jump_wrapper { display: block; } #jump_page_wrapper{ position: fixed; right: 0; top: 0; bottom: 0; } #jump_page { padding: 5px 0 3px; margin: 0 0 25px 25px; max-height: 100%; overflow: auto; } #jump_page .source { display: block; padding: 15px; text-decoration: none; border-top: 1px solid #eee; } #jump_page .source:hover { background: #f5f5ff; } #jump_page .source:first-child { } /*---------------------- Low resolutions (> 320px) ---------------------*/ @media only screen and (min-width: 320px) { .pilwrap { display: none; } ul.sections > li > div { display: block; padding:5px 10px 0 10px; } ul.sections > li > div.annotation ul, ul.sections > li > div.annotation ol { padding-left: 30px; } ul.sections > li > div.content { overflow-x:auto; -webkit-box-shadow: inset 0 0 5px #e5e5ee; box-shadow: inset 0 0 5px #e5e5ee; border: 1px solid #dedede; margin:5px 10px 5px 10px; padding-bottom: 5px; } ul.sections > li > div.annotation pre { margin: 7px 0 7px; padding-left: 15px; } ul.sections > li > div.annotation p tt, .annotation code { background: #f8f8ff; border: 1px solid #dedede; font-size: 12px; padding: 0 0.2em; } } /*---------------------- (> 481px) ---------------------*/ @media only screen and (min-width: 481px) { #container { position: relative; } body { background-color: #F5F5FF; font-size: 15px; line-height: 21px; } pre, tt, code { line-height: 18px; } p, ul, ol { margin: 0 0 15px; } #jump_to { padding: 5px 10px; } #jump_wrapper { padding: 0; } #jump_to, #jump_page { font: 10px Arial; text-transform: uppercase; } #jump_page .source { padding: 5px 10px; } #jump_to a.large { display: inline-block; } #jump_to a.small { display: none; } #background { position: absolute; top: 0; bottom: 0; width: 350px; background: #fff; border-right: 1px solid #e5e5ee; z-index: -1; } ul.sections > li > div.annotation ul, ul.sections > li > div.annotation ol { padding-left: 40px; } ul.sections > li { white-space: nowrap; } ul.sections > li > div { display: inline-block; } ul.sections > li > div.annotation { max-width: 350px; min-width: 350px; min-height: 5px; padding: 13px; overflow-x: hidden; white-space: normal; vertical-align: top; text-align: left; } ul.sections > li > div.annotation pre { margin: 15px 0 15px; padding-left: 15px; } ul.sections > li > div.content { padding: 13px; vertical-align: top; border: none; -webkit-box-shadow: none; box-shadow: none; } .pilwrap { position: relative; display: inline; } .pilcrow { font: 12px Arial; text-decoration: none; color: #454545; position: absolute; top: 3px; left: -20px; padding: 1px 2px; opacity: 0; -webkit-transition: opacity 0.2s linear; } .for-h1 .pilcrow { top: 47px; } .for-h2 .pilcrow, .for-h3 .pilcrow, .for-h4 .pilcrow { top: 35px; } ul.sections > li > div.annotation:hover .pilcrow { opacity: 1; } } /*---------------------- (> 1025px) ---------------------*/ @media only screen and (min-width: 1025px) { body { font-size: 16px; line-height: 24px; } #background { width: 525px; } ul.sections > li > div.annotation { max-width: 525px; min-width: 525px; padding: 10px 25px 1px 50px; } ul.sections > li > div.content { padding: 9px 15px 16px 25px; } } /*---------------------- Syntax Highlighting -----------------------------*/ td.linenos { background-color: #f0f0f0; padding-right: 10px; } span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } /* github.com style (c) Vasily Polovnyov */ pre code { display: block; padding: 0.5em; color: #000; background: #f8f8ff } pre .hljs-comment, pre .hljs-template_comment, pre .hljs-diff .hljs-header, pre .hljs-javadoc { color: #408080; font-style: italic } pre .hljs-keyword, pre .hljs-assignment, pre .hljs-literal, pre .hljs-css .hljs-rule .hljs-keyword, pre .hljs-winutils, pre .hljs-javascript .hljs-title, pre .hljs-lisp .hljs-title, pre .hljs-subst { color: #954121; /*font-weight: bold*/ } pre .hljs-number, pre .hljs-hexcolor { color: #40a070 } pre .hljs-string, pre .hljs-tag .hljs-value, pre .hljs-phpdoc, pre .hljs-tex .hljs-formula { color: #219161; } pre .hljs-title, pre .hljs-id { color: #19469D; } pre .hljs-params { color: #00F; } pre .hljs-javascript .hljs-title, pre .hljs-lisp .hljs-title, pre .hljs-subst { font-weight: normal } pre .hljs-class .hljs-title, pre .hljs-haskell .hljs-label, pre .hljs-tex .hljs-command { color: #458; font-weight: bold } pre .hljs-tag, pre .hljs-tag .hljs-title, pre .hljs-rules .hljs-property, pre .hljs-django .hljs-tag .hljs-keyword { color: #000080; font-weight: normal } pre .hljs-attribute, pre .hljs-variable, pre .hljs-instancevar, pre .hljs-lisp .hljs-body { color: #008080 } pre .hljs-regexp { color: #B68 } pre .hljs-class { color: #458; font-weight: bold } pre .hljs-symbol, pre .hljs-ruby .hljs-symbol .hljs-string, pre .hljs-ruby .hljs-symbol .hljs-keyword, pre .hljs-ruby .hljs-symbol .hljs-keymethods, pre .hljs-lisp .hljs-keyword, pre .hljs-tex .hljs-special, pre .hljs-input_number { color: #990073 } pre .hljs-builtin, pre .hljs-constructor, pre .hljs-built_in, pre .hljs-lisp .hljs-title { color: #0086b3 } pre .hljs-preprocessor, pre .hljs-pi, pre .hljs-doctype, pre .hljs-shebang, pre .hljs-cdata { color: #999; font-weight: bold } pre .hljs-deletion { background: #fdd } pre .hljs-addition { background: #dfd } pre .hljs-diff .hljs-change { background: #0086b3 } pre .hljs-chunk { color: #aaa } pre .hljs-tex .hljs-formula { opacity: 0.5; } underscore-1.8.3/docs/favicon.ico000066400000000000000000000025761250726036100167610ustar00rootroot00000000000000h( qA*underscore-1.8.3/docs/images/000077500000000000000000000000001250726036100160735ustar00rootroot00000000000000underscore-1.8.3/docs/images/background.png000066400000000000000000000040741250726036100207250ustar00rootroot00000000000000PNG  IHDR22]tEXtSoftwareAdobe ImageReadyqe<IDATxڼv:DQUISǶA1zP$rL@O>e߿v߽{>|y{)͛ym&Ը0{t62L#o9i`< O~9D _ޞW5;Z pVYbJ)nH!B:>۪>DˠY)͌MĜt 0mU+Y($&ϩ!U|}ݢzQڬ6'NIjdOQCWR5uJVZXtsuR +ed)ui{ #wЎpx$(9/%DBÝvKa@n{^;UɓnɿCΤ!Ķ1y7]OP#P؉AN3y5P2$*"!U :iv(i.k.~0i\\w`ujrmt"!6(v l/hml#Kkeaw䅐40MPF'Z4zƦxl'"i5$&sNvmjunQٶG8RfzV3Cd;nJ&tWsugXsv ˔PWZSѝB`IENDB`underscore-1.8.3/docs/images/underscore.png000066400000000000000000000206721250726036100207610ustar00rootroot00000000000000PNG  IHDR);tEXtSoftwareAdobe ImageReadyqe<!\IDATxrv!Y7s'[RuwzeLt ,?.KO Dm'J,:3W %nGl4pV+\+s?_$W,>=M;]6BF6?N<#z\QΟ%mmo hRvahٷ6)O㓯xXu`x9'9\1u["Ug42X=J;UͭQ9U6K:"-*"ֶchompm0ios|qC3 ?\gnY=I?S[ Պb^eǵ ;+wnfs^U(z+IԕISƚb q *KY C#ɧIeD:o0$i ڢ!?0`똒mpPD!2,*Jqf/AZًf&["ĊTI:z,QbC hNd~=1#`%BlC}C; opsk2O`- &gܩZ8@V{uܷiJPU+Į2udd,y?׺iuB|b޸9ff[\7`|uܻ^Y=-sexKqx2XFj>pRlLͭpqO E46Fӹ\JTODp^c}(+T6={ͤ&[,!ءh;׫]o}b}V4bQιZMV L\L0ZI\OTo{))aJǑ\6TIIX[FPE9lTPq<<+SF|BpViΕP'A*B )6$.7%O:[u|m91OZIG. OHE*mQN=y]Fuz<2oDrtWW&6q1\*SQI[Ūx30{/O+M m ͭC=66BKNW̟G++tPX*uo8]OKO2Q]?{lzkdN/Փ)G Nlq<&AdtLܖ .UUIRPWzBޫl+SUIqѯȚ3{̙fLL8-a0ϛLZݾNhUlTڲQ-#i~rVOA U7&o=ĖM>q1^I5fPjZ#ֶ_-V;gG9IVABB2xczղkz[+ShvPR't^j2%Խ`/O\ z@8{t}u`霱գZ]}B[a`'{@&97 0w`@;q[BzD 280&am<Ӥ-3[vlqT*RMH@بBB+FA%J^ڎ`?QU0%)Yhذ5HŒնN0!\>r)jie$2Uʭ0 fl.1 žW\.,PKa!.:LF"Ôuޒݳw8@?zN^#0qJw?e˔m%H ~Ed.ˇ J\ŖoKT8n8{P3>gB_S [Lxaz\ga Z? aN?QVg/Phyi}ZcaFJy/iՔXXj}Vr=~{'gWV-₉&i_!0`QJt$' %9xJfֳ?&?;vs[Nh>T<s$V)CDb,*DWZѡbKwS[X >X JsOm߈^A >ŽV)H5B)Xދp}hiͫj~hmRZ9OxȻ畯$> ,qV)Ȓ v^RWw5|}=z]}x{b7^AuJd-+>lscP(==" )8zA_˒^ƄOLQNRD{NcQ  8̀V)G:@/#P;o鳽~Bdd'NHJiFkKt*|Cc<.(>Cl3)\Z@`4gP* `(lO9aP_qK<´5J!er8)Ld]Qrph 0&ӋקiL,>ߕPs[I~@`4kP*!/_(Qq"=L UOl/R ׺. FDR~0$]:Z`8`OI`Z YpE7 w2d&n)׶U>L %Tbߞ$#( 0 !^lL6}'FALv !3 r Iq3ʕV)1&VUTȐ9aHlru;| <2l2_n@`4w`*6+hvR,ݙ!_,2+4~(!!bjk{G,brsDFl&h6J AąL L-w%2TRqߴ []!;3d?ΖBcO 6sTdp JJ}!mЊ<=疤X&s^s2iJSxp2=oE{>#~wҙ&ut8T+O܏V7N_pc@*jyccpQXՕ.}©2yS;B~$R*!Kخ1GcE骆,L:D`XuhrZh~R*Yخ]eoT0PAXȻ$z^eq*/@:?,"8[՞^;gxS܃y77!Z(D\-yCn8m(Kh"2jOH#,Bud۹AO)<@u8γVUҟ^f@u(7˱u*)۷* >d{ 4NbEUFBm ?apkp[Tޘ{^8tiQ+2м)(6BU:! }/*؈ϙ䨁g'}bC2B= L|B W^L9e]jbmHRh=T{ $o{'߬c!1+"Th=&*P-=p/Bf7n<+!*PFTسZzc[$ E MH9@hwy6vwpڟ^TAz?N)~ȾʡOBwĢў6چyMOa@s}4+"{cxZhzW Nj28ˍCgs{ڤ@^cz>иsFcXx 8'Zx˽YIfۃ5ScgZӷ ڣ1!2afMb5ӴŶi}Kx4^hNj&?"0rfPW,`3Dɂ2f`>DEWӰ*(c,0UĮn5F`x Rͣx caԜmUݵ&wQA<δe\G RdONt(ÆB Cd,jh00}FŐ>B&2L RM\NG> m{Bƨ@hy=cgoӆVGDmOGsGT30 g7}cGn"X+ϫC1\;uObëlM@wALdF47;8 *UDkiCë 0چmNZ5ǟg>n9 y}vZVRjr&90"0`LUL:C>+iN p)}UI`&p ZV:<8PӃ2^ExF ̥PmRj_BCi; 2cK9W`y~! f>%J K9Է8VK]6%ԭ ɾs}-q 2NQj$qiZݱc  ߡJ/&%y0UJJU2}S>:lhINYUJ|(iֳr {>9@tOۯʷQ?_ 1yV0\ QVPA?2JP{ $}c6)ό=R<,q&t˹e|%zJ1޲Zf1GD۹]%jS 4 3ȋPX-[BCarULLKȣ@3JUˁ%PH7PMEe 86!~X6ػ6]%|npV`.Q : r(*U gI1"='|Մ19\O4ĠO1%ӫgBel[ .ko#?4LpeC90U fwd靀u6A:)j#r=_Gnާ\#P ,AgfR%ɖ-Kc J]Rs,0ak[u6y=_ B#iU88pӲDZއ??8؏zuQX|ظZDWT[;rD:e+_e*,Ih3`:8.ZU*c,8[kY)-(lOﲉPѴ_-G†ohck:N6Ӑ5[yWDqqܳA$T2gv߮")>aF!EzBˀPڼŘAܱm~IAZ' %,NJn6*tb}[kV$܋ƎO畾'υjY7nY-r̅MO:=|Ǟfjlc}NWnZK|Ж6a_oJЙ3F_LධWlBD6}<юJy9ޮ>챧DLt'"θf[{Y FĸdEz9[Խ(KdˑȂDq7n7==Ti͛hMǭEL>-e;9sȱzQ`g{V~|8'pSdcz-0[*9ד q{icj-/86<XԜ5Cyt cSҍj GbۚkBǣT}Wodl&BOyy({L b}4yZx7XߓyOJmؼk+.޹#z0ED ,Z`>hQ蟽ұ=F-uU-L(+H툐7w)U7̝4ʪ6|RIZdO`~bסE݆ۭ1`lK"o-7dvfGJ=j M^^ YuKҠ/V1\m`_y"{{B,T/vbQ3T_C_x)8glb\{}0&_ʹkD0u\DB=U*pWOW ){yHrg>-lVnP F9MŢ4^uL~bHGf{gZ+Tcl\d]= fBoA(([lM_e;-|`kT8<r4'QNK?dvsb[mE5zTG:f߯t|@MrgvϯeՑVKx)\00;e Ypܳ r1o@B0`y>y PfjZymA`euV0:1kC`!A`gsD_b @^q5:=j>kԓ+;z&Eq"~.ʅ=ąV0Gq鿍zIls˲5ja|';K;Ԩ}̉XqN03JmE~X_AG7k5d;i",Fl܊__ mX_ Z^_,;}ʿlwOb}@<_?CMw<w*noY~ $m-PkEbXa17n]鿿=z5u_~.P_M)nL|M4g뉰XK)$Z.wk @` @` U`?K1fm{.e0wk+n6qq\ۛOɋkXlFYˑN_\qr$Ķ)&6Zz\UjC?*Mr\_k"/??? 0"fkru͆/_@`M`%ןb/E3_F%}%&IENDB`underscore-1.8.3/docs/public/000077500000000000000000000000001250726036100161045ustar00rootroot00000000000000underscore-1.8.3/docs/public/stylesheets/000077500000000000000000000000001250726036100204605ustar00rootroot00000000000000underscore-1.8.3/docs/public/stylesheets/normalize.css000066400000000000000000000153321250726036100231760ustar00rootroot00000000000000/*! normalize.css v2.0.1 | MIT License | git.io/normalize */ /* ========================================================================== HTML5 display definitions ========================================================================== */ /* * Corrects `block` display not defined in IE 8/9. */ article, aside, details, figcaption, figure, footer, header, hgroup, nav, section, summary { display: block; } /* * Corrects `inline-block` display not defined in IE 8/9. */ audio, canvas, video { display: inline-block; } /* * Prevents modern browsers from displaying `audio` without controls. * Remove excess height in iOS 5 devices. */ audio:not([controls]) { display: none; height: 0; } /* * Addresses styling for `hidden` attribute not present in IE 8/9. */ [hidden] { display: none; } /* ========================================================================== Base ========================================================================== */ /* * 1. Sets default font family to sans-serif. * 2. Prevents iOS text size adjust after orientation change, without disabling * user zoom. */ html { font-family: sans-serif; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ -ms-text-size-adjust: 100%; /* 2 */ } /* * Removes default margin. */ body { margin: 0; } /* ========================================================================== Links ========================================================================== */ /* * Addresses `outline` inconsistency between Chrome and other browsers. */ a:focus { outline: thin dotted; } /* * Improves readability when focused and also mouse hovered in all browsers. */ a:active, a:hover { outline: 0; } /* ========================================================================== Typography ========================================================================== */ /* * Addresses `h1` font sizes within `section` and `article` in Firefox 4+, * Safari 5, and Chrome. */ h1 { font-size: 2em; } /* * Addresses styling not present in IE 8/9, Safari 5, and Chrome. */ abbr[title] { border-bottom: 1px dotted; } /* * Addresses style set to `bolder` in Firefox 4+, Safari 5, and Chrome. */ b, strong { font-weight: bold; } /* * Addresses styling not present in Safari 5 and Chrome. */ dfn { font-style: italic; } /* * Addresses styling not present in IE 8/9. */ mark { background: #ff0; color: #000; } /* * Corrects font family set oddly in Safari 5 and Chrome. */ code, kbd, pre, samp { font-family: monospace, serif; font-size: 1em; } /* * Improves readability of pre-formatted text in all browsers. */ pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; } /* * Sets consistent quote types. */ q { quotes: "\201C" "\201D" "\2018" "\2019"; } /* * Addresses inconsistent and variable font size in all browsers. */ small { font-size: 80%; } /* * Prevents `sub` and `sup` affecting `line-height` in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* ========================================================================== Embedded content ========================================================================== */ /* * Removes border when inside `a` element in IE 8/9. */ img { border: 0; } /* * Corrects overflow displayed oddly in IE 9. */ svg:not(:root) { overflow: hidden; } /* ========================================================================== Figures ========================================================================== */ /* * Addresses margin not present in IE 8/9 and Safari 5. */ figure { margin: 0; } /* ========================================================================== Forms ========================================================================== */ /* * Define consistent border, margin, and padding. */ fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } /* * 1. Corrects color not being inherited in IE 8/9. * 2. Remove padding so people aren't caught out if they zero out fieldsets. */ legend { border: 0; /* 1 */ padding: 0; /* 2 */ } /* * 1. Corrects font family not being inherited in all browsers. * 2. Corrects font size not being inherited in all browsers. * 3. Addresses margins set differently in Firefox 4+, Safari 5, and Chrome */ button, input, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 2 */ margin: 0; /* 3 */ } /* * Addresses Firefox 4+ setting `line-height` on `input` using `!important` in * the UA stylesheet. */ button, input { line-height: normal; } /* * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` * and `video` controls. * 2. Corrects inability to style clickable `input` types in iOS. * 3. Improves usability and consistency of cursor style between image-type * `input` and others. */ button, html input[type="button"], /* 1 */ input[type="reset"], input[type="submit"] { -webkit-appearance: button; /* 2 */ cursor: pointer; /* 3 */ } /* * Re-set default cursor for disabled elements. */ button[disabled], input[disabled] { cursor: default; } /* * 1. Addresses box sizing set to `content-box` in IE 8/9. * 2. Removes excess padding in IE 8/9. */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /* * 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome. * 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome * (include `-moz` to future-proof). */ input[type="search"] { -webkit-appearance: textfield; /* 1 */ -moz-box-sizing: content-box; -webkit-box-sizing: content-box; /* 2 */ box-sizing: content-box; } /* * Removes inner padding and search cancel button in Safari 5 and Chrome * on OS X. */ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /* * Removes inner padding and border in Firefox 4+. */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /* * 1. Removes default vertical scrollbar in IE 8/9. * 2. Improves readability and alignment in all browsers. */ textarea { overflow: auto; /* 1 */ vertical-align: top; /* 2 */ } /* ========================================================================== Tables ========================================================================== */ /* * Remove most spacing between table cells. */ table { border-collapse: collapse; border-spacing: 0; }underscore-1.8.3/docs/underscore.html000066400000000000000000005325371250726036100177040ustar00rootroot00000000000000 underscore.js
  • underscore.js

  • Underscore.js 1.8.3
    http://underscorejs.org
    (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
    Underscore may be freely distributed under the MIT license.
    
    (function() {
  • Baseline setup

  • Establish the root object, window in the browser, or exports on the server.

      var root = this;
  • Save the previous value of the _ variable.

      var previousUnderscore = root._;
  • Save bytes in the minified (but not gzipped) version:

      var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  • Create quick reference variables for speed access to core prototypes.

      var
        push             = ArrayProto.push,
        slice            = ArrayProto.slice,
        toString         = ObjProto.toString,
        hasOwnProperty   = ObjProto.hasOwnProperty;
  • All ECMAScript 5 native function implementations that we hope to use are declared here.

      var
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeBind         = FuncProto.bind,
        nativeCreate       = Object.create;
  • Naked function reference for surrogate-prototype-swapping.

      var Ctor = function(){};
  • Create a safe reference to the Underscore object for use below.

      var _ = function(obj) {
        if (obj instanceof _) return obj;
        if (!(this instanceof _)) return new _(obj);
        this._wrapped = obj;
      };
  • Export the Underscore object for Node.js, with backwards-compatibility for the old require() API. If we’re in the browser, add _ as a global object.

      if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
          exports = module.exports = _;
        }
        exports._ = _;
      } else {
        root._ = _;
      }
  • Current version.

      _.VERSION = '1.8.3';
  • Internal function that returns an efficient (for current engines) version of the passed-in callback, to be repeatedly applied in other Underscore functions.

      var optimizeCb = function(func, context, argCount) {
        if (context === void 0) return func;
        switch (argCount == null ? 3 : argCount) {
          case 1: return function(value) {
            return func.call(context, value);
          };
          case 2: return function(value, other) {
            return func.call(context, value, other);
          };
          case 3: return function(value, index, collection) {
            return func.call(context, value, index, collection);
          };
          case 4: return function(accumulator, value, index, collection) {
            return func.call(context, accumulator, value, index, collection);
          };
        }
        return function() {
          return func.apply(context, arguments);
        };
      };
  • A mostly-internal function to generate callbacks that can be applied to each element in a collection, returning the desired result — either identity, an arbitrary callback, a property matcher, or a property accessor.

      var cb = function(value, context, argCount) {
        if (value == null) return _.identity;
        if (_.isFunction(value)) return optimizeCb(value, context, argCount);
        if (_.isObject(value)) return _.matcher(value);
        return _.property(value);
      };
      _.iteratee = function(value, context) {
        return cb(value, context, Infinity);
      };
  • An internal function for creating assigner functions.

      var createAssigner = function(keysFunc, undefinedOnly) {
        return function(obj) {
          var length = arguments.length;
          if (length < 2 || obj == null) return obj;
          for (var index = 1; index < length; index++) {
            var source = arguments[index],
                keys = keysFunc(source),
                l = keys.length;
            for (var i = 0; i < l; i++) {
              var key = keys[i];
              if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
            }
          }
          return obj;
        };
      };
  • An internal function for creating a new object that inherits from another.

      var baseCreate = function(prototype) {
        if (!_.isObject(prototype)) return {};
        if (nativeCreate) return nativeCreate(prototype);
        Ctor.prototype = prototype;
        var result = new Ctor;
        Ctor.prototype = null;
        return result;
      };
    
      var property = function(key) {
        return function(obj) {
          return obj == null ? void 0 : obj[key];
        };
      };
  • Helper for collection methods to determine whether a collection should be iterated as an array or as an object Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094

      var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
      var getLength = property('length');
      var isArrayLike = function(collection) {
        var length = getLength(collection);
        return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
      };
  • Collection Functions

  • The cornerstone, an each implementation, aka forEach. Handles raw objects in addition to array-likes. Treats all sparse array-likes as if they were dense.

      _.each = _.forEach = function(obj, iteratee, context) {
        iteratee = optimizeCb(iteratee, context);
        var i, length;
        if (isArrayLike(obj)) {
          for (i = 0, length = obj.length; i < length; i++) {
            iteratee(obj[i], i, obj);
          }
        } else {
          var keys = _.keys(obj);
          for (i = 0, length = keys.length; i < length; i++) {
            iteratee(obj[keys[i]], keys[i], obj);
          }
        }
        return obj;
      };
  • Return the results of applying the iteratee to each element.

      _.map = _.collect = function(obj, iteratee, context) {
        iteratee = cb(iteratee, context);
        var keys = !isArrayLike(obj) && _.keys(obj),
            length = (keys || obj).length,
            results = Array(length);
        for (var index = 0; index < length; index++) {
          var currentKey = keys ? keys[index] : index;
          results[index] = iteratee(obj[currentKey], currentKey, obj);
        }
        return results;
      };
  • Create a reducing function iterating left or right.

      function createReduce(dir) {
  • Optimized iterator function as using arguments.length in the main function will deoptimize the, see #1991.

        function iterator(obj, iteratee, memo, keys, index, length) {
          for (; index >= 0 && index < length; index += dir) {
            var currentKey = keys ? keys[index] : index;
            memo = iteratee(memo, obj[currentKey], currentKey, obj);
          }
          return memo;
        }
    
        return function(obj, iteratee, memo, context) {
          iteratee = optimizeCb(iteratee, context, 4);
          var keys = !isArrayLike(obj) && _.keys(obj),
              length = (keys || obj).length,
              index = dir > 0 ? 0 : length - 1;
  • Determine the initial value if none is provided.

          if (arguments.length < 3) {
            memo = obj[keys ? keys[index] : index];
            index += dir;
          }
          return iterator(obj, iteratee, memo, keys, index, length);
        };
      }
  • Reduce builds up a single result from a list of values, aka inject, or foldl.

      _.reduce = _.foldl = _.inject = createReduce(1);
  • The right-associative version of reduce, also known as foldr.

      _.reduceRight = _.foldr = createReduce(-1);
  • Return the first value which passes a truth test. Aliased as detect.

      _.find = _.detect = function(obj, predicate, context) {
        var key;
        if (isArrayLike(obj)) {
          key = _.findIndex(obj, predicate, context);
        } else {
          key = _.findKey(obj, predicate, context);
        }
        if (key !== void 0 && key !== -1) return obj[key];
      };
  • Return all the elements that pass a truth test. Aliased as select.

      _.filter = _.select = function(obj, predicate, context) {
        var results = [];
        predicate = cb(predicate, context);
        _.each(obj, function(value, index, list) {
          if (predicate(value, index, list)) results.push(value);
        });
        return results;
      };
  • Return all the elements for which a truth test fails.

      _.reject = function(obj, predicate, context) {
        return _.filter(obj, _.negate(cb(predicate)), context);
      };
  • Determine whether all of the elements match a truth test. Aliased as all.

      _.every = _.all = function(obj, predicate, context) {
        predicate = cb(predicate, context);
        var keys = !isArrayLike(obj) && _.keys(obj),
            length = (keys || obj).length;
        for (var index = 0; index < length; index++) {
          var currentKey = keys ? keys[index] : index;
          if (!predicate(obj[currentKey], currentKey, obj)) return false;
        }
        return true;
      };
  • Determine if at least one element in the object matches a truth test. Aliased as any.

      _.some = _.any = function(obj, predicate, context) {
        predicate = cb(predicate, context);
        var keys = !isArrayLike(obj) && _.keys(obj),
            length = (keys || obj).length;
        for (var index = 0; index < length; index++) {
          var currentKey = keys ? keys[index] : index;
          if (predicate(obj[currentKey], currentKey, obj)) return true;
        }
        return false;
      };
  • Determine if the array or object contains a given item (using ===). Aliased as includes and include.

      _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
        if (!isArrayLike(obj)) obj = _.values(obj);
        if (typeof fromIndex != 'number' || guard) fromIndex = 0;
        return _.indexOf(obj, item, fromIndex) >= 0;
      };
  • Invoke a method (with arguments) on every item in a collection.

      _.invoke = function(obj, method) {
        var args = slice.call(arguments, 2);
        var isFunc = _.isFunction(method);
        return _.map(obj, function(value) {
          var func = isFunc ? method : value[method];
          return func == null ? func : func.apply(value, args);
        });
      };
  • Convenience version of a common use case of map: fetching a property.

      _.pluck = function(obj, key) {
        return _.map(obj, _.property(key));
      };
  • Convenience version of a common use case of filter: selecting only objects containing specific key:value pairs.

      _.where = function(obj, attrs) {
        return _.filter(obj, _.matcher(attrs));
      };
  • Convenience version of a common use case of find: getting the first object containing specific key:value pairs.

      _.findWhere = function(obj, attrs) {
        return _.find(obj, _.matcher(attrs));
      };
  • Return the maximum element (or element-based computation).

      _.max = function(obj, iteratee, context) {
        var result = -Infinity, lastComputed = -Infinity,
            value, computed;
        if (iteratee == null && obj != null) {
          obj = isArrayLike(obj) ? obj : _.values(obj);
          for (var i = 0, length = obj.length; i < length; i++) {
            value = obj[i];
            if (value > result) {
              result = value;
            }
          }
        } else {
          iteratee = cb(iteratee, context);
          _.each(obj, function(value, index, list) {
            computed = iteratee(value, index, list);
            if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
              result = value;
              lastComputed = computed;
            }
          });
        }
        return result;
      };
  • Return the minimum element (or element-based computation).

      _.min = function(obj, iteratee, context) {
        var result = Infinity, lastComputed = Infinity,
            value, computed;
        if (iteratee == null && obj != null) {
          obj = isArrayLike(obj) ? obj : _.values(obj);
          for (var i = 0, length = obj.length; i < length; i++) {
            value = obj[i];
            if (value < result) {
              result = value;
            }
          }
        } else {
          iteratee = cb(iteratee, context);
          _.each(obj, function(value, index, list) {
            computed = iteratee(value, index, list);
            if (computed < lastComputed || computed === Infinity && result === Infinity) {
              result = value;
              lastComputed = computed;
            }
          });
        }
        return result;
      };
  • Shuffle a collection, using the modern version of the Fisher-Yates shuffle.

      _.shuffle = function(obj) {
        var set = isArrayLike(obj) ? obj : _.values(obj);
        var length = set.length;
        var shuffled = Array(length);
        for (var index = 0, rand; index < length; index++) {
          rand = _.random(0, index);
          if (rand !== index) shuffled[index] = shuffled[rand];
          shuffled[rand] = set[index];
        }
        return shuffled;
      };
  • Sample n random values from a collection. If n is not specified, returns a single random element. The internal guard argument allows it to work with map.

      _.sample = function(obj, n, guard) {
        if (n == null || guard) {
          if (!isArrayLike(obj)) obj = _.values(obj);
          return obj[_.random(obj.length - 1)];
        }
        return _.shuffle(obj).slice(0, Math.max(0, n));
      };
  • Sort the object’s values by a criterion produced by an iteratee.

      _.sortBy = function(obj, iteratee, context) {
        iteratee = cb(iteratee, context);
        return _.pluck(_.map(obj, function(value, index, list) {
          return {
            value: value,
            index: index,
            criteria: iteratee(value, index, list)
          };
        }).sort(function(left, right) {
          var a = left.criteria;
          var b = right.criteria;
          if (a !== b) {
            if (a > b || a === void 0) return 1;
            if (a < b || b === void 0) return -1;
          }
          return left.index - right.index;
        }), 'value');
      };
  • An internal function used for aggregate “group by” operations.

      var group = function(behavior) {
        return function(obj, iteratee, context) {
          var result = {};
          iteratee = cb(iteratee, context);
          _.each(obj, function(value, index) {
            var key = iteratee(value, index, obj);
            behavior(result, value, key);
          });
          return result;
        };
      };
  • Groups the object’s values by a criterion. Pass either a string attribute to group by, or a function that returns the criterion.

      _.groupBy = group(function(result, value, key) {
        if (_.has(result, key)) result[key].push(value); else result[key] = [value];
      });
  • Indexes the object’s values by a criterion, similar to groupBy, but for when you know that your index values will be unique.

      _.indexBy = group(function(result, value, key) {
        result[key] = value;
      });
  • Counts instances of an object that group by a certain criterion. Pass either a string attribute to count by, or a function that returns the criterion.

      _.countBy = group(function(result, value, key) {
        if (_.has(result, key)) result[key]++; else result[key] = 1;
      });
  • Safely create a real, live array from anything iterable.

      _.toArray = function(obj) {
        if (!obj) return [];
        if (_.isArray(obj)) return slice.call(obj);
        if (isArrayLike(obj)) return _.map(obj, _.identity);
        return _.values(obj);
      };
  • Return the number of elements in an object.

      _.size = function(obj) {
        if (obj == null) return 0;
        return isArrayLike(obj) ? obj.length : _.keys(obj).length;
      };
  • Split a collection into two arrays: one whose elements all satisfy the given predicate, and one whose elements all do not satisfy the predicate.

      _.partition = function(obj, predicate, context) {
        predicate = cb(predicate, context);
        var pass = [], fail = [];
        _.each(obj, function(value, key, obj) {
          (predicate(value, key, obj) ? pass : fail).push(value);
        });
        return [pass, fail];
      };
  • Array Functions

  • Get the first element of an array. Passing n will return the first N values in the array. Aliased as head and take. The guard check allows it to work with _.map.

      _.first = _.head = _.take = function(array, n, guard) {
        if (array == null) return void 0;
        if (n == null || guard) return array[0];
        return _.initial(array, array.length - n);
      };
  • Returns everything but the last entry of the array. Especially useful on the arguments object. Passing n will return all the values in the array, excluding the last N.

      _.initial = function(array, n, guard) {
        return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
      };
  • Get the last element of an array. Passing n will return the last N values in the array.

      _.last = function(array, n, guard) {
        if (array == null) return void 0;
        if (n == null || guard) return array[array.length - 1];
        return _.rest(array, Math.max(0, array.length - n));
      };
  • Returns everything but the first entry of the array. Aliased as tail and drop. Especially useful on the arguments object. Passing an n will return the rest N values in the array.

      _.rest = _.tail = _.drop = function(array, n, guard) {
        return slice.call(array, n == null || guard ? 1 : n);
      };
  • Trim out all falsy values from an array.

      _.compact = function(array) {
        return _.filter(array, _.identity);
      };
  • Internal implementation of a recursive flatten function.

      var flatten = function(input, shallow, strict, startIndex) {
        var output = [], idx = 0;
        for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
          var value = input[i];
          if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
  • flatten current level of array or arguments object

            if (!shallow) value = flatten(value, shallow, strict);
            var j = 0, len = value.length;
            output.length += len;
            while (j < len) {
              output[idx++] = value[j++];
            }
          } else if (!strict) {
            output[idx++] = value;
          }
        }
        return output;
      };
  • Flatten out an array, either recursively (by default), or just one level.

      _.flatten = function(array, shallow) {
        return flatten(array, shallow, false);
      };
  • Return a version of the array that does not contain the specified value(s).

      _.without = function(array) {
        return _.difference(array, slice.call(arguments, 1));
      };
  • Produce a duplicate-free version of the array. If the array has already been sorted, you have the option of using a faster algorithm. Aliased as unique.

      _.uniq = _.unique = function(array, isSorted, iteratee, context) {
        if (!_.isBoolean(isSorted)) {
          context = iteratee;
          iteratee = isSorted;
          isSorted = false;
        }
        if (iteratee != null) iteratee = cb(iteratee, context);
        var result = [];
        var seen = [];
        for (var i = 0, length = getLength(array); i < length; i++) {
          var value = array[i],
              computed = iteratee ? iteratee(value, i, array) : value;
          if (isSorted) {
            if (!i || seen !== computed) result.push(value);
            seen = computed;
          } else if (iteratee) {
            if (!_.contains(seen, computed)) {
              seen.push(computed);
              result.push(value);
            }
          } else if (!_.contains(result, value)) {
            result.push(value);
          }
        }
        return result;
      };
  • Produce an array that contains the union: each distinct element from all of the passed-in arrays.

      _.union = function() {
        return _.uniq(flatten(arguments, true, true));
      };
  • Produce an array that contains every item shared between all the passed-in arrays.

      _.intersection = function(array) {
        var result = [];
        var argsLength = arguments.length;
        for (var i = 0, length = getLength(array); i < length; i++) {
          var item = array[i];
          if (_.contains(result, item)) continue;
          for (var j = 1; j < argsLength; j++) {
            if (!_.contains(arguments[j], item)) break;
          }
          if (j === argsLength) result.push(item);
        }
        return result;
      };
  • Take the difference between one array and a number of other arrays. Only the elements present in just the first array will remain.

      _.difference = function(array) {
        var rest = flatten(arguments, true, true, 1);
        return _.filter(array, function(value){
          return !_.contains(rest, value);
        });
      };
  • Zip together multiple lists into a single array — elements that share an index go together.

      _.zip = function() {
        return _.unzip(arguments);
      };
  • Complement of _.zip. Unzip accepts an array of arrays and groups each array’s elements on shared indices

      _.unzip = function(array) {
        var length = array && _.max(array, getLength).length || 0;
        var result = Array(length);
    
        for (var index = 0; index < length; index++) {
          result[index] = _.pluck(array, index);
        }
        return result;
      };
  • Converts lists into objects. Pass either a single array of [key, value] pairs, or two parallel arrays of the same length — one of keys, and one of the corresponding values.

      _.object = function(list, values) {
        var result = {};
        for (var i = 0, length = getLength(list); i < length; i++) {
          if (values) {
            result[list[i]] = values[i];
          } else {
            result[list[i][0]] = list[i][1];
          }
        }
        return result;
      };
  • Generator function to create the findIndex and findLastIndex functions

      function createPredicateIndexFinder(dir) {
        return function(array, predicate, context) {
          predicate = cb(predicate, context);
          var length = getLength(array);
          var index = dir > 0 ? 0 : length - 1;
          for (; index >= 0 && index < length; index += dir) {
            if (predicate(array[index], index, array)) return index;
          }
          return -1;
        };
      }
  • Returns the first index on an array-like that passes a predicate test

      _.findIndex = createPredicateIndexFinder(1);
      _.findLastIndex = createPredicateIndexFinder(-1);
  • Use a comparator function to figure out the smallest index at which an object should be inserted so as to maintain order. Uses binary search.

      _.sortedIndex = function(array, obj, iteratee, context) {
        iteratee = cb(iteratee, context, 1);
        var value = iteratee(obj);
        var low = 0, high = getLength(array);
        while (low < high) {
          var mid = Math.floor((low + high) / 2);
          if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
        }
        return low;
      };
  • Generator function to create the indexOf and lastIndexOf functions

      function createIndexFinder(dir, predicateFind, sortedIndex) {
        return function(array, item, idx) {
          var i = 0, length = getLength(array);
          if (typeof idx == 'number') {
            if (dir > 0) {
                i = idx >= 0 ? idx : Math.max(idx + length, i);
            } else {
                length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
            }
          } else if (sortedIndex && idx && length) {
            idx = sortedIndex(array, item);
            return array[idx] === item ? idx : -1;
          }
          if (item !== item) {
            idx = predicateFind(slice.call(array, i, length), _.isNaN);
            return idx >= 0 ? idx + i : -1;
          }
          for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
            if (array[idx] === item) return idx;
          }
          return -1;
        };
      }
  • Return the position of the first occurrence of an item in an array, or -1 if the item is not included in the array. If the array is large and already in sort order, pass true for isSorted to use binary search.

      _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
      _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
  • Generate an integer Array containing an arithmetic progression. A port of the native Python range() function. See the Python documentation.

      _.range = function(start, stop, step) {
        if (stop == null) {
          stop = start || 0;
          start = 0;
        }
        step = step || 1;
    
        var length = Math.max(Math.ceil((stop - start) / step), 0);
        var range = Array(length);
    
        for (var idx = 0; idx < length; idx++, start += step) {
          range[idx] = start;
        }
    
        return range;
      };
  • Function (ahem) Functions

  • Determines whether to execute a function as a constructor or a normal function with the provided arguments

      var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
        if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
        var self = baseCreate(sourceFunc.prototype);
        var result = sourceFunc.apply(self, args);
        if (_.isObject(result)) return result;
        return self;
      };
  • Create a function bound to a given object (assigning this, and arguments, optionally). Delegates to ECMAScript 5‘s native Function.bind if available.

      _.bind = function(func, context) {
        if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
        if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
        var args = slice.call(arguments, 2);
        var bound = function() {
          return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
        };
        return bound;
      };
  • Partially apply a function by creating a version that has had some of its arguments pre-filled, without changing its dynamic this context. _ acts as a placeholder, allowing any combination of arguments to be pre-filled.

      _.partial = function(func) {
        var boundArgs = slice.call(arguments, 1);
        var bound = function() {
          var position = 0, length = boundArgs.length;
          var args = Array(length);
          for (var i = 0; i < length; i++) {
            args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
          }
          while (position < arguments.length) args.push(arguments[position++]);
          return executeBound(func, bound, this, this, args);
        };
        return bound;
      };
  • Bind a number of an object’s methods to that object. Remaining arguments are the method names to be bound. Useful for ensuring that all callbacks defined on an object belong to it.

      _.bindAll = function(obj) {
        var i, length = arguments.length, key;
        if (length <= 1) throw new Error('bindAll must be passed function names');
        for (i = 1; i < length; i++) {
          key = arguments[i];
          obj[key] = _.bind(obj[key], obj);
        }
        return obj;
      };
  • Memoize an expensive function by storing its results.

      _.memoize = function(func, hasher) {
        var memoize = function(key) {
          var cache = memoize.cache;
          var address = '' + (hasher ? hasher.apply(this, arguments) : key);
          if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
          return cache[address];
        };
        memoize.cache = {};
        return memoize;
      };
  • Delays a function for the given number of milliseconds, and then calls it with the arguments supplied.

      _.delay = function(func, wait) {
        var args = slice.call(arguments, 2);
        return setTimeout(function(){
          return func.apply(null, args);
        }, wait);
      };
  • Defers a function, scheduling it to run after the current call stack has cleared.

      _.defer = _.partial(_.delay, _, 1);
  • Returns a function, that, when invoked, will only be triggered at most once during a given window of time. Normally, the throttled function will run as much as it can, without ever going more than once per wait duration; but if you’d like to disable the execution on the leading edge, pass {leading: false}. To disable execution on the trailing edge, ditto.

      _.throttle = function(func, wait, options) {
        var context, args, result;
        var timeout = null;
        var previous = 0;
        if (!options) options = {};
        var later = function() {
          previous = options.leading === false ? 0 : _.now();
          timeout = null;
          result = func.apply(context, args);
          if (!timeout) context = args = null;
        };
        return function() {
          var now = _.now();
          if (!previous && options.leading === false) previous = now;
          var remaining = wait - (now - previous);
          context = this;
          args = arguments;
          if (remaining <= 0 || remaining > wait) {
            if (timeout) {
              clearTimeout(timeout);
              timeout = null;
            }
            previous = now;
            result = func.apply(context, args);
            if (!timeout) context = args = null;
          } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining);
          }
          return result;
        };
      };
  • Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If immediate is passed, trigger the function on the leading edge, instead of the trailing.

      _.debounce = function(func, wait, immediate) {
        var timeout, args, context, timestamp, result;
    
        var later = function() {
          var last = _.now() - timestamp;
    
          if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last);
          } else {
            timeout = null;
            if (!immediate) {
              result = func.apply(context, args);
              if (!timeout) context = args = null;
            }
          }
        };
    
        return function() {
          context = this;
          args = arguments;
          timestamp = _.now();
          var callNow = immediate && !timeout;
          if (!timeout) timeout = setTimeout(later, wait);
          if (callNow) {
            result = func.apply(context, args);
            context = args = null;
          }
    
          return result;
        };
      };
  • Returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function.

      _.wrap = function(func, wrapper) {
        return _.partial(wrapper, func);
      };
  • Returns a negated version of the passed-in predicate.

      _.negate = function(predicate) {
        return function() {
          return !predicate.apply(this, arguments);
        };
      };
  • Returns a function that is the composition of a list of functions, each consuming the return value of the function that follows.

      _.compose = function() {
        var args = arguments;
        var start = args.length - 1;
        return function() {
          var i = start;
          var result = args[start].apply(this, arguments);
          while (i--) result = args[i].call(this, result);
          return result;
        };
      };
  • Returns a function that will only be executed on and after the Nth call.

      _.after = function(times, func) {
        return function() {
          if (--times < 1) {
            return func.apply(this, arguments);
          }
        };
      };
  • Returns a function that will only be executed up to (but not including) the Nth call.

      _.before = function(times, func) {
        var memo;
        return function() {
          if (--times > 0) {
            memo = func.apply(this, arguments);
          }
          if (times <= 1) func = null;
          return memo;
        };
      };
  • Returns a function that will be executed at most one time, no matter how often you call it. Useful for lazy initialization.

      _.once = _.partial(_.before, 2);
  • Object Functions

  • Keys in IE < 9 that won’t be iterated by for key in ... and thus missed.

      var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
      var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
                          'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
    
      function collectNonEnumProps(obj, keys) {
        var nonEnumIdx = nonEnumerableProps.length;
        var constructor = obj.constructor;
        var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
  • Constructor is a special case.

        var prop = 'constructor';
        if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
    
        while (nonEnumIdx--) {
          prop = nonEnumerableProps[nonEnumIdx];
          if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
            keys.push(prop);
          }
        }
      }
  • Retrieve the names of an object’s own properties. Delegates to ECMAScript 5‘s native Object.keys

      _.keys = function(obj) {
        if (!_.isObject(obj)) return [];
        if (nativeKeys) return nativeKeys(obj);
        var keys = [];
        for (var key in obj) if (_.has(obj, key)) keys.push(key);
  • Ahem, IE < 9.

        if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
      };
  • Retrieve all the property names of an object.

      _.allKeys = function(obj) {
        if (!_.isObject(obj)) return [];
        var keys = [];
        for (var key in obj) keys.push(key);
  • Ahem, IE < 9.

        if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
      };
  • Retrieve the values of an object’s properties.

      _.values = function(obj) {
        var keys = _.keys(obj);
        var length = keys.length;
        var values = Array(length);
        for (var i = 0; i < length; i++) {
          values[i] = obj[keys[i]];
        }
        return values;
      };
  • Returns the results of applying the iteratee to each element of the object In contrast to _.map it returns an object

      _.mapObject = function(obj, iteratee, context) {
        iteratee = cb(iteratee, context);
        var keys =  _.keys(obj),
              length = keys.length,
              results = {},
              currentKey;
          for (var index = 0; index < length; index++) {
            currentKey = keys[index];
            results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
          }
          return results;
      };
  • Convert an object into a list of [key, value] pairs.

      _.pairs = function(obj) {
        var keys = _.keys(obj);
        var length = keys.length;
        var pairs = Array(length);
        for (var i = 0; i < length; i++) {
          pairs[i] = [keys[i], obj[keys[i]]];
        }
        return pairs;
      };
  • Invert the keys and values of an object. The values must be serializable.

      _.invert = function(obj) {
        var result = {};
        var keys = _.keys(obj);
        for (var i = 0, length = keys.length; i < length; i++) {
          result[obj[keys[i]]] = keys[i];
        }
        return result;
      };
  • Return a sorted list of the function names available on the object. Aliased as methods

      _.functions = _.methods = function(obj) {
        var names = [];
        for (var key in obj) {
          if (_.isFunction(obj[key])) names.push(key);
        }
        return names.sort();
      };
  • Extend a given object with all the properties in passed-in object(s).

      _.extend = createAssigner(_.allKeys);
  • Assigns a given object with all the own properties in the passed-in object(s) (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)

      _.extendOwn = _.assign = createAssigner(_.keys);
  • Returns the first key on an object that passes a predicate test

      _.findKey = function(obj, predicate, context) {
        predicate = cb(predicate, context);
        var keys = _.keys(obj), key;
        for (var i = 0, length = keys.length; i < length; i++) {
          key = keys[i];
          if (predicate(obj[key], key, obj)) return key;
        }
      };
  • Return a copy of the object only containing the whitelisted properties.

      _.pick = function(object, oiteratee, context) {
        var result = {}, obj = object, iteratee, keys;
        if (obj == null) return result;
        if (_.isFunction(oiteratee)) {
          keys = _.allKeys(obj);
          iteratee = optimizeCb(oiteratee, context);
        } else {
          keys = flatten(arguments, false, false, 1);
          iteratee = function(value, key, obj) { return key in obj; };
          obj = Object(obj);
        }
        for (var i = 0, length = keys.length; i < length; i++) {
          var key = keys[i];
          var value = obj[key];
          if (iteratee(value, key, obj)) result[key] = value;
        }
        return result;
      };
  • Return a copy of the object without the blacklisted properties.

      _.omit = function(obj, iteratee, context) {
        if (_.isFunction(iteratee)) {
          iteratee = _.negate(iteratee);
        } else {
          var keys = _.map(flatten(arguments, false, false, 1), String);
          iteratee = function(value, key) {
            return !_.contains(keys, key);
          };
        }
        return _.pick(obj, iteratee, context);
      };
  • Fill in a given object with default properties.

      _.defaults = createAssigner(_.allKeys, true);
  • Creates an object that inherits from the given prototype object. If additional properties are provided then they will be added to the created object.

      _.create = function(prototype, props) {
        var result = baseCreate(prototype);
        if (props) _.extendOwn(result, props);
        return result;
      };
  • Create a (shallow-cloned) duplicate of an object.

      _.clone = function(obj) {
        if (!_.isObject(obj)) return obj;
        return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
      };
  • Invokes interceptor with the obj, and then returns obj. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

      _.tap = function(obj, interceptor) {
        interceptor(obj);
        return obj;
      };
  • Returns whether an object has a given set of key:value pairs.

      _.isMatch = function(object, attrs) {
        var keys = _.keys(attrs), length = keys.length;
        if (object == null) return !length;
        var obj = Object(object);
        for (var i = 0; i < length; i++) {
          var key = keys[i];
          if (attrs[key] !== obj[key] || !(key in obj)) return false;
        }
        return true;
      };
  • Internal recursive comparison function for isEqual.

      var eq = function(a, b, aStack, bStack) {
  • Identical objects are equal. 0 === -0, but they aren’t identical. See the Harmony egal proposal.

        if (a === b) return a !== 0 || 1 / a === 1 / b;
  • A strict comparison is necessary because null == undefined.

        if (a == null || b == null) return a === b;
  • Unwrap any wrapped objects.

        if (a instanceof _) a = a._wrapped;
        if (b instanceof _) b = b._wrapped;
  • Compare [[Class]] names.

        var className = toString.call(a);
        if (className !== toString.call(b)) return false;
        switch (className) {
  • Strings, numbers, regular expressions, dates, and booleans are compared by value.

          case '[object RegExp]':
  • RegExps are coerced to strings for comparison (Note: ‘’ + /a/i === ‘/a/i’)

          case '[object String]':
  • Primitives and their corresponding object wrappers are equivalent; thus, "5" is equivalent to new String("5").

            return '' + a === '' + b;
          case '[object Number]':
  • NaNs are equivalent, but non-reflexive. Object(NaN) is equivalent to NaN

            if (+a !== +a) return +b !== +b;
  • An egal comparison is performed for other numeric values.

            return +a === 0 ? 1 / +a === 1 / b : +a === +b;
          case '[object Date]':
          case '[object Boolean]':
  • Coerce dates and booleans to numeric primitive values. Dates are compared by their millisecond representations. Note that invalid dates with millisecond representations of NaN are not equivalent.

            return +a === +b;
        }
    
        var areArrays = className === '[object Array]';
        if (!areArrays) {
          if (typeof a != 'object' || typeof b != 'object') return false;
  • Objects with different constructors are not equivalent, but Objects or Arrays from different frames are.

          var aCtor = a.constructor, bCtor = b.constructor;
          if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
                                   _.isFunction(bCtor) && bCtor instanceof bCtor)
                              && ('constructor' in a && 'constructor' in b)) {
            return false;
          }
        }
  • Assume equality for cyclic structures. The algorithm for detecting cyclic structures is adapted from ES 5.1 section 15.12.3, abstract operation JO.

  • Initializing stack of traversed objects. It’s done here since we only need them for objects and arrays comparison.

        aStack = aStack || [];
        bStack = bStack || [];
        var length = aStack.length;
        while (length--) {
  • Linear search. Performance is inversely proportional to the number of unique nested structures.

          if (aStack[length] === a) return bStack[length] === b;
        }
  • Add the first object to the stack of traversed objects.

        aStack.push(a);
        bStack.push(b);
  • Recursively compare objects and arrays.

        if (areArrays) {
  • Compare array lengths to determine if a deep comparison is necessary.

          length = a.length;
          if (length !== b.length) return false;
  • Deep compare the contents, ignoring non-numeric properties.

          while (length--) {
            if (!eq(a[length], b[length], aStack, bStack)) return false;
          }
        } else {
  • Deep compare objects.

          var keys = _.keys(a), key;
          length = keys.length;
  • Ensure that both objects contain the same number of properties before comparing deep equality.

          if (_.keys(b).length !== length) return false;
          while (length--) {
  • Deep compare each member

            key = keys[length];
            if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
          }
        }
  • Remove the first object from the stack of traversed objects.

        aStack.pop();
        bStack.pop();
        return true;
      };
  • Perform a deep comparison to check if two objects are equal.

      _.isEqual = function(a, b) {
        return eq(a, b);
      };
  • Is a given array, string, or object empty? An “empty” object has no enumerable own-properties.

      _.isEmpty = function(obj) {
        if (obj == null) return true;
        if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
        return _.keys(obj).length === 0;
      };
  • Is a given value a DOM element?

      _.isElement = function(obj) {
        return !!(obj && obj.nodeType === 1);
      };
  • Is a given value an array? Delegates to ECMA5’s native Array.isArray

      _.isArray = nativeIsArray || function(obj) {
        return toString.call(obj) === '[object Array]';
      };
  • Is a given variable an object?

      _.isObject = function(obj) {
        var type = typeof obj;
        return type === 'function' || type === 'object' && !!obj;
      };
  • Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.

      _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
        _['is' + name] = function(obj) {
          return toString.call(obj) === '[object ' + name + ']';
        };
      });
  • Define a fallback version of the method in browsers (ahem, IE < 9), where there isn’t any inspectable “Arguments” type.

      if (!_.isArguments(arguments)) {
        _.isArguments = function(obj) {
          return _.has(obj, 'callee');
        };
      }
  • Optimize isFunction if appropriate. Work around some typeof bugs in old v8, IE 11 (#1621), and in Safari 8 (#1929).

      if (typeof /./ != 'function' && typeof Int8Array != 'object') {
        _.isFunction = function(obj) {
          return typeof obj == 'function' || false;
        };
      }
  • Is a given object a finite number?

      _.isFinite = function(obj) {
        return isFinite(obj) && !isNaN(parseFloat(obj));
      };
  • Is the given value NaN? (NaN is the only number which does not equal itself).

      _.isNaN = function(obj) {
        return _.isNumber(obj) && obj !== +obj;
      };
  • Is a given value a boolean?

      _.isBoolean = function(obj) {
        return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
      };
  • Is a given value equal to null?

      _.isNull = function(obj) {
        return obj === null;
      };
  • Is a given variable undefined?

      _.isUndefined = function(obj) {
        return obj === void 0;
      };
  • Shortcut function for checking if an object has a given property directly on itself (in other words, not on a prototype).

      _.has = function(obj, key) {
        return obj != null && hasOwnProperty.call(obj, key);
      };
  • Utility Functions

  • Run Underscore.js in noConflict mode, returning the _ variable to its previous owner. Returns a reference to the Underscore object.

      _.noConflict = function() {
        root._ = previousUnderscore;
        return this;
      };
  • Keep the identity function around for default iteratees.

      _.identity = function(value) {
        return value;
      };
  • Predicate-generating functions. Often useful outside of Underscore.

      _.constant = function(value) {
        return function() {
          return value;
        };
      };
    
      _.noop = function(){};
    
      _.property = property;
  • Generates a function for a given object that returns a given property.

      _.propertyOf = function(obj) {
        return obj == null ? function(){} : function(key) {
          return obj[key];
        };
      };
  • Returns a predicate for checking whether an object has a given set of key:value pairs.

      _.matcher = _.matches = function(attrs) {
        attrs = _.extendOwn({}, attrs);
        return function(obj) {
          return _.isMatch(obj, attrs);
        };
      };
  • Run a function n times.

      _.times = function(n, iteratee, context) {
        var accum = Array(Math.max(0, n));
        iteratee = optimizeCb(iteratee, context, 1);
        for (var i = 0; i < n; i++) accum[i] = iteratee(i);
        return accum;
      };
  • Return a random integer between min and max (inclusive).

      _.random = function(min, max) {
        if (max == null) {
          max = min;
          min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
      };
  • A (possibly faster) way to get the current timestamp as an integer.

      _.now = Date.now || function() {
        return new Date().getTime();
      };
  • List of HTML entities for escaping.

      var escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        '`': '&#x60;'
      };
      var unescapeMap = _.invert(escapeMap);
  • Functions for escaping and unescaping strings to/from HTML interpolation.

      var createEscaper = function(map) {
        var escaper = function(match) {
          return map[match];
        };
  • Regexes for identifying a key that needs to be escaped

        var source = '(?:' + _.keys(map).join('|') + ')';
        var testRegexp = RegExp(source);
        var replaceRegexp = RegExp(source, 'g');
        return function(string) {
          string = string == null ? '' : '' + string;
          return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
        };
      };
      _.escape = createEscaper(escapeMap);
      _.unescape = createEscaper(unescapeMap);
  • If the value of the named property is a function then invoke it with the object as context; otherwise, return it.

      _.result = function(object, property, fallback) {
        var value = object == null ? void 0 : object[property];
        if (value === void 0) {
          value = fallback;
        }
        return _.isFunction(value) ? value.call(object) : value;
      };
  • Generate a unique integer id (unique within the entire client session). Useful for temporary DOM ids.

      var idCounter = 0;
      _.uniqueId = function(prefix) {
        var id = ++idCounter + '';
        return prefix ? prefix + id : id;
      };
  • By default, Underscore uses ERB-style template delimiters, change the following template settings to use alternative delimiters.

      _.templateSettings = {
        evaluate    : /<%([\s\S]+?)%>/g,
        interpolate : /<%=([\s\S]+?)%>/g,
        escape      : /<%-([\s\S]+?)%>/g
      };
  • When customizing templateSettings, if you don’t want to define an interpolation, evaluation or escaping regex, we need one that is guaranteed not to match.

      var noMatch = /(.)^/;
  • Certain characters need to be escaped so that they can be put into a string literal.

      var escapes = {
        "'":      "'",
        '\\':     '\\',
        '\r':     'r',
        '\n':     'n',
        '\u2028': 'u2028',
        '\u2029': 'u2029'
      };
    
      var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
    
      var escapeChar = function(match) {
        return '\\' + escapes[match];
      };
  • JavaScript micro-templating, similar to John Resig’s implementation. Underscore templating handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. NB: oldSettings only exists for backwards compatibility.

      _.template = function(text, settings, oldSettings) {
        if (!settings && oldSettings) settings = oldSettings;
        settings = _.defaults({}, settings, _.templateSettings);
  • Combine delimiters into one regular expression via alternation.

        var matcher = RegExp([
          (settings.escape || noMatch).source,
          (settings.interpolate || noMatch).source,
          (settings.evaluate || noMatch).source
        ].join('|') + '|$', 'g');
  • Compile the template source, escaping string literals appropriately.

        var index = 0;
        var source = "__p+='";
        text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
          source += text.slice(index, offset).replace(escaper, escapeChar);
          index = offset + match.length;
    
          if (escape) {
            source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
          } else if (interpolate) {
            source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
          } else if (evaluate) {
            source += "';\n" + evaluate + "\n__p+='";
          }
  • Adobe VMs need the match returned to produce the correct offest.

          return match;
        });
        source += "';\n";
  • If a variable is not specified, place data values in local scope.

        if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
    
        source = "var __t,__p='',__j=Array.prototype.join," +
          "print=function(){__p+=__j.call(arguments,'');};\n" +
          source + 'return __p;\n';
    
        try {
          var render = new Function(settings.variable || 'obj', '_', source);
        } catch (e) {
          e.source = source;
          throw e;
        }
    
        var template = function(data) {
          return render.call(this, data, _);
        };
  • Provide the compiled source as a convenience for precompilation.

        var argument = settings.variable || 'obj';
        template.source = 'function(' + argument + '){\n' + source + '}';
    
        return template;
      };
  • Add a “chain” function. Start chaining a wrapped Underscore object.

      _.chain = function(obj) {
        var instance = _(obj);
        instance._chain = true;
        return instance;
      };
  • OOP

  • If Underscore is called as a function, it returns a wrapped object that can be used OO-style. This wrapper holds altered versions of all the underscore functions. Wrapped objects may be chained.

  • Helper function to continue chaining intermediate results.

      var result = function(instance, obj) {
        return instance._chain ? _(obj).chain() : obj;
      };
  • Add your own custom functions to the Underscore object.

      _.mixin = function(obj) {
        _.each(_.functions(obj), function(name) {
          var func = _[name] = obj[name];
          _.prototype[name] = function() {
            var args = [this._wrapped];
            push.apply(args, arguments);
            return result(this, func.apply(_, args));
          };
        });
      };
  • Add all of the Underscore functions to the wrapper object.

      _.mixin(_);
  • Add all mutator Array functions to the wrapper.

      _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
        var method = ArrayProto[name];
        _.prototype[name] = function() {
          var obj = this._wrapped;
          method.apply(obj, arguments);
          if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
          return result(this, obj);
        };
      });
  • Add all accessor Array functions to the wrapper.

      _.each(['concat', 'join', 'slice'], function(name) {
        var method = ArrayProto[name];
        _.prototype[name] = function() {
          return result(this, method.apply(this._wrapped, arguments));
        };
      });
  • Extracts the result from a wrapped and chained object.

      _.prototype.value = function() {
        return this._wrapped;
      };
  • Provide unwrapping proxy for some methods used in engine operations such as arithmetic and JSON stringification.

      _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
    
      _.prototype.toString = function() {
        return '' + this._wrapped;
      };
  • AMD registration happens at the end for compatibility with AMD loaders that may not enforce next-turn semantics on modules. Even though general practice for AMD registration is to be anonymous, underscore registers as a named module because, like jQuery, it is a base library that is popular enough to be bundled in a third party lib, but not be part of an AMD load request. Those cases could generate an error when an anonymous define() is called outside of a loader request.

      if (typeof define === 'function' && define.amd) {
        define('underscore', [], function() {
          return _;
        });
      }
    }.call(this));
underscore-1.8.3/favicon.ico000066400000000000000000000025761250726036100160310ustar00rootroot00000000000000h( qA*underscore-1.8.3/index.html000066400000000000000000003717651250726036100157160ustar00rootroot00000000000000 Underscore.js

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

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

A complete Test Suite is included for your perusal.

You may also read through the annotated source code.

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

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

Underscore is an open-source component of DocumentCloud.

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

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

Installation

  • Node.js npm install underscore
  • Meteor.js meteor add underscore
  • Require.js require(["underscore"], ...
  • Bower bower install underscore
  • Component component install jashkenas/underscore

Collection Functions (Arrays or Objects)

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

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

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

map_.map(list, iteratee, [context]) Alias: collect
Produces a new array of values by mapping each value in list through a transformation function (iteratee). The iteratee is passed three arguments: the value, then the index (or key) of the iteration, and finally a reference to the entire list.

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

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

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

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

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

var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
=> [4, 5, 2, 3, 0, 1]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

contains_.contains(list, value, [fromIndex]) Alias: includes
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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Array Functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique
Produces a duplicate-free version of the array, using === to test object equality. 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.

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

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

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

unzip_.unzip(*arrays)
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.

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

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

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

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

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

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

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

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

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

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

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

findIndex_.findIndex(array, predicate, [context])
Similar to _.indexOf, returns the first index where the predicate truth test passes; otherwise returns -1.

_.findIndex([4, 6, 8, 12], isPrime);
=> -1 // not found
_.findIndex([4, 6, 7, 12], isPrime);
=> 2

findLastIndex_.findLastIndex(array, predicate, [context])
Like _.findIndex but iterates the array in reverse, returning the index closest to the end where the predicate truth test passes.

var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},
             {'id': 2, 'name': 'Ted', 'last': 'White'},
             {'id': 3, 'name': 'Frank', 'last': 'James'},
             {'id': 4, 'name': 'Ted', 'last': 'Jones'}];
_.findLastIndex(users, {
  name: 'Ted'
});
=> 3

range_.range([start], stop, [step])
A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1. Returns a list of integers from start (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.

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

Function (uh, ahem) Functions

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

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

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

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

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

var subtract = function(a, b) { return b - a; };
sub5 = _.partial(subtract, 5);
sub5(20);
=> 15

// Using a placeholder
subFrom20 = _.partial(subtract, _, 20);
subFrom20(5);
=> 15

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Object Functions

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

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

allKeys_.allKeys(object)
Retrieve all the names of object's own and inherited properties.

function Stooge(name) {
  this.name = name;
}
Stooge.prototype.silly = true;
_.allKeys(new Stooge("Moe"));
=> ["name", "silly"]

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

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

mapObject_.mapObject(object, iteratee, [context])
Like map, but for objects. Transform the value of each property in turn.

_.mapObject({start: 5, end: 12}, function(val, key) {
  return val + 5;
});
=> {start: 10, end: 17}

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

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

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

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

create_.create(prototype, props)
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.

var moe = _.create(Stooge.prototype, {name: "Moe"});

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

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

findKey_.findKey(object, predicate, [context])
Similar to _.findIndex but for keys in objects. Returns the key where the predicate truth test passes or undefined.

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

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

extendOwn_.extendOwn(destination, *sources) Alias: assign
Like extend, but only copies own properties over to the destination object.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

propertyOf_.propertyOf(object)
Inverse of _.property. Takes an object and returns a function which will return the value of a provided property.

var stooge = {name: 'moe'};
_.propertyOf(stooge)('name');
=> 'moe'

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

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

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

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

isMatch_.isMatch(object, properties)
Tells you if the keys and values in properties are contained in object.

var stooge = {name: 'moe', age: 32};
_.isMatch(stooge, {age: 32});
=> true

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

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

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

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

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

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

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

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

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

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

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

_.isFunction(alert);
=> true

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

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

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

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

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

_.isFinite(-101);
=> true

_.isFinite(-Infinity);
=> false

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

_.isBoolean(null);
=> false

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

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

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

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

isError_.isError(object)
Returns true if object inherrits from an Error.

try {
  throw new TypeError("Example");
} catch (o_O) {
  _.isError(o_O)
}
=> true

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

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

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

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

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

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

Utility Functions

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

var underscore = _.noConflict();

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

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

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

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

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

obj.initialize = _.noop;

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

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

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

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

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

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

iteratee_.iteratee(value, [context])
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.
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.

var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
_.map(stooges, _.iteratee('age'));
=> [25, 21, 23];

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

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

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

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

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

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

result_.result(object, property, [defaultValue])
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 than the default will be returned. If defaultValue is a function its result will be returned.

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

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

_.now();
=> 1392066795351

template_.template(templateString, [settings])
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate 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.

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

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

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

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

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

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

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

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

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

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

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

Chaining

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

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

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

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

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

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

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

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

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

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

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

The Underscore documentation is also available in Simplified Chinese.

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

Dollar.swift, a Swift port of many of the Underscore.js functions and more. (source)

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

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

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

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

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

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

Ruby's Enumerable module.

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

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

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

Python's itertools.

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

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

Change Log

1.8.3April 2, 2015DiffDocs

  • Adds an _.create method, as a slimmed down version of Object.create.
  • Works around an iOS bug that can improperly cause isArrayLike to be JIT-ed. Also fixes a bug when passing 0 to isArrayLike.

1.8.2Feb. 22, 2015DiffDocs

  • Restores the previous old-Internet-Explorer edge cases changed in 1.8.1.
  • Adds a fromIndex argument to _.contains.

1.8.1Feb. 19, 2015DiffDocs

  • 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...

1.8.0Feb. 19, 2015DiffDocs

  • Added _.mapObject, which is similar to _.map, but just for the values in your object. (A real crowd pleaser.)
  • Added _.allKeys which returns all the enumerable property names on an object.
  • 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.
  • Added _.extendOwn — a less-useful form of _.extend that only copies over "own" properties.
  • Added _.findIndex and _.findLastIndex functions, which nicely complement their twin-twins _.indexOf and _.lastIndexOf.
  • Added an _.isMatch predicate function that tells you if an object matches key-value properties. A kissing cousin of _.isEqual and _.matcher.
  • Added an _.isError function.
  • Restored the _.unzip function as the inverse of zip. Flip-flopping. I know.
  • _.result now takes an optional fallback value (or function that provides the fallback value).
  • Added the _.propertyOf function generator as a mirror-world version of _.property.
  • Deprecated _.matches. It's now known by a more harmonious name — _.matcher.
  • Various and diverse code simplifications, changes for improved cross-platform compatibility, and edge case bug fixes.

1.7.0August 26, 2014DiffDocs

  • For consistency and speed across browsers, Underscore now ignores native array methods for forEach, map, reduce, reduceRight, filter, every, some, indexOf, and lastIndexOf. "Sparse" arrays are officially dead in Underscore.
  • Added _.iteratee to customize the iterators used by collection functions. Many Underscore methods will take a string argument for easier _.property-style lookups, an object for _.where-style filtering, or a function as a custom callback.
  • Added _.before as a counterpart to _.after.
  • Added _.negate to invert the truth value of a passed-in predicate.
  • Added _.noop as a handy empty placeholder function.
  • _.isEmpty now works with arguments objects.
  • _.has now guards against nullish objects.
  • _.omit can now take an iteratee function.
  • _.partition is now called with index and object.
  • _.matches creates a shallow clone of your object and only iterates over own properties.
  • Aligning better with the forthcoming ECMA6 Object.assign, _.extend only iterates over the object's own properties.
  • Falsey guards are no longer needed in _.extend and _.defaults—if the passed in argument isn't a JavaScript object it's just returned.
  • Fixed a few edge cases in _.max and _.min to handle arrays containing NaN (like strings or other objects) and Infinity and -Infinity.
  • Override base methods like each and some and they'll be used internally by other Underscore functions too.
  • The escape functions handle backticks (`), to deal with an IE ≤ 8 bug.
  • For consistency, _.union and _.difference now only work with arrays and not variadic args.
  • _.memoize exposes the cache of memoized values as a property on the returned function.
  • _.pick accepts iteratee and context arguments for a more advanced callback.
  • Underscore templates no longer accept an initial data object. _.template always returns a function now.
  • Optimizations and code cleanup aplenty.

1.6.0February 10, 2014DiffDocs

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

1.5.2September 7, 2013DiffDocs

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

1.5.1July 8, 2013DiffDocs

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

1.5.0July 6, 2013DiffDocs

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

1.4.4January 30, 2013DiffDocs

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

1.4.3December 4, 2012DiffDocs

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

1.4.2October 6, 2012DiffDocs

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

1.4.1October 1, 2012DiffDocs

  • Fixed a 1.4.0 regression in the lastIndexOf function.

1.4.0September 27, 2012DiffDocs

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

1.3.3April 10, 2012DiffDocs

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

1.3.1January 23, 2012DiffDocs

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

1.3.0January 11, 2012DiffDocs

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

1.2.4January 4, 2012DiffDocs

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

1.2.3December 7, 2011DiffDocs

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

1.2.2November 14, 2011DiffDocs

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

1.2.1October 24, 2011DiffDocs

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

1.2.0October 5, 2011DiffDocs

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

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

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

1.1.5March 20, 2011DiffDocs
Added an _.defaults function, for use merging together JS objects representing default options. Added an _.once function, for manufacturing functions that should only ever execute a single time. _.bind now delegates to the native 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.

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

1.1.3December 1, 2010DiffDocs
In CommonJS, Underscore may now be required with just:
var _ = require("underscore"). Added _.throttle and _.debounce functions. Removed _.breakLoop, in favor of an 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.

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

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

1.1.0August 18, 2010DiffDocs
The method signature of _.reduce has been changed to match the 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A DocumentCloud Project

underscore-1.8.3/karma.conf-sauce.js000066400000000000000000000042711250726036100173550ustar00rootroot00000000000000var _ = require('./'); // Browsers to run on Sauce Labs platforms var sauceBrowsers = _.reduce([ ['firefox', '35'], ['firefox', '30'], ['firefox', '20'], ['firefox', '11'], ['firefox', '4'], ['chrome', '40'], ['chrome', '35'], ['chrome', '28'], ['internet explorer', '11', 'Windows 8.1'], ['internet explorer', '10', 'Windows 8'], ['internet explorer', '9', 'Windows 7'], // Currently do not work with Karma. // ['internet explorer', '8', 'Windows 7'], // ['internet explorer', '7', 'Windows XP'], // ['internet explorer', '6', 'Windows XP'], ['opera', '12'], ['opera', '11'], ['android', '4.3'], ['android', '4.0'], ['safari', '8'], ['safari', '6'], ['safari', '7'], ['safari', '5'] ], function(memo, platform) { var label = (platform[0] + '_v' + platform[1]).replace(' ', '_').toUpperCase(); memo[label] = _.pick({ 'base': 'SauceLabs', 'browserName': platform[0], 'version': platform[1], 'platform': platform[2] }, Boolean); return memo; }, {}); module.exports = function(config) { if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) { console.log('Sauce environments not set --- Skipping'); return process.exit(0); } config.set({ basePath: '', frameworks: ['qunit'], singleRun: true, // list of files / patterns to load in the browser files: [ 'test/vendor/qunit-extras.js', 'underscore.js', 'test/*.js' ], // test results reporter to use reporters: ['dots', 'saucelabs'], port: 9876, colors: true, logLevel: config.LOG_INFO, sauceLabs: { build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')', startConnect: true, tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, // TODO(vojta): remove once SauceLabs supports websockets. // This speeds up the capturing a bit, as browsers don't even try to use websocket. transports: ['xhr-polling'], captureTimeout: 120000, customLaunchers: sauceBrowsers // Browsers to launch, commented out to prevent karma from starting // too many concurrent browsers and timing sauce out. // browsers: _.keys(sauceBrowsers) }); }; underscore-1.8.3/karma.conf.js000066400000000000000000000016561250726036100162630ustar00rootroot00000000000000// Note some browser launchers should be installed before using karma start. // For example: // $ npm install karma-firefox-launcher // $ karma start --browser=Firefox // See http://karma-runner.github.io/0.8/config/configuration-file.html module.exports = function(config) { config.set({ basePath: '', frameworks: ['qunit'], logLevel: config.LOG_INFO, port: 9876, // list of files / patterns to load in the browser files: [ 'test/vendor/qunit-extras.js', 'underscore.js', 'test/*.js' ], // Test results reporter to use // https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };underscore-1.8.3/package.json000066400000000000000000000022071250726036100161650ustar00rootroot00000000000000{ "name": "underscore", "description": "JavaScript's functional programming helper library.", "homepage": "http://underscorejs.org", "keywords": [ "util", "functional", "server", "client", "browser" ], "author": "Jeremy Ashkenas ", "repository": { "type": "git", "url": "git://github.com/jashkenas/underscore.git" }, "main": "underscore.js", "version": "1.8.3", "devDependencies": { "docco": "*", "eslint": "0.6.x", "karma": "~0.12.31", "karma-qunit": "~0.1.4", "qunit-cli": "~0.2.0", "uglify-js": "2.4.x" }, "scripts": { "test": "npm run test-node && npm run lint", "lint": "eslint underscore.js test/*.js", "test-node": "qunit-cli test/*.js", "test-browser": "npm i karma-phantomjs-launcher && ./node_modules/karma/bin/karma start", "build": "uglifyjs underscore.js -c \"evaluate=false\" --comments \"/ .*/\" -m --source-map underscore-min.map -o underscore-min.js", "doc": "docco underscore.js" }, "license": "MIT", "files": [ "underscore.js", "underscore-min.js", "underscore-min.map", "LICENSE" ] } underscore-1.8.3/test/000077500000000000000000000000001250726036100146555ustar00rootroot00000000000000underscore-1.8.3/test/.eslintrc000066400000000000000000000007611250726036100165050ustar00rootroot00000000000000{ "env": { "browser": true }, "globals": { "_": false, "test": false, "ok": false, "is": false, "equal": false, "deepEqual": false, "strictEqual": false, "notStrictEqual": false, "notEqual": false, "throws": false, "asyncTest": false, "start": false, "expect": false, "QUnit": false }, "rules": { "brace-style": 0, "dot-notation": 1, "no-new-wrappers": 0, "no-sparse-arrays": 0, "no-extend-native": 0 } } underscore-1.8.3/test/arrays.js000066400000000000000000000551631250726036100165260ustar00rootroot00000000000000(function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Arrays'); test('first', function() { equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array'); equal(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"'); deepEqual(_.first([1, 2, 3], 0), [], 'can pass an index to first'); deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can pass an index to first'); deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'can pass an index to first'); var result = (function(){ return _.first(arguments); }(4, 3, 2, 1)); equal(result, 4, 'works on an arguments object.'); result = _.map([[1, 2, 3], [1, 2, 3]], _.first); deepEqual(result, [1, 1], 'works well with _.map'); result = (function() { return _.first([1, 2, 3], 2); }()); deepEqual(result, [1, 2]); equal(_.first(null), undefined, 'handles nulls'); strictEqual(_.first([1, 2, 3], -1).length, 0); }); test('head', function() { strictEqual(_.first, _.head, 'alias for first'); }); test('take', function() { strictEqual(_.first, _.take, 'alias for first'); }); test('rest', function() { var numbers = [1, 2, 3, 4]; deepEqual(_.rest(numbers), [2, 3, 4], 'working rest()'); deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'working rest(0)'); deepEqual(_.rest(numbers, 2), [3, 4], 'rest can take an index'); var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4)); deepEqual(result, [2, 3, 4], 'works on arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.rest); deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map'); result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4)); deepEqual(result, [2, 3, 4], 'works on arguments object'); }); test('tail', function() { strictEqual(_.rest, _.tail, 'alias for rest'); }); test('drop', function() { strictEqual(_.rest, _.drop, 'alias for rest'); }); test('initial', function() { deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'working initial()'); deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'initial can take an index'); deepEqual(_.initial([1, 2, 3, 4], 6), [], 'initial can take a large index'); var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4)); deepEqual(result, [1, 2, 3], 'initial works on arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.initial); deepEqual(_.flatten(result), [1, 2, 1, 2], 'initial works with _.map'); }); test('last', function() { equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array'); deepEqual(_.last([1, 2, 3], 0), [], 'can pass an index to last'); deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can pass an index to last'); deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'can pass an index to last'); var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4)); equal(result, 4, 'works on an arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.last); deepEqual(result, [3, 3], 'works well with _.map'); equal(_.last(null), undefined, 'handles nulls'); strictEqual(_.last([1, 2, 3], -1).length, 0); }); test('compact', function() { equal(_.compact([0, 1, false, 2, false, 3]).length, 3, 'can trim out all falsy values'); var result = (function(){ return _.compact(arguments).length; }(0, 1, false, 2, false, 3)); equal(result, 3, 'works on an arguments object'); }); test('flatten', function() { deepEqual(_.flatten(null), [], 'Flattens supports null'); deepEqual(_.flatten(void 0), [], 'Flattens supports undefined'); deepEqual(_.flatten([[], [[]], []]), [], 'Flattens empty arrays'); deepEqual(_.flatten([[], [[]], []], true), [[]], 'Flattens empty arrays'); var list = [1, [2], [3, [[[4]]]]]; deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays'); deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays'); var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]])); deepEqual(result, [1, 2, 3, 4], 'works on an arguments object'); list = [[1], [2], [3], [[4]]]; deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays'); equal(_.flatten([_.range(10), _.range(10), 5, 1, 3], true).length, 23); equal(_.flatten([_.range(10), _.range(10), 5, 1, 3]).length, 23); equal(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3]).length, 1056003, 'Flatten can handle massive collections'); equal(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3], true).length, 1056003, 'Flatten can handle massive collections'); }); test('without', function() { var list = [1, 2, 1, 0, 3, 1, 4]; deepEqual(_.without(list, 0, 1), [2, 3, 4], 'can remove all instances of an object'); var result = (function(){ return _.without(arguments, 0, 1); }(1, 2, 1, 0, 3, 1, 4)); deepEqual(result, [2, 3, 4], 'works on an arguments object'); list = [{one : 1}, {two : 2}]; equal(_.without(list, {one : 1}).length, 2, 'uses real object identity for comparisons.'); equal(_.without(list, list[0]).length, 1, 'ditto.'); }); test('sortedIndex', function() { var numbers = [10, 20, 30, 40, 50], num = 35; var indexForNum = _.sortedIndex(numbers, num); equal(indexForNum, 3, '35 should be inserted at index 3'); var indexFor30 = _.sortedIndex(numbers, 30); equal(indexFor30, 2, '30 should be inserted at index 2'); var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}]; var iterator = function(obj){ return obj.x; }; strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2); strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3); var context = {1: 2, 2: 3, 3: 4}; iterator = function(obj){ return this[obj]; }; strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1); var values = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, 2147483647]; var array = Array(Math.pow(2, 32) - 1); var length = values.length; while (length--) { array[values[length]] = values[length]; } equal(_.sortedIndex(array, 2147483648), 2147483648, 'should work with large indexes'); }); test('uniq', function() { var list = [1, 2, 1, 3, 1, 4]; deepEqual(_.uniq(list), [1, 2, 3, 4], 'can find the unique values of an unsorted array'); list = [1, 1, 1, 2, 2, 3]; deepEqual(_.uniq(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster'); list = [{name: 'moe'}, {name: 'curly'}, {name: 'larry'}, {name: 'curly'}]; var iterator = function(value) { return value.name; }; deepEqual(_.map(_.uniq(list, false, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator'); deepEqual(_.map(_.uniq(list, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator without specifying whether array is sorted'); iterator = function(value) { return value + 1; }; list = [1, 2, 2, 3, 4, 4]; deepEqual(_.uniq(list, true, iterator), [1, 2, 3, 4], 'iterator works with sorted array'); var kittens = [ {kitten: 'Celery', cuteness: 8}, {kitten: 'Juniper', cuteness: 10}, {kitten: 'Spottis', cuteness: 10} ]; var expected = [ {kitten: 'Celery', cuteness: 8}, {kitten: 'Juniper', cuteness: 10} ]; deepEqual(_.uniq(kittens, true, 'cuteness'), expected, 'string iterator works with sorted array'); var result = (function(){ return _.uniq(arguments); }(1, 2, 1, 3, 1, 4)); deepEqual(result, [1, 2, 3, 4], 'works on an arguments object'); var a = {}, b = {}, c = {}; deepEqual(_.uniq([a, b, a, b, c]), [a, b, c], 'works on values that can be tested for equivalency but not ordered'); deepEqual(_.uniq(null), []); var context = {}; list = [3]; _.uniq(list, function(value, index, array) { strictEqual(this, context); strictEqual(value, 3); strictEqual(index, 0); strictEqual(array, list); }, context); deepEqual(_.uniq([{a: 1, b: 1}, {a: 1, b: 2}, {a: 1, b: 3}, {a: 2, b: 1}], 'a'), [{a: 1, b: 1}, {a: 2, b: 1}], 'can use pluck like iterator'); deepEqual(_.uniq([{0: 1, b: 1}, {0: 1, b: 2}, {0: 1, b: 3}, {0: 2, b: 1}], 0), [{0: 1, b: 1}, {0: 2, b: 1}], 'can use falsey pluck like iterator'); }); test('unique', function() { strictEqual(_.uniq, _.unique, 'alias for uniq'); }); test('intersection', function() { var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho']; deepEqual(_.intersection(stooges, leaders), ['moe'], 'can take the set intersection of two arrays'); deepEqual(_(stooges).intersection(leaders), ['moe'], 'can perform an OO-style intersection'); var result = (function(){ return _.intersection(arguments, leaders); }('moe', 'curly', 'larry')); deepEqual(result, ['moe'], 'works on an arguments object'); var theSixStooges = ['moe', 'moe', 'curly', 'curly', 'larry', 'larry']; deepEqual(_.intersection(theSixStooges, leaders), ['moe'], 'returns a duplicate-free array'); result = _.intersection([2, 4, 3, 1], [1, 2, 3]); deepEqual(result, [2, 3, 1], 'preserves order of first array'); result = _.intersection(null, [1, 2, 3]); equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as first argument'); equal(result.length, 0, 'returns an empty array when passed null as first argument'); result = _.intersection([1, 2, 3], null); equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as argument beyond the first'); equal(result.length, 0, 'returns an empty array when passed null as argument beyond the first'); }); test('union', function() { var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]); deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays'); result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]); deepEqual(result, [1, 2, 3, 30, 40, [1]], 'takes the union of a list of nested arrays'); var args = null; (function(){ args = arguments; }(1, 2, 3)); result = _.union(args, [2, 30, 1], [1, 40]); deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays'); result = _.union([1, 2, 3], 4); deepEqual(result, [1, 2, 3], 'restrict the union to arrays only'); }); test('difference', function() { var result = _.difference([1, 2, 3], [2, 30, 40]); deepEqual(result, [1, 3], 'takes the difference of two arrays'); result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]); deepEqual(result, [3, 4], 'takes the difference of three arrays'); result = _.difference([1, 2, 3], 1); deepEqual(result, [1, 2, 3], 'restrict the difference to arrays only'); }); test('zip', function() { var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true]; deepEqual(_.zip(names, ages, leaders), [ ['moe', 30, true], ['larry', 40, undefined], ['curly', 50, undefined] ], 'zipped together arrays of different lengths'); var stooges = _.zip(['moe', 30, 'stooge 1'], ['larry', 40, 'stooge 2'], ['curly', 50, 'stooge 3']); deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], ['stooge 1', 'stooge 2', 'stooge 3']], 'zipped pairs'); // In the case of difference lengths of the tuples undefineds // should be used as placeholder stooges = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']); deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], [undefined, undefined, 'extra data']], 'zipped pairs with empties'); var empty = _.zip([]); deepEqual(empty, [], 'unzipped empty'); deepEqual(_.zip(null), [], 'handles null'); deepEqual(_.zip(), [], '_.zip() returns []'); }); test('unzip', function() { deepEqual(_.unzip(null), [], 'handles null'); deepEqual(_.unzip([['a', 'b'], [1, 2]]), [['a', 1], ['b', 2]]); // complements zip var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); deepEqual(_.unzip(zipped), [['fred', 'barney'], [30, 40], [true, false]]); zipped = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']); deepEqual(_.unzip(zipped), [['moe', 30, void 0], ['larry', 40, void 0], ['curly', 50, 'extra data']], 'Uses length of largest array'); }); test('object', function() { var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]); var shouldBe = {moe: 30, larry: 40, curly: 50}; deepEqual(result, shouldBe, 'two arrays zipped together into an object'); result = _.object([['one', 1], ['two', 2], ['three', 3]]); shouldBe = {one: 1, two: 2, three: 3}; deepEqual(result, shouldBe, 'an array of pairs zipped together into an object'); var stooges = {moe: 30, larry: 40, curly: 50}; deepEqual(_.object(_.pairs(stooges)), stooges, 'an object converted to pairs and back to an object'); deepEqual(_.object(null), {}, 'handles nulls'); }); test('indexOf', function() { var numbers = [1, 2, 3]; equal(_.indexOf(numbers, 2), 1, 'can compute indexOf'); var result = (function(){ return _.indexOf(arguments, 2); }(1, 2, 3)); equal(result, 1, 'works on an arguments object'); _.each([null, void 0, [], false], function(val) { var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val); equal(_.indexOf(val, 2), -1, msg); equal(_.indexOf(val, 2, -1), -1, msg); equal(_.indexOf(val, 2, -20), -1, msg); equal(_.indexOf(val, 2, 15), -1, msg); }); var num = 35; numbers = [10, 20, 30, 40, 50]; var index = _.indexOf(numbers, num, true); equal(index, -1, '35 is not in the list'); numbers = [10, 20, 30, 40, 50]; num = 40; index = _.indexOf(numbers, num, true); equal(index, 3, '40 is in the list'); numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40; equal(_.indexOf(numbers, num, true), 1, '40 is in the list'); equal(_.indexOf(numbers, 6, true), -1, '6 isnt in the list'); equal(_.indexOf([1, 2, 5, 4, 6, 7], 5, true), -1, 'sorted indexOf doesn\'t uses binary search'); ok(_.every(['1', [], {}, null], function() { return _.indexOf(numbers, num, {}) === 1; }), 'non-nums as fromIndex make indexOf assume sorted'); numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; index = _.indexOf(numbers, 2, 5); equal(index, 7, 'supports the fromIndex argument'); index = _.indexOf([,,,], undefined); equal(index, 0, 'treats sparse arrays as if they were dense'); var array = [1, 2, 3, 1, 2, 3]; strictEqual(_.indexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index'); strictEqual(_.indexOf(array, 1, -2), -1, 'neg `fromIndex` starts at the right index'); strictEqual(_.indexOf(array, 2, -3), 4); _.each([-6, -8, -Infinity], function(fromIndex) { strictEqual(_.indexOf(array, 1, fromIndex), 0); }); strictEqual(_.indexOf([1, 2, 3], 1, true), 0); index = _.indexOf([], undefined, true); equal(index, -1, 'empty array with truthy `isSorted` returns -1'); }); test('indexOf with NaN', function() { strictEqual(_.indexOf([1, 2, NaN, NaN], NaN), 2, 'Expected [1, 2, NaN] to contain NaN'); strictEqual(_.indexOf([1, 2, Infinity], NaN), -1, 'Expected [1, 2, NaN] to contain NaN'); strictEqual(_.indexOf([1, 2, NaN, NaN], NaN, 1), 2, 'startIndex does not affect result'); strictEqual(_.indexOf([1, 2, NaN, NaN], NaN, -2), 2, 'startIndex does not affect result'); (function() { strictEqual(_.indexOf(arguments, NaN), 2, 'Expected arguments [1, 2, NaN] to contain NaN'); }(1, 2, NaN, NaN)); }); test('indexOf with +- 0', function() { _.each([-0, +0], function(val) { strictEqual(_.indexOf([1, 2, val, val], val), 2); strictEqual(_.indexOf([1, 2, val, val], -val), 2); }); }); test('lastIndexOf', function() { var numbers = [1, 0, 1]; var falsey = [void 0, '', 0, false, NaN, null, undefined]; equal(_.lastIndexOf(numbers, 1), 2); numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0]; numbers.lastIndexOf = null; equal(_.lastIndexOf(numbers, 1), 5, 'can compute lastIndexOf, even without the native function'); equal(_.lastIndexOf(numbers, 0), 8, 'lastIndexOf the other element'); var result = (function(){ return _.lastIndexOf(arguments, 1); }(1, 0, 1, 0, 0, 1, 0, 0, 0)); equal(result, 5, 'works on an arguments object'); _.each([null, void 0, [], false], function(val) { var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val); equal(_.lastIndexOf(val, 2), -1, msg); equal(_.lastIndexOf(val, 2, -1), -1, msg); equal(_.lastIndexOf(val, 2, -20), -1, msg); equal(_.lastIndexOf(val, 2, 15), -1, msg); }); numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; var index = _.lastIndexOf(numbers, 2, 2); equal(index, 1, 'supports the fromIndex argument'); var array = [1, 2, 3, 1, 2, 3]; strictEqual(_.lastIndexOf(array, 1, 0), 0, 'starts at the correct from idx'); strictEqual(_.lastIndexOf(array, 3), 5, 'should return the index of the last matched value'); strictEqual(_.lastIndexOf(array, 4), -1, 'should return `-1` for an unmatched value'); strictEqual(_.lastIndexOf(array, 1, 2), 0, 'should work with a positive `fromIndex`'); _.each([6, 8, Math.pow(2, 32), Infinity], function(fromIndex) { strictEqual(_.lastIndexOf(array, undefined, fromIndex), -1); strictEqual(_.lastIndexOf(array, 1, fromIndex), 3); strictEqual(_.lastIndexOf(array, '', fromIndex), -1); }); var expected = _.map(falsey, function(value) { return typeof value == 'number' ? -1 : 5; }); var actual = _.map(falsey, function(fromIndex) { return _.lastIndexOf(array, 3, fromIndex); }); deepEqual(actual, expected, 'should treat falsey `fromIndex` values, except `0` and `NaN`, as `array.length`'); strictEqual(_.lastIndexOf(array, 3, '1'), 5, 'should treat non-number `fromIndex` values as `array.length`'); strictEqual(_.lastIndexOf(array, 3, true), 5, 'should treat non-number `fromIndex` values as `array.length`'); strictEqual(_.lastIndexOf(array, 2, -3), 1, 'should work with a negative `fromIndex`'); strictEqual(_.lastIndexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index'); deepEqual(_.map([-6, -8, -Infinity], function(fromIndex) { return _.lastIndexOf(array, 1, fromIndex); }), [0, -1, -1]); }); test('lastIndexOf with NaN', function() { strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN), 3, 'Expected [1, 2, NaN] to contain NaN'); strictEqual(_.lastIndexOf([1, 2, Infinity], NaN), -1, 'Expected [1, 2, NaN] to contain NaN'); strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN, 2), 2, 'fromIndex does not affect result'); strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN, -2), 2, 'fromIndex does not affect result'); (function() { strictEqual(_.lastIndexOf(arguments, NaN), 3, 'Expected arguments [1, 2, NaN] to contain NaN'); }(1, 2, NaN, NaN)); }); test('lastIndexOf with +- 0', function() { _.each([-0, +0], function(val) { strictEqual(_.lastIndexOf([1, 2, val, val], val), 3); strictEqual(_.lastIndexOf([1, 2, val, val], -val), 3); strictEqual(_.lastIndexOf([-1, 1, 2], -val), -1); }); }); test('findIndex', function() { var objects = [ {'a': 0, 'b': 0}, {'a': 1, 'b': 1}, {'a': 2, 'b': 2}, {'a': 0, 'b': 0} ]; equal(_.findIndex(objects, function(obj) { return obj.a === 0; }), 0); equal(_.findIndex(objects, function(obj) { return obj.b * obj.a === 4; }), 2); equal(_.findIndex(objects, 'a'), 1, 'Uses lookupIterator'); equal(_.findIndex(objects, function(obj) { return obj.b * obj.a === 5; }), -1); equal(_.findIndex(null, _.noop), -1); strictEqual(_.findIndex(objects, function(a) { return a.foo === null; }), -1); _.findIndex([{a: 1}], function(a, key, obj) { equal(key, 0); deepEqual(obj, [{a: 1}]); strictEqual(this, objects, 'called with context'); }, objects); var sparse = []; sparse[20] = {'a': 2, 'b': 2}; equal(_.findIndex(sparse, function(obj) { return obj && obj.b * obj.a === 4; }), 20, 'Works with sparse arrays'); var array = [1, 2, 3, 4]; array.match = 55; strictEqual(_.findIndex(array, function(x) { return x === 55; }), -1, 'doesn\'t match array-likes keys'); }); test('findLastIndex', function() { var objects = [ {'a': 0, 'b': 0}, {'a': 1, 'b': 1}, {'a': 2, 'b': 2}, {'a': 0, 'b': 0} ]; equal(_.findLastIndex(objects, function(obj) { return obj.a === 0; }), 3); equal(_.findLastIndex(objects, function(obj) { return obj.b * obj.a === 4; }), 2); equal(_.findLastIndex(objects, 'a'), 2, 'Uses lookupIterator'); equal(_.findLastIndex(objects, function(obj) { return obj.b * obj.a === 5; }), -1); equal(_.findLastIndex(null, _.noop), -1); strictEqual(_.findLastIndex(objects, function(a) { return a.foo === null; }), -1); _.findLastIndex([{a: 1}], function(a, key, obj) { equal(key, 0); deepEqual(obj, [{a: 1}]); strictEqual(this, objects, 'called with context'); }, objects); var sparse = []; sparse[20] = {'a': 2, 'b': 2}; equal(_.findLastIndex(sparse, function(obj) { return obj && obj.b * obj.a === 4; }), 20, 'Works with sparse arrays'); var array = [1, 2, 3, 4]; array.match = 55; strictEqual(_.findLastIndex(array, function(x) { return x === 55; }), -1, 'doesn\'t match array-likes keys'); }); test('range', function() { deepEqual(_.range(0), [], 'range with 0 as a first argument generates an empty array'); deepEqual(_.range(4), [0, 1, 2, 3], 'range with a single positive argument generates an array of elements 0,1,2,...,n-1'); deepEqual(_.range(5, 8), [5, 6, 7], 'range with two arguments a & b, a<b generates an array of elements a,a+1,a+2,...,b-2,b-1'); deepEqual(_.range(8, 5), [], 'range with two arguments a & b, b<a generates an empty array'); deepEqual(_.range(3, 10, 3), [3, 6, 9], 'range with three arguments a & b & c, c < b-a, a < b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) < c'); deepEqual(_.range(3, 10, 15), [3], 'range with three arguments a & b & c, c > b-a, a < b generates an array with a single element, equal to a'); deepEqual(_.range(12, 7, -2), [12, 10, 8], 'range with three arguments a & b & c, a > b, c < 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b'); deepEqual(_.range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs'); }); }()); underscore-1.8.3/test/chaining.js000066400000000000000000000061671250726036100170050ustar00rootroot00000000000000(function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Chaining'); test('map/flatten/reduce', function() { var lyrics = [ 'I\'m a lumberjack and I\'m okay', 'I sleep all night and I work all day', 'He\'s a lumberjack and he\'s okay', 'He sleeps all night and he works all day' ]; var counts = _(lyrics).chain() .map(function(line) { return line.split(''); }) .flatten() .reduce(function(hash, l) { hash[l] = hash[l] || 0; hash[l]++; return hash; }, {}).value(); equal(counts.a, 16, 'counted all the letters in the song'); equal(counts.e, 10, 'counted all the letters in the song'); }); test('select/reject/sortBy', function() { var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers = _(numbers).chain().select(function(n) { return n % 2 === 0; }).reject(function(n) { return n % 4 === 0; }).sortBy(function(n) { return -n; }).value(); deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers'); }); test('select/reject/sortBy in functional style', function() { var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers = _.chain(numbers).select(function(n) { return n % 2 === 0; }).reject(function(n) { return n % 4 === 0; }).sortBy(function(n) { return -n; }).value(); deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers'); }); test('reverse/concat/unshift/pop/map', function() { var numbers = [1, 2, 3, 4, 5]; numbers = _(numbers).chain() .reverse() .concat([5, 5, 5]) .unshift(17) .pop() .map(function(n){ return n * 2; }) .value(); deepEqual(numbers, [34, 10, 8, 6, 4, 2, 10, 10], 'can chain together array functions.'); }); test('splice', function() { var instance = _([1, 2, 3, 4, 5]).chain(); deepEqual(instance.splice(1, 3).value(), [1, 5]); deepEqual(instance.splice(1, 0).value(), [1, 5]); deepEqual(instance.splice(1, 1).value(), [1]); deepEqual(instance.splice(0, 1).value(), [], '#397 Can create empty array'); }); test('shift', function() { var instance = _([1, 2, 3]).chain(); deepEqual(instance.shift().value(), [2, 3]); deepEqual(instance.shift().value(), [3]); deepEqual(instance.shift().value(), [], '#397 Can create empty array'); }); test('pop', function() { var instance = _([1, 2, 3]).chain(); deepEqual(instance.pop().value(), [1, 2]); deepEqual(instance.pop().value(), [1]); deepEqual(instance.pop().value(), [], '#397 Can create empty array'); }); test('chaining works in small stages', function() { var o = _([1, 2, 3, 4]).chain(); deepEqual(o.filter(function(i) { return i < 3; }).value(), [1, 2]); deepEqual(o.filter(function(i) { return i > 2; }).value(), [3, 4]); }); test('#1562: Engine proxies for chained functions', function() { var wrapped = _(512); strictEqual(wrapped.toJSON(), 512); strictEqual(wrapped.valueOf(), 512); strictEqual(+wrapped, 512); strictEqual(wrapped.toString(), '512'); strictEqual('' + wrapped, '512'); }); }()); underscore-1.8.3/test/collections.js000066400000000000000000001016701250726036100175360ustar00rootroot00000000000000(function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Collections'); test('each', function() { _.each([1, 2, 3], function(num, i) { equal(num, i + 1, 'each iterators provide value and iteration count'); }); var answers = []; _.each([1, 2, 3], function(num){ answers.push(num * this.multiplier);}, {multiplier : 5}); deepEqual(answers, [5, 10, 15], 'context object property accessed'); answers = []; _.each([1, 2, 3], function(num){ answers.push(num); }); deepEqual(answers, [1, 2, 3], 'aliased as "forEach"'); answers = []; var obj = {one : 1, two : 2, three : 3}; obj.constructor.prototype.four = 4; _.each(obj, function(value, key){ answers.push(key); }); deepEqual(answers, ['one', 'two', 'three'], 'iterating over objects works, and ignores the object prototype.'); delete obj.constructor.prototype.four; // ensure the each function is JITed _(1000).times(function() { _.each([], function(){}); }); var count = 0; obj = {1 : 'foo', 2 : 'bar', 3 : 'baz'}; _.each(obj, function(value, key){ count++; }); equal(count, 3, 'the fun should be called only 3 times'); var answer = null; _.each([1, 2, 3], function(num, index, arr){ if (_.include(arr, num)) answer = true; }); ok(answer, 'can reference the original collection from inside the iterator'); answers = 0; _.each(null, function(){ ++answers; }); equal(answers, 0, 'handles a null properly'); _.each(false, function(){}); var a = [1, 2, 3]; strictEqual(_.each(a, function(){}), a); strictEqual(_.each(null, function(){}), null); }); test('forEach', function() { strictEqual(_.each, _.forEach, 'alias for each'); }); test('lookupIterator with contexts', function() { _.each([true, false, 'yes', '', 0, 1, {}], function(context) { _.each([1], function() { equal(this, context); }, context); }); }); test('Iterating objects with sketchy length properties', function() { var functions = [ 'each', 'map', 'filter', 'find', 'some', 'every', 'max', 'min', 'groupBy', 'countBy', 'partition', 'indexBy' ]; var reducers = ['reduce', 'reduceRight']; var tricks = [ {length: '5'}, { length: { valueOf: _.constant(5) } }, {length: Math.pow(2, 53) + 1}, {length: Math.pow(2, 53)}, {length: null}, {length: -2}, {length: new Number(15)} ]; expect(tricks.length * (functions.length + reducers.length + 4)); _.each(tricks, function(trick) { var length = trick.length; strictEqual(_.size(trick), 1, 'size on obj with length: ' + length); deepEqual(_.toArray(trick), [length], 'toArray on obj with length: ' + length); deepEqual(_.shuffle(trick), [length], 'shuffle on obj with length: ' + length); deepEqual(_.sample(trick), length, 'sample on obj with length: ' + length); _.each(functions, function(method) { _[method](trick, function(val, key) { strictEqual(key, 'length', method + ': ran with length = ' + val); }); }); _.each(reducers, function(method) { strictEqual(_[method](trick), trick.length, method); }); }); }); test('Resistant to collection length and properties changing while iterating', function() { var collection = [ 'each', 'map', 'filter', 'find', 'some', 'every', 'max', 'min', 'reject', 'groupBy', 'countBy', 'partition', 'indexBy', 'reduce', 'reduceRight' ]; var array = [ 'findIndex', 'findLastIndex' ]; var object = [ 'mapObject', 'findKey', 'pick', 'omit' ]; _.each(collection.concat(array), function(method) { var sparseArray = [1, 2, 3]; sparseArray.length = 100; var answers = 0; _[method](sparseArray, function(){ ++answers; return method === 'every' ? true : null; }, {}); equal(answers, 100, method + ' enumerates [0, length)'); var growingCollection = [1, 2, 3], count = 0; _[method](growingCollection, function() { if (count < 10) growingCollection.push(count++); return method === 'every' ? true : null; }, {}); equal(count, 3, method + ' is resistant to length changes'); }); _.each(collection.concat(object), function(method) { var changingObject = {0: 0, 1: 1}, count = 0; _[method](changingObject, function(val) { if (count < 10) changingObject[++count] = val + 1; return method === 'every' ? true : null; }, {}); equal(count, 2, method + ' is resistant to property changes'); }); }); test('map', function() { var doubled = _.map([1, 2, 3], function(num){ return num * 2; }); deepEqual(doubled, [2, 4, 6], 'doubled numbers'); var tripled = _.map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier : 3}); deepEqual(tripled, [3, 6, 9], 'tripled numbers with context'); doubled = _([1, 2, 3]).map(function(num){ return num * 2; }); deepEqual(doubled, [2, 4, 6], 'OO-style doubled numbers'); var ids = _.map({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){ return n.id; }); deepEqual(ids, ['1', '2'], 'Can use collection methods on Array-likes.'); deepEqual(_.map(null, _.noop), [], 'handles a null properly'); deepEqual(_.map([1], function() { return this.length; }, [5]), [1], 'called with context'); // Passing a property name like _.pluck. var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}]; deepEqual(_.map(people, 'name'), ['moe', 'curly'], 'predicate string map to object properties'); }); test('collect', function() { strictEqual(_.map, _.collect, 'alias for map'); }); test('reduce', function() { var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }, 0); equal(sum, 6, 'can sum up an array'); var context = {multiplier : 3}; sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num * this.multiplier; }, 0, context); equal(sum, 18, 'can reduce with a context object'); sum = _.inject([1, 2, 3], function(sum, num){ return sum + num; }, 0); equal(sum, 6, 'aliased as "inject"'); sum = _([1, 2, 3]).reduce(function(sum, num){ return sum + num; }, 0); equal(sum, 6, 'OO-style reduce'); sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }); equal(sum, 6, 'default initial value'); var prod = _.reduce([1, 2, 3, 4], function(prod, num){ return prod * num; }); equal(prod, 24, 'can reduce via multiplication'); ok(_.reduce(null, _.noop, 138) === 138, 'handles a null (with initial value) properly'); equal(_.reduce([], _.noop, undefined), undefined, 'undefined can be passed as a special case'); equal(_.reduce([_], _.noop), _, 'collection of length one with no initial value returns the first item'); equal(_.reduce([], _.noop), undefined, 'returns undefined when collection is empty and no initial value'); }); test('foldl', function() { strictEqual(_.reduce, _.foldl, 'alias for reduce'); }); test('reduceRight', function() { var list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }, ''); equal(list, 'bazbarfoo', 'can perform right folds'); list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }); equal(list, 'bazbarfoo', 'default initial value'); var sum = _.reduceRight({a: 1, b: 2, c: 3}, function(sum, num){ return sum + num; }); equal(sum, 6, 'default initial value on object'); ok(_.reduceRight(null, _.noop, 138) === 138, 'handles a null (with initial value) properly'); equal(_.reduceRight([_], _.noop), _, 'collection of length one with no initial value returns the first item'); equal(_.reduceRight([], _.noop, undefined), undefined, 'undefined can be passed as a special case'); equal(_.reduceRight([], _.noop), undefined, 'returns undefined when collection is empty and no initial value'); // Assert that the correct arguments are being passed. var args, memo = {}, object = {a: 1, b: 2}, lastKey = _.keys(object).pop(); var expected = lastKey === 'a' ? [memo, 1, 'a', object] : [memo, 2, 'b', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, memo); deepEqual(args, expected); // And again, with numeric keys. object = {'2': 'a', '1': 'b'}; lastKey = _.keys(object).pop(); args = null; expected = lastKey === '2' ? [memo, 'a', '2', object] : [memo, 'b', '1', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, memo); deepEqual(args, expected); }); test('foldr', function() { strictEqual(_.reduceRight, _.foldr, 'alias for reduceRight'); }); test('find', function() { var array = [1, 2, 3, 4]; strictEqual(_.find(array, function(n) { return n > 2; }), 3, 'should return first found `value`'); strictEqual(_.find(array, function() { return false; }), void 0, 'should return `undefined` if `value` is not found'); array.dontmatch = 55; strictEqual(_.find(array, function(x) { return x === 55; }), void 0, 'iterates array-likes correctly'); // Matching an object like _.findWhere. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; deepEqual(_.find(list, {a: 1}), {a: 1, b: 2}, 'can be used as findWhere'); deepEqual(_.find(list, {b: 4}), {a: 1, b: 4}); ok(!_.find(list, {c: 1}), 'undefined when not found'); ok(!_.find([], {c: 1}), 'undefined when searching empty list'); var result = _.find([1, 2, 3], function(num){ return num * 2 === 4; }); equal(result, 2, 'found the first "2" and broke the loop'); var obj = { a: {x: 1, z: 3}, b: {x: 2, z: 2}, c: {x: 3, z: 4}, d: {x: 4, z: 1} }; deepEqual(_.find(obj, {x: 2}), {x: 2, z: 2}, 'works on objects'); deepEqual(_.find(obj, {x: 2, z: 1}), void 0); deepEqual(_.find(obj, function(x) { return x.x === 4; }), {x: 4, z: 1}); _.findIndex([{a: 1}], function(a, key, obj) { equal(key, 0); deepEqual(obj, [{a: 1}]); strictEqual(this, _, 'called with context'); }, _); }); test('detect', function() { strictEqual(_.detect, _.find, 'alias for detect'); }); test('filter', function() { var evenArray = [1, 2, 3, 4, 5, 6]; var evenObject = {one: 1, two: 2, three: 3}; var isEven = function(num){ return num % 2 === 0; }; deepEqual(_.filter(evenArray, isEven), [2, 4, 6]); deepEqual(_.filter(evenObject, isEven), [2], 'can filter objects'); deepEqual(_.filter([{}, evenObject, []], 'two'), [evenObject], 'predicate string map to object properties'); _.filter([1], function() { equal(this, evenObject, 'given context'); }, evenObject); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; deepEqual(_.filter(list, {a: 1}), [{a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]); deepEqual(_.filter(list, {b: 2}), [{a: 1, b: 2}, {a: 2, b: 2}]); deepEqual(_.filter(list, {}), list, 'Empty object accepts all items'); deepEqual(_(list).filter({}), list, 'OO-filter'); }); test('select', function() { strictEqual(_.filter, _.select, 'alias for filter'); }); test('reject', function() { var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 === 0; }); deepEqual(odds, [1, 3, 5], 'rejected each even number'); var context = 'obj'; var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){ equal(context, 'obj'); return num % 2 !== 0; }, context); deepEqual(evens, [2, 4, 6], 'rejected each odd number'); deepEqual(_.reject([odds, {one: 1, two: 2, three: 3}], 'two'), [odds], 'predicate string map to object properties'); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; deepEqual(_.reject(list, {a: 1}), [{a: 2, b: 2}]); deepEqual(_.reject(list, {b: 2}), [{a: 1, b: 3}, {a: 1, b: 4}]); deepEqual(_.reject(list, {}), [], 'Returns empty list given empty object'); deepEqual(_.reject(list, []), [], 'Returns empty list given empty array'); }); test('every', function() { ok(_.every([], _.identity), 'the empty set'); ok(_.every([true, true, true], _.identity), 'every true values'); ok(!_.every([true, false, true], _.identity), 'one false value'); ok(_.every([0, 10, 28], function(num){ return num % 2 === 0; }), 'even numbers'); ok(!_.every([0, 11, 28], function(num){ return num % 2 === 0; }), 'an odd number'); ok(_.every([1], _.identity) === true, 'cast to boolean - true'); ok(_.every([0], _.identity) === false, 'cast to boolean - false'); ok(!_.every([undefined, undefined, undefined], _.identity), 'works with arrays of undefined'); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; ok(!_.every(list, {a: 1, b: 2}), 'Can be called with object'); ok(_.every(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; ok(_.every(list, {b: 2}), 'Can be called with object'); ok(!_.every(list, 'c'), 'String mapped to object property'); ok(_.every({a: 1, b: 2, c: 3, d: 4}, _.isNumber), 'takes objects'); ok(!_.every({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); ok(_.every(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); ok(!_.every(['a', 'b', 'c', 'd', 'f'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); test('all', function() { strictEqual(_.all, _.every, 'alias for all'); }); test('some', function() { ok(!_.some([]), 'the empty set'); ok(!_.some([false, false, false]), 'all false values'); ok(_.some([false, false, true]), 'one true value'); ok(_.some([null, 0, 'yes', false]), 'a string'); ok(!_.some([null, 0, '', false]), 'falsy values'); ok(!_.some([1, 11, 29], function(num){ return num % 2 === 0; }), 'all odd numbers'); ok(_.some([1, 10, 29], function(num){ return num % 2 === 0; }), 'an even number'); ok(_.some([1], _.identity) === true, 'cast to boolean - true'); ok(_.some([0], _.identity) === false, 'cast to boolean - false'); ok(_.some([false, false, true])); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; ok(!_.some(list, {a: 5, b: 2}), 'Can be called with object'); ok(_.some(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; ok(_.some(list, {b: 2}), 'Can be called with object'); ok(!_.some(list, 'd'), 'String mapped to object property'); ok(_.some({a: '1', b: '2', c: '3', d: '4', e: 6}, _.isNumber), 'takes objects'); ok(!_.some({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); ok(_.some(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); ok(!_.some(['x', 'y', 'z'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); test('any', function() { strictEqual(_.any, _.some, 'alias for any'); }); test('includes', function() { _.each([null, void 0, 0, 1, NaN, {}, []], function(val) { strictEqual(_.includes(val, 'hasOwnProperty'), false); }); strictEqual(_.includes([1, 2, 3], 2), true, 'two is in the array'); ok(!_.includes([1, 3, 9], 2), 'two is not in the array'); strictEqual(_.includes([5, 4, 3, 2, 1], 5, true), true, 'doesn\'t delegate to binary search'); ok(_.includes({moe: 1, larry: 3, curly: 9}, 3) === true, '_.includes on objects checks their values'); ok(_([1, 2, 3]).includes(2), 'OO-style includes'); }); test('include', function() { strictEqual(_.includes, _.include, 'alias for includes'); }); test('contains', function() { strictEqual(_.includes, _.contains, 'alias for includes'); var numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; strictEqual(_.includes(numbers, 1, 1), true, 'contains takes a fromIndex'); strictEqual(_.includes(numbers, 1, -1), false, 'contains takes a fromIndex'); strictEqual(_.includes(numbers, 1, -2), false, 'contains takes a fromIndex'); strictEqual(_.includes(numbers, 1, -3), true, 'contains takes a fromIndex'); strictEqual(_.includes(numbers, 1, 6), true, 'contains takes a fromIndex'); strictEqual(_.includes(numbers, 1, 7), false, 'contains takes a fromIndex'); ok(_.every([1, 2, 3], _.partial(_.contains, numbers)), 'fromIndex is guarded'); }); test('includes with NaN', function() { strictEqual(_.includes([1, 2, NaN, NaN], NaN), true, 'Expected [1, 2, NaN] to contain NaN'); strictEqual(_.includes([1, 2, Infinity], NaN), false, 'Expected [1, 2, NaN] to contain NaN'); }); test('includes with +- 0', function() { _.each([-0, +0], function(val) { strictEqual(_.includes([1, 2, val, val], val), true); strictEqual(_.includes([1, 2, val, val], -val), true); strictEqual(_.includes([-1, 1, 2], -val), false); }); }); test('invoke', 5, function() { var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, 'sort'); deepEqual(result[0], [1, 5, 7], 'first array sorted'); deepEqual(result[1], [1, 2, 3], 'second array sorted'); _.invoke([{ method: function() { deepEqual(_.toArray(arguments), [1, 2, 3], 'called with arguments'); } }], 'method', 1, 2, 3); deepEqual(_.invoke([{a: null}, {}, {a: _.constant(1)}], 'a'), [null, void 0, 1], 'handles null & undefined'); throws(function() { _.invoke([{a: 1}], 'a'); }, TypeError, 'throws for non-functions'); }); test('invoke w/ function reference', function() { var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, Array.prototype.sort); deepEqual(result[0], [1, 5, 7], 'first array sorted'); deepEqual(result[1], [1, 2, 3], 'second array sorted'); deepEqual(_.invoke([1, 2, 3], function(a) { return a + this; }, 5), [6, 7, 8], 'receives params from invoke'); }); // Relevant when using ClojureScript test('invoke when strings have a call method', function() { String.prototype.call = function() { return 42; }; var list = [[5, 1, 7], [3, 2, 1]]; var s = 'foo'; equal(s.call(), 42, 'call function exists'); var result = _.invoke(list, 'sort'); deepEqual(result[0], [1, 5, 7], 'first array sorted'); deepEqual(result[1], [1, 2, 3], 'second array sorted'); delete String.prototype.call; equal(s.call, undefined, 'call function removed'); }); test('pluck', function() { var people = [{name: 'moe', age: 30}, {name: 'curly', age: 50}]; deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'pulls names out of objects'); deepEqual(_.pluck(people, 'address'), [undefined, undefined], 'missing properties are returned as undefined'); //compat: most flexible handling of edge cases deepEqual(_.pluck([{'[object Object]': 1}], {}), [1]); }); test('where', function() { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; var result = _.where(list, {a: 1}); equal(result.length, 3); equal(result[result.length - 1].b, 4); result = _.where(list, {b: 2}); equal(result.length, 2); equal(result[0].a, 1); result = _.where(list, {}); equal(result.length, list.length); function test() {} test.map = _.map; deepEqual(_.where([_, {a: 1, b: 2}, _], test), [_, _], 'checks properties given function'); }); test('findWhere', function() { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; var result = _.findWhere(list, {a: 1}); deepEqual(result, {a: 1, b: 2}); result = _.findWhere(list, {b: 4}); deepEqual(result, {a: 1, b: 4}); result = _.findWhere(list, {c: 1}); ok(_.isUndefined(result), 'undefined when not found'); result = _.findWhere([], {c: 1}); ok(_.isUndefined(result), 'undefined when searching empty list'); function test() {} test.map = _.map; equal(_.findWhere([_, {a: 1, b: 2}, _], test), _, 'checks properties given function'); function TestClass() { this.y = 5; this.x = 'foo'; } var expect = {c: 1, x: 'foo', y: 5}; deepEqual(_.findWhere([{y: 5, b: 6}, expect], new TestClass()), expect, 'uses class instance properties'); }); test('max', function() { equal(-Infinity, _.max(null), 'can handle null/undefined'); equal(-Infinity, _.max(undefined), 'can handle null/undefined'); equal(-Infinity, _.max(null, _.identity), 'can handle null/undefined'); equal(3, _.max([1, 2, 3]), 'can perform a regular Math.max'); var neg = _.max([1, 2, 3], function(num){ return -num; }); equal(neg, 1, 'can perform a computation-based max'); equal(-Infinity, _.max({}), 'Maximum value of an empty object'); equal(-Infinity, _.max([]), 'Maximum value of an empty array'); equal(_.max({'a': 'a'}), -Infinity, 'Maximum value of a non-numeric collection'); equal(299999, _.max(_.range(1, 300000)), 'Maximum value of a too-big array'); equal(3, _.max([1, 2, 3, 'test']), 'Finds correct max in array starting with num and containing a NaN'); equal(3, _.max(['test', 1, 2, 3]), 'Finds correct max in array starting with NaN'); var a = {x: -Infinity}; var b = {x: -Infinity}; var iterator = function(o){ return o.x; }; equal(_.max([a, b], iterator), a, 'Respects iterator return value of -Infinity'); deepEqual(_.max([{'a': 1}, {'a': 0, 'b': 3}, {'a': 4}, {'a': 2}], 'a'), {'a': 4}, 'String keys use property iterator'); deepEqual(_.max([0, 2], function(a){ return a * this.x; }, {x: 1}), 2, 'Iterator context'); deepEqual(_.max([[1], [2, 3], [-1, 4], [5]], 0), [5], 'Lookup falsy iterator'); deepEqual(_.max([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: 2}, 'Lookup falsy iterator'); }); test('min', function() { equal(Infinity, _.min(null), 'can handle null/undefined'); equal(Infinity, _.min(undefined), 'can handle null/undefined'); equal(Infinity, _.min(null, _.identity), 'can handle null/undefined'); equal(1, _.min([1, 2, 3]), 'can perform a regular Math.min'); var neg = _.min([1, 2, 3], function(num){ return -num; }); equal(neg, 3, 'can perform a computation-based min'); equal(Infinity, _.min({}), 'Minimum value of an empty object'); equal(Infinity, _.min([]), 'Minimum value of an empty array'); equal(_.min({'a': 'a'}), Infinity, 'Minimum value of a non-numeric collection'); var now = new Date(9999999999); var then = new Date(0); equal(_.min([now, then]), then); equal(1, _.min(_.range(1, 300000)), 'Minimum value of a too-big array'); equal(1, _.min([1, 2, 3, 'test']), 'Finds correct min in array starting with num and containing a NaN'); equal(1, _.min(['test', 1, 2, 3]), 'Finds correct min in array starting with NaN'); var a = {x: Infinity}; var b = {x: Infinity}; var iterator = function(o){ return o.x; }; equal(_.min([a, b], iterator), a, 'Respects iterator return value of Infinity'); deepEqual(_.min([{'a': 1}, {'a': 0, 'b': 3}, {'a': 4}, {'a': 2}], 'a'), {'a': 0, 'b': 3}, 'String keys use property iterator'); deepEqual(_.min([0, 2], function(a){ return a * this.x; }, {x: -1}), 2, 'Iterator context'); deepEqual(_.min([[1], [2, 3], [-1, 4], [5]], 0), [-1, 4], 'Lookup falsy iterator'); deepEqual(_.min([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: -1}, 'Lookup falsy iterator'); }); test('sortBy', function() { var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}]; people = _.sortBy(people, function(person){ return person.age; }); deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'stooges sorted by age'); var list = [undefined, 4, 1, undefined, 3, 2]; deepEqual(_.sortBy(list, _.identity), [1, 2, 3, 4, undefined, undefined], 'sortBy with undefined values'); list = ['one', 'two', 'three', 'four', 'five']; var sorted = _.sortBy(list, 'length'); deepEqual(sorted, ['one', 'two', 'four', 'five', 'three'], 'sorted by length'); function Pair(x, y) { this.x = x; this.y = y; } var collection = [ new Pair(1, 1), new Pair(1, 2), new Pair(1, 3), new Pair(1, 4), new Pair(1, 5), new Pair(1, 6), new Pair(2, 1), new Pair(2, 2), new Pair(2, 3), new Pair(2, 4), new Pair(2, 5), new Pair(2, 6), new Pair(undefined, 1), new Pair(undefined, 2), new Pair(undefined, 3), new Pair(undefined, 4), new Pair(undefined, 5), new Pair(undefined, 6) ]; var actual = _.sortBy(collection, function(pair) { return pair.x; }); deepEqual(actual, collection, 'sortBy should be stable'); deepEqual(_.sortBy(collection, 'x'), collection, 'sortBy accepts property string'); list = ['q', 'w', 'e', 'r', 't', 'y']; deepEqual(_.sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses _.identity if iterator is not specified'); }); test('groupBy', function() { var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; }); ok('0' in parity && '1' in parity, 'created a group for each value'); deepEqual(parity[0], [2, 4, 6], 'put each even number in the right group'); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.groupBy(list, 'length'); deepEqual(grouped['3'], ['one', 'two', 'six', 'ten']); deepEqual(grouped['4'], ['four', 'five', 'nine']); deepEqual(grouped['5'], ['three', 'seven', 'eight']); var context = {}; _.groupBy([{}], function(){ ok(this === context); }, context); grouped = _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); equal(grouped.constructor.length, 1); equal(grouped.hasOwnProperty.length, 2); var array = [{}]; _.groupBy(array, function(value, index, obj){ ok(obj === array); }); array = [1, 2, 1, 2, 3]; grouped = _.groupBy(array); equal(grouped['1'].length, 2); equal(grouped['3'].length, 1); var matrix = [ [1, 2], [1, 3], [2, 3] ]; deepEqual(_.groupBy(matrix, 0), {1: [[1, 2], [1, 3]], 2: [[2, 3]]}); deepEqual(_.groupBy(matrix, 1), {2: [[1, 2]], 3: [[1, 3], [2, 3]]}); }); test('indexBy', function() { var parity = _.indexBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); equal(parity['true'], 4); equal(parity['false'], 5); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.indexBy(list, 'length'); equal(grouped['3'], 'ten'); equal(grouped['4'], 'nine'); equal(grouped['5'], 'eight'); var array = [1, 2, 1, 2, 3]; grouped = _.indexBy(array); equal(grouped['1'], 1); equal(grouped['2'], 2); equal(grouped['3'], 3); }); test('countBy', function() { var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); equal(parity['true'], 2); equal(parity['false'], 3); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.countBy(list, 'length'); equal(grouped['3'], 4); equal(grouped['4'], 3); equal(grouped['5'], 3); var context = {}; _.countBy([{}], function(){ ok(this === context); }, context); grouped = _.countBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); equal(grouped.constructor, 1); equal(grouped.hasOwnProperty, 2); var array = [{}]; _.countBy(array, function(value, index, obj){ ok(obj === array); }); array = [1, 2, 1, 2, 3]; grouped = _.countBy(array); equal(grouped['1'], 2); equal(grouped['3'], 1); }); test('shuffle', function() { var numbers = _.range(10); var shuffled = _.shuffle(numbers); notStrictEqual(numbers, shuffled, 'original object is unmodified'); ok(_.every(_.range(10), function() { //appears consistent? return _.every(numbers, _.partial(_.contains, numbers)); }), 'contains the same members before and after shuffle'); shuffled = _.shuffle({a: 1, b: 2, c: 3, d: 4}); equal(shuffled.length, 4); deepEqual(shuffled.sort(), [1, 2, 3, 4], 'works on objects'); }); test('sample', function() { var numbers = _.range(10); var allSampled = _.sample(numbers, 10).sort(); deepEqual(allSampled, numbers, 'contains the same members before and after sample'); allSampled = _.sample(numbers, 20).sort(); deepEqual(allSampled, numbers, 'also works when sampling more objects than are present'); ok(_.contains(numbers, _.sample(numbers)), 'sampling a single element returns something from the array'); strictEqual(_.sample([]), undefined, 'sampling empty array with no number returns undefined'); notStrictEqual(_.sample([], 5), [], 'sampling empty array with a number returns an empty array'); notStrictEqual(_.sample([1, 2, 3], 0), [], 'sampling an array with 0 picks returns an empty array'); deepEqual(_.sample([1, 2], -1), [], 'sampling a negative number of picks returns an empty array'); ok(_.contains([1, 2, 3], _.sample({a: 1, b: 2, c: 3})), 'sample one value from an object'); }); test('toArray', function() { ok(!_.isArray(arguments), 'arguments object is not an array'); ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array'); var a = [1, 2, 3]; ok(_.toArray(a) !== a, 'array is cloned'); deepEqual(_.toArray(a), [1, 2, 3], 'cloned array contains same elements'); var numbers = _.toArray({one : 1, two : 2, three : 3}); deepEqual(numbers, [1, 2, 3], 'object flattened into array'); if (typeof document != 'undefined') { // test in IE < 9 var actual; try { actual = _.toArray(document.childNodes); } catch(ex) { } deepEqual(actual, _.map(document.childNodes, _.identity), 'works on NodeList'); } }); test('size', function() { equal(_.size({one : 1, two : 2, three : 3}), 3, 'can compute the size of an object'); equal(_.size([1, 2, 3]), 3, 'can compute the size of an array'); equal(_.size({length: 3, 0: 0, 1: 0, 2: 0}), 3, 'can compute the size of Array-likes'); var func = function() { return _.size(arguments); }; equal(func(1, 2, 3, 4), 4, 'can test the size of the arguments object'); equal(_.size('hello'), 5, 'can compute the size of a string literal'); equal(_.size(new String('hello')), 5, 'can compute the size of string object'); equal(_.size(null), 0, 'handles nulls'); equal(_.size(0), 0, 'handles numbers'); }); test('partition', function() { var list = [0, 1, 2, 3, 4, 5]; deepEqual(_.partition(list, function(x) { return x < 4; }), [[0, 1, 2, 3], [4, 5]], 'handles bool return values'); deepEqual(_.partition(list, function(x) { return x & 1; }), [[1, 3, 5], [0, 2, 4]], 'handles 0 and 1 return values'); deepEqual(_.partition(list, function(x) { return x - 3; }), [[0, 1, 2, 4, 5], [3]], 'handles other numeric return values'); deepEqual(_.partition(list, function(x) { return x > 1 ? null : true; }), [[0, 1], [2, 3, 4, 5]], 'handles null return values'); deepEqual(_.partition(list, function(x) { if (x < 2) return true; }), [[0, 1], [2, 3, 4, 5]], 'handles undefined return values'); deepEqual(_.partition({a: 1, b: 2, c: 3}, function(x) { return x > 1; }), [[2, 3], [1]], 'handles objects'); deepEqual(_.partition(list, function(x, index) { return index % 2; }), [[1, 3, 5], [0, 2, 4]], 'can reference the array index'); deepEqual(_.partition(list, function(x, index, arr) { return x === arr.length - 1; }), [[5], [0, 1, 2, 3, 4]], 'can reference the collection'); // Default iterator deepEqual(_.partition([1, false, true, '']), [[1, true], [false, '']], 'Default iterator'); deepEqual(_.partition([{x: 1}, {x: 0}, {x: 1}], 'x'), [[{x: 1}, {x: 1}], [{x: 0}]], 'Takes a string'); // Context var predicate = function(x){ return x === this.x; }; deepEqual(_.partition([1, 2, 3], predicate, {x: 2}), [[2], [1, 3]], 'partition takes a context argument'); deepEqual(_.partition([{a: 1}, {b: 2}, {a: 1, b: 2}], {a: 1}), [[{a: 1}, {a: 1, b: 2}], [{b: 2}]], 'predicate can be object'); var object = {a: 1}; _.partition(object, function(val, key, obj) { equal(val, 1); equal(key, 'a'); equal(obj, object); equal(this, predicate); }, predicate); }); if (typeof document != 'undefined') { test('Can use various collection methods on NodeLists', function() { var parent = document.createElement('div'); parent.innerHTML = 'textnode'; var elementChildren = _.filter(parent.childNodes, _.isElement); equal(elementChildren.length, 2); deepEqual(_.map(elementChildren, 'id'), ['id1', 'id2']); deepEqual(_.map(parent.childNodes, 'nodeType'), [1, 3, 1]); ok(!_.every(parent.childNodes, _.isElement)); ok(_.some(parent.childNodes, _.isElement)); function compareNode(node) { return _.isElement(node) ? node.id.charAt(2) : void 0; } equal(_.max(parent.childNodes, compareNode), _.last(parent.childNodes)); equal(_.min(parent.childNodes, compareNode), _.first(parent.childNodes)); }); } }()); underscore-1.8.3/test/cross-document.js000066400000000000000000000100731250726036100201610ustar00rootroot00000000000000(function() { if (typeof document == 'undefined') return; var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Cross Document'); /* global iObject, iElement, iArguments, iFunction, iArray, iError, iString, iNumber, iBoolean, iDate, iRegExp, iNaN, iNull, iUndefined, ActiveXObject */ // Setup remote variables for iFrame tests. var iframe = document.createElement('iframe'); iframe.frameBorder = iframe.height = iframe.width = 0; document.body.appendChild(iframe); var iDoc = (iDoc = iframe.contentDocument || iframe.contentWindow).document || iDoc; iDoc.write( [ '' ].join('\n') ); iDoc.close(); test('isEqual', function() { ok(!_.isEqual(iNumber, 101)); ok(_.isEqual(iNumber, 100)); // Objects from another frame. ok(_.isEqual({}, iObject), 'Objects with equivalent members created in different documents are equal'); // Array from another frame. ok(_.isEqual([1, 2, 3], iArray), 'Arrays with equivalent elements created in different documents are equal'); }); test('isEmpty', function() { ok(!_([iNumber]).isEmpty(), '[1] is not empty'); ok(!_.isEmpty(iArray), '[] is empty'); ok(_.isEmpty(iObject), '{} is empty'); }); test('isElement', function() { ok(!_.isElement('div'), 'strings are not dom elements'); ok(_.isElement(document.body), 'the body tag is a DOM element'); ok(_.isElement(iElement), 'even from another frame'); }); test('isArguments', function() { ok(_.isArguments(iArguments), 'even from another frame'); }); test('isObject', function() { ok(_.isObject(iElement), 'even from another frame'); ok(_.isObject(iFunction), 'even from another frame'); }); test('isArray', function() { ok(_.isArray(iArray), 'even from another frame'); }); test('isString', function() { ok(_.isString(iString), 'even from another frame'); }); test('isNumber', function() { ok(_.isNumber(iNumber), 'even from another frame'); }); test('isBoolean', function() { ok(_.isBoolean(iBoolean), 'even from another frame'); }); test('isFunction', function() { ok(_.isFunction(iFunction), 'even from another frame'); }); test('isDate', function() { ok(_.isDate(iDate), 'even from another frame'); }); test('isRegExp', function() { ok(_.isRegExp(iRegExp), 'even from another frame'); }); test('isNaN', function() { ok(_.isNaN(iNaN), 'even from another frame'); }); test('isNull', function() { ok(_.isNull(iNull), 'even from another frame'); }); test('isUndefined', function() { ok(_.isUndefined(iUndefined), 'even from another frame'); }); test('isError', function() { ok(_.isError(iError), 'even from another frame'); }); if (typeof ActiveXObject != 'undefined') { test('IE host objects', function() { var xml = new ActiveXObject('Msxml2.DOMDocument.3.0'); ok(!_.isNumber(xml)); ok(!_.isBoolean(xml)); ok(!_.isNaN(xml)); ok(!_.isFunction(xml)); ok(!_.isNull(xml)); ok(!_.isUndefined(xml)); }); test('#1621 IE 11 compat mode DOM elements are not functions', function() { var fn = function() {}; var xml = new ActiveXObject('Msxml2.DOMDocument.3.0'); var div = document.createElement('div'); // JIT the function var count = 200; while (count--) { _.isFunction(fn); } equal(_.isFunction(xml), false); equal(_.isFunction(div), false); equal(_.isFunction(fn), true); }); } }());underscore-1.8.3/test/functions.js000066400000000000000000000463151250726036100172340ustar00rootroot00000000000000(function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Functions'); QUnit.config.asyncRetries = 3; test('bind', function() { var context = {name : 'moe'}; var func = function(arg) { return 'name: ' + (this.name || arg); }; var bound = _.bind(func, context); equal(bound(), 'name: moe', 'can bind a function to a context'); bound = _(func).bind(context); equal(bound(), 'name: moe', 'can do OO-style binding'); bound = _.bind(func, null, 'curly'); var result = bound(); // Work around a PhantomJS bug when applying a function with null|undefined. ok(result === 'name: curly' || result === 'name: ' + window.name, 'can bind without specifying a context'); func = function(salutation, name) { return salutation + ': ' + name; }; func = _.bind(func, this, 'hello'); equal(func('moe'), 'hello: moe', 'the function was partially applied in advance'); func = _.bind(func, this, 'curly'); equal(func(), 'hello: curly', 'the function was completely applied in advance'); func = function(salutation, firstname, lastname) { return salutation + ': ' + firstname + ' ' + lastname; }; func = _.bind(func, this, 'hello', 'moe', 'curly'); equal(func(), 'hello: moe curly', 'the function was partially applied in advance and can accept multiple arguments'); func = function(context, message) { equal(this, context, message); }; _.bind(func, 0, 0, 'can bind a function to `0`')(); _.bind(func, '', '', 'can bind a function to an empty string')(); _.bind(func, false, false, 'can bind a function to `false`')(); // These tests are only meaningful when using a browser without a native bind function // To test this with a modern browser, set underscore's nativeBind to undefined var F = function () { return this; }; var boundf = _.bind(F, {hello: 'moe curly'}); var Boundf = boundf; // make eslint happy. var newBoundf = new Boundf(); equal(newBoundf.hello, undefined, 'function should not be bound to the context, to comply with ECMAScript 5'); equal(boundf().hello, 'moe curly', "When called without the new operator, it's OK to be bound to the context"); ok(newBoundf instanceof F, 'a bound instance is an instance of the original function'); throws(function() { _.bind('notafunction'); }, TypeError, 'throws an error when binding to a non-function'); }); test('partial', function() { var obj = {name: 'moe'}; var func = function() { return this.name + ' ' + _.toArray(arguments).join(' '); }; obj.func = _.partial(func, 'a', 'b'); equal(obj.func('c', 'd'), 'moe a b c d', 'can partially apply'); obj.func = _.partial(func, _, 'b', _, 'd'); equal(obj.func('a', 'c'), 'moe a b c d', 'can partially apply with placeholders'); func = _.partial(function() { return arguments.length; }, _, 'b', _, 'd'); equal(func('a', 'c', 'e'), 5, 'accepts more arguments than the number of placeholders'); equal(func('a'), 4, 'accepts fewer arguments than the number of placeholders'); func = _.partial(function() { return typeof arguments[2]; }, _, 'b', _, 'd'); equal(func('a'), 'undefined', 'unfilled placeholders are undefined'); // passes context function MyWidget(name, options) { this.name = name; this.options = options; } MyWidget.prototype.get = function() { return this.name; }; var MyWidgetWithCoolOpts = _.partial(MyWidget, _, {a: 1}); var widget = new MyWidgetWithCoolOpts('foo'); ok(widget instanceof MyWidget, 'Can partially bind a constructor'); equal(widget.get(), 'foo', 'keeps prototype'); deepEqual(widget.options, {a: 1}); }); test('bindAll', function() { var curly = {name : 'curly'}, moe = { name : 'moe', getName : function() { return 'name: ' + this.name; }, sayHi : function() { return 'hi: ' + this.name; } }; curly.getName = moe.getName; _.bindAll(moe, 'getName', 'sayHi'); curly.sayHi = moe.sayHi; equal(curly.getName(), 'name: curly', 'unbound function is bound to current object'); equal(curly.sayHi(), 'hi: moe', 'bound function is still bound to original object'); curly = {name : 'curly'}; moe = { name : 'moe', getName : function() { return 'name: ' + this.name; }, sayHi : function() { return 'hi: ' + this.name; }, sayLast : function() { return this.sayHi(_.last(arguments)); } }; throws(function() { _.bindAll(moe); }, Error, 'throws an error for bindAll with no functions named'); throws(function() { _.bindAll(moe, 'sayBye'); }, TypeError, 'throws an error for bindAll if the given key is undefined'); throws(function() { _.bindAll(moe, 'name'); }, TypeError, 'throws an error for bindAll if the given key is not a function'); _.bindAll(moe, 'sayHi', 'sayLast'); curly.sayHi = moe.sayHi; equal(curly.sayHi(), 'hi: moe'); var sayLast = moe.sayLast; equal(sayLast(1, 2, 3, 4, 5, 6, 7, 'Tom'), 'hi: moe', 'createCallback works with any number of arguments'); }); test('memoize', function() { var fib = function(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }; equal(fib(10), 55, 'a memoized version of fibonacci produces identical results'); fib = _.memoize(fib); // Redefine `fib` for memoization equal(fib(10), 55, 'a memoized version of fibonacci produces identical results'); var o = function(str) { return str; }; var fastO = _.memoize(o); equal(o('toString'), 'toString', 'checks hasOwnProperty'); equal(fastO('toString'), 'toString', 'checks hasOwnProperty'); // Expose the cache. var upper = _.memoize(function(s) { return s.toUpperCase(); }); equal(upper('foo'), 'FOO'); equal(upper('bar'), 'BAR'); deepEqual(upper.cache, {foo: 'FOO', bar: 'BAR'}); upper.cache = {foo: 'BAR', bar: 'FOO'}; equal(upper('foo'), 'BAR'); equal(upper('bar'), 'FOO'); var hashed = _.memoize(function(key) { //https://github.com/jashkenas/underscore/pull/1679#discussion_r13736209 ok(/[a-z]+/.test(key), 'hasher doesn\'t change keys'); return key; }, function(key) { return key.toUpperCase(); }); hashed('yep'); deepEqual(hashed.cache, {'YEP': 'yep'}, 'takes a hasher'); // Test that the hash function can be used to swizzle the key. var objCacher = _.memoize(function(value, key) { return {key: key, value: value}; }, function(value, key) { return key; }); var myObj = objCacher('a', 'alpha'); var myObjAlias = objCacher('b', 'alpha'); notStrictEqual(myObj, undefined, 'object is created if second argument used as key'); strictEqual(myObj, myObjAlias, 'object is cached if second argument used as key'); strictEqual(myObj.value, 'a', 'object is not modified if second argument used as key'); }); asyncTest('delay', 2, function() { var delayed = false; _.delay(function(){ delayed = true; }, 100); setTimeout(function(){ ok(!delayed, "didn't delay the function quite yet"); }, 50); setTimeout(function(){ ok(delayed, 'delayed the function'); start(); }, 150); }); asyncTest('defer', 1, function() { var deferred = false; _.defer(function(bool){ deferred = bool; }, true); _.delay(function(){ ok(deferred, 'deferred the function'); start(); }, 50); }); asyncTest('throttle', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr(); equal(counter, 1, 'incr was called immediately'); _.delay(function(){ equal(counter, 2, 'incr was throttled'); start(); }, 64); }); asyncTest('throttle arguments', 2, function() { var value = 0; var update = function(val){ value = val; }; var throttledUpdate = _.throttle(update, 32); throttledUpdate(1); throttledUpdate(2); _.delay(function(){ throttledUpdate(3); }, 64); equal(value, 1, 'updated to latest value'); _.delay(function(){ equal(value, 3, 'updated to latest value'); start(); }, 96); }); asyncTest('throttle once', 2, function() { var counter = 0; var incr = function(){ return ++counter; }; var throttledIncr = _.throttle(incr, 32); var result = throttledIncr(); _.delay(function(){ equal(result, 1, 'throttled functions return their value'); equal(counter, 1, 'incr was called once'); start(); }, 64); }); asyncTest('throttle twice', 1, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr(); _.delay(function(){ equal(counter, 2, 'incr was called twice'); start(); }, 64); }); asyncTest('more throttling', 3, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 30); throttledIncr(); throttledIncr(); equal(counter, 1); _.delay(function(){ equal(counter, 2); throttledIncr(); equal(counter, 3); start(); }, 85); }); asyncTest('throttle repeatedly with results', 6, function() { var counter = 0; var incr = function(){ return ++counter; }; var throttledIncr = _.throttle(incr, 100); var results = []; var saveResult = function() { results.push(throttledIncr()); }; saveResult(); saveResult(); _.delay(saveResult, 50); _.delay(saveResult, 150); _.delay(saveResult, 160); _.delay(saveResult, 230); _.delay(function() { equal(results[0], 1, 'incr was called once'); equal(results[1], 1, 'incr was throttled'); equal(results[2], 1, 'incr was throttled'); equal(results[3], 2, 'incr was called twice'); equal(results[4], 2, 'incr was throttled'); equal(results[5], 3, 'incr was called trailing'); start(); }, 300); }); asyncTest('throttle triggers trailing call when invoked repeatedly', 2, function() { var counter = 0; var limit = 48; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); var stamp = new Date; while (new Date - stamp < limit) { throttledIncr(); } var lastCount = counter; ok(counter > 1); _.delay(function() { ok(counter > lastCount); start(); }, 96); }); asyncTest('throttle does not trigger leading call when leading is set to false', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 60, {leading: false}); throttledIncr(); throttledIncr(); equal(counter, 0); _.delay(function() { equal(counter, 1); start(); }, 96); }); asyncTest('more throttle does not trigger leading call when leading is set to false', 3, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100, {leading: false}); throttledIncr(); _.delay(throttledIncr, 50); _.delay(throttledIncr, 60); _.delay(throttledIncr, 200); equal(counter, 0); _.delay(function() { equal(counter, 1); }, 250); _.delay(function() { equal(counter, 2); start(); }, 350); }); asyncTest('one more throttle with leading: false test', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100, {leading: false}); var time = new Date; while (new Date - time < 350) throttledIncr(); ok(counter <= 3); _.delay(function() { ok(counter <= 4); start(); }, 200); }); asyncTest('throttle does not trigger trailing call when trailing is set to false', 4, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 60, {trailing: false}); throttledIncr(); throttledIncr(); throttledIncr(); equal(counter, 1); _.delay(function() { equal(counter, 1); throttledIncr(); throttledIncr(); equal(counter, 2); _.delay(function() { equal(counter, 2); start(); }, 96); }, 96); }); asyncTest('throttle continues to function after system time is set backwards', 2, function() { var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100); var origNowFunc = _.now; throttledIncr(); equal(counter, 1); _.now = function () { return new Date(2013, 0, 1, 1, 1, 1); }; _.delay(function() { throttledIncr(); equal(counter, 2); start(); _.now = origNowFunc; }, 200); }); asyncTest('throttle re-entrant', 2, function() { var sequence = [ ['b1', 'b2'], ['c1', 'c2'] ]; var value = ''; var throttledAppend; var append = function(arg){ value += this + arg; var args = sequence.pop(); if (args) { throttledAppend.call(args[0], args[1]); } }; throttledAppend = _.throttle(append, 32); throttledAppend.call('a1', 'a2'); equal(value, 'a1a2'); _.delay(function(){ equal(value, 'a1a2c1c2b1b2', 'append was throttled successfully'); start(); }, 100); }); asyncTest('debounce', 1, function() { var counter = 0; var incr = function(){ counter++; }; var debouncedIncr = _.debounce(incr, 32); debouncedIncr(); debouncedIncr(); _.delay(debouncedIncr, 16); _.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 96); }); asyncTest('debounce asap', 4, function() { var a, b; var counter = 0; var incr = function(){ return ++counter; }; var debouncedIncr = _.debounce(incr, 64, true); a = debouncedIncr(); b = debouncedIncr(); equal(a, 1); equal(b, 1); equal(counter, 1, 'incr was called immediately'); _.delay(debouncedIncr, 16); _.delay(debouncedIncr, 32); _.delay(debouncedIncr, 48); _.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 128); }); asyncTest('debounce asap recursively', 2, function() { var counter = 0; var debouncedIncr = _.debounce(function(){ counter++; if (counter < 10) debouncedIncr(); }, 32, true); debouncedIncr(); equal(counter, 1, 'incr was called immediately'); _.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 96); }); asyncTest('debounce after system time is set backwards', 2, function() { var counter = 0; var origNowFunc = _.now; var debouncedIncr = _.debounce(function(){ counter++; }, 100, true); debouncedIncr(); equal(counter, 1, 'incr was called immediately'); _.now = function () { return new Date(2013, 0, 1, 1, 1, 1); }; _.delay(function() { debouncedIncr(); equal(counter, 2, 'incr was debounced successfully'); start(); _.now = origNowFunc; }, 200); }); asyncTest('debounce re-entrant', 2, function() { var sequence = [ ['b1', 'b2'] ]; var value = ''; var debouncedAppend; var append = function(arg){ value += this + arg; var args = sequence.pop(); if (args) { debouncedAppend.call(args[0], args[1]); } }; debouncedAppend = _.debounce(append, 32); debouncedAppend.call('a1', 'a2'); equal(value, ''); _.delay(function(){ equal(value, 'a1a2b1b2', 'append was debounced successfully'); start(); }, 100); }); test('once', function() { var num = 0; var increment = _.once(function(){ return ++num; }); increment(); increment(); equal(num, 1); equal(increment(), 1, 'stores a memo to the last value'); }); test('Recursive onced function.', 1, function() { var f = _.once(function(){ ok(true); f(); }); f(); }); test('wrap', function() { var greet = function(name){ return 'hi: ' + name; }; var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); }); equal(backwards('moe'), 'hi: moe eom', 'wrapped the salutation function'); var inner = function(){ return 'Hello '; }; var obj = {name : 'Moe'}; obj.hi = _.wrap(inner, function(fn){ return fn() + this.name; }); equal(obj.hi(), 'Hello Moe'); var noop = function(){}; var wrapped = _.wrap(noop, function(){ return Array.prototype.slice.call(arguments, 0); }); var ret = wrapped(['whats', 'your'], 'vector', 'victor'); deepEqual(ret, [noop, ['whats', 'your'], 'vector', 'victor']); }); test('negate', function() { var isOdd = function(n){ return n & 1; }; equal(_.negate(isOdd)(2), true, 'should return the complement of the given function'); equal(_.negate(isOdd)(3), false, 'should return the complement of the given function'); }); test('compose', function() { var greet = function(name){ return 'hi: ' + name; }; var exclaim = function(sentence){ return sentence + '!'; }; var composed = _.compose(exclaim, greet); equal(composed('moe'), 'hi: moe!', 'can compose a function that takes another'); composed = _.compose(greet, exclaim); equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative'); // f(g(h(x, y, z))) function h(x, y, z) { equal(arguments.length, 3, 'First function called with multiple args'); return z * y; } function g(x) { equal(arguments.length, 1, 'Composed function is called with 1 argument'); return x; } function f(x) { equal(arguments.length, 1, 'Composed function is called with 1 argument'); return x * 2; } composed = _.compose(f, g, h); equal(composed(1, 2, 3), 12); }); test('after', function() { var testAfter = function(afterAmount, timesCalled) { var afterCalled = 0; var after = _.after(afterAmount, function() { afterCalled++; }); while (timesCalled--) after(); return afterCalled; }; equal(testAfter(5, 5), 1, 'after(N) should fire after being called N times'); equal(testAfter(5, 4), 0, 'after(N) should not fire unless called N times'); equal(testAfter(0, 0), 0, 'after(0) should not fire immediately'); equal(testAfter(0, 1), 1, 'after(0) should fire when first invoked'); }); test('before', function() { var testBefore = function(beforeAmount, timesCalled) { var beforeCalled = 0; var before = _.before(beforeAmount, function() { beforeCalled++; }); while (timesCalled--) before(); return beforeCalled; }; equal(testBefore(5, 5), 4, 'before(N) should not fire after being called N times'); equal(testBefore(5, 4), 4, 'before(N) should fire before being called N times'); equal(testBefore(0, 0), 0, 'before(0) should not fire immediately'); equal(testBefore(0, 1), 0, 'before(0) should not fire when first invoked'); var context = {num: 0}; var increment = _.before(3, function(){ return ++this.num; }); _.times(10, increment, context); equal(increment(), 2, 'stores a memo to the last value'); equal(context.num, 2, 'provides context'); }); test('iteratee', function() { var identity = _.iteratee(); equal(identity, _.identity, '_.iteratee is exposed as an external function.'); function fn() { return arguments; } _.each([_.iteratee(fn), _.iteratee(fn, {})], function(cb) { equal(cb().length, 0); deepEqual(_.toArray(cb(1, 2, 3)), _.range(1, 4)); deepEqual(_.toArray(cb(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), _.range(1, 11)); }); }); }()); underscore-1.8.3/test/index.html000066400000000000000000000012171250726036100166530ustar00rootroot00000000000000 Underscore Test Suite
underscore-1.8.3/test/objects.js000066400000000000000000001274221250726036100166540ustar00rootroot00000000000000(function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Objects'); var testElement = typeof document === 'object' ? document.createElement('div') : void 0; test('keys', function() { deepEqual(_.keys({one : 1, two : 2}), ['one', 'two'], 'can extract the keys from an object'); // the test above is not safe because it relies on for-in enumeration order var a = []; a[1] = 0; deepEqual(_.keys(a), ['1'], 'is not fooled by sparse arrays; see issue #95'); deepEqual(_.keys(null), []); deepEqual(_.keys(void 0), []); deepEqual(_.keys(1), []); deepEqual(_.keys('a'), []); deepEqual(_.keys(true), []); // keys that may be missed if the implementation isn't careful var trouble = { 'constructor': Object, 'valueOf': _.noop, 'hasOwnProperty': null, 'toString': 5, 'toLocaleString': undefined, 'propertyIsEnumerable': /a/, 'isPrototypeOf': this, '__defineGetter__': Boolean, '__defineSetter__': {}, '__lookupSetter__': false, '__lookupGetter__': [] }; var troubleKeys = ['constructor', 'valueOf', 'hasOwnProperty', 'toString', 'toLocaleString', 'propertyIsEnumerable', 'isPrototypeOf', '__defineGetter__', '__defineSetter__', '__lookupSetter__', '__lookupGetter__'].sort(); deepEqual(_.keys(trouble).sort(), troubleKeys, 'matches non-enumerable properties'); }); test('allKeys', function() { deepEqual(_.allKeys({one : 1, two : 2}), ['one', 'two'], 'can extract the allKeys from an object'); // the test above is not safe because it relies on for-in enumeration order var a = []; a[1] = 0; deepEqual(_.allKeys(a), ['1'], 'is not fooled by sparse arrays; see issue #95'); a.a = a; deepEqual(_.allKeys(a), ['1', 'a'], 'is not fooled by sparse arrays with additional properties'); _.each([null, void 0, 1, 'a', true, NaN, {}, [], new Number(5), new Date(0)], function(val) { deepEqual(_.allKeys(val), []); }); // allKeys that may be missed if the implementation isn't careful var trouble = { constructor: Object, valueOf: _.noop, hasOwnProperty: null, toString: 5, toLocaleString: undefined, propertyIsEnumerable: /a/, isPrototypeOf: this }; var troubleKeys = ['constructor', 'valueOf', 'hasOwnProperty', 'toString', 'toLocaleString', 'propertyIsEnumerable', 'isPrototypeOf'].sort(); deepEqual(_.allKeys(trouble).sort(), troubleKeys, 'matches non-enumerable properties'); function A() {} A.prototype.foo = 'foo'; var b = new A(); b.bar = 'bar'; deepEqual(_.allKeys(b).sort(), ['bar', 'foo'], 'should include inherited keys'); function y() {} y.x = 'z'; deepEqual(_.allKeys(y), ['x'], 'should get keys from constructor'); }); test('values', function() { deepEqual(_.values({one: 1, two: 2}), [1, 2], 'can extract the values from an object'); deepEqual(_.values({one: 1, two: 2, length: 3}), [1, 2, 3], '... even when one of them is "length"'); }); test('pairs', function() { deepEqual(_.pairs({one: 1, two: 2}), [['one', 1], ['two', 2]], 'can convert an object into pairs'); deepEqual(_.pairs({one: 1, two: 2, length: 3}), [['one', 1], ['two', 2], ['length', 3]], '... even when one of them is "length"'); }); test('invert', function() { var obj = {first: 'Moe', second: 'Larry', third: 'Curly'}; deepEqual(_.keys(_.invert(obj)), ['Moe', 'Larry', 'Curly'], 'can invert an object'); deepEqual(_.invert(_.invert(obj)), obj, 'two inverts gets you back where you started'); obj = {length: 3}; equal(_.invert(obj)['3'], 'length', 'can invert an object with "length"'); }); test('functions', function() { var obj = {a : 'dash', b : _.map, c : /yo/, d : _.reduce}; deepEqual(['b', 'd'], _.functions(obj), 'can grab the function names of any passed-in object'); var Animal = function(){}; Animal.prototype.run = function(){}; deepEqual(_.functions(new Animal), ['run'], 'also looks up functions on the prototype'); }); test('methods', function() { strictEqual(_.functions, _.methods, 'alias for functions'); }); test('extend', function() { var result; equal(_.extend({}, {a: 'b'}).a, 'b', 'can extend an object with the attributes of another'); equal(_.extend({a: 'x'}, {a: 'b'}).a, 'b', 'properties in source override destination'); equal(_.extend({x: 'x'}, {a: 'b'}).x, 'x', "properties not in source don't get overriden"); result = _.extend({x: 'x'}, {a: 'a'}, {b: 'b'}); deepEqual(result, {x: 'x', a: 'a', b: 'b'}, 'can extend from multiple source objects'); result = _.extend({x: 'x'}, {a: 'a', x: 2}, {a: 'b'}); deepEqual(result, {x: 2, a: 'b'}, 'extending from multiple source objects last property trumps'); result = _.extend({}, {a: void 0, b: null}); deepEqual(_.keys(result), ['a', 'b'], 'extend copies undefined values'); var F = function() {}; F.prototype = {a: 'b'}; var subObj = new F(); subObj.c = 'd'; deepEqual(_.extend({}, subObj), {a: 'b', c: 'd'}, 'extend copies all properties from source'); _.extend(subObj, {}); ok(!subObj.hasOwnProperty('a'), "extend does not convert destination object's 'in' properties to 'own' properties"); try { result = {}; _.extend(result, null, undefined, {a: 1}); } catch(ex) {} equal(result.a, 1, 'should not error on `null` or `undefined` sources'); strictEqual(_.extend(null, {a: 1}), null, 'extending null results in null'); strictEqual(_.extend(undefined, {a: 1}), undefined, 'extending undefined results in undefined'); }); test('extendOwn', function() { var result; equal(_.extendOwn({}, {a: 'b'}).a, 'b', 'can assign an object with the attributes of another'); equal(_.extendOwn({a: 'x'}, {a: 'b'}).a, 'b', 'properties in source override destination'); equal(_.extendOwn({x: 'x'}, {a: 'b'}).x, 'x', "properties not in source don't get overriden"); result = _.extendOwn({x: 'x'}, {a: 'a'}, {b: 'b'}); deepEqual(result, {x: 'x', a: 'a', b: 'b'}, 'can assign from multiple source objects'); result = _.assign({x: 'x'}, {a: 'a', x: 2}, {a: 'b'}); deepEqual(result, {x: 2, a: 'b'}, 'assigning from multiple source objects last property trumps'); deepEqual(_.extendOwn({}, {a: void 0, b: null}), {a: void 0, b: null}, 'assign copies undefined values'); var F = function() {}; F.prototype = {a: 'b'}; var subObj = new F(); subObj.c = 'd'; deepEqual(_.extendOwn({}, subObj), {c: 'd'}, 'assign copies own properties from source'); result = {}; deepEqual(_.assign(result, null, undefined, {a: 1}), {a: 1}, 'should not error on `null` or `undefined` sources'); _.each(['a', 5, null, false], function(val) { strictEqual(_.assign(val, {a: 1}), val, 'assigning non-objects results in returning the non-object value'); }); strictEqual(_.extendOwn(undefined, {a: 1}), undefined, 'assigning undefined results in undefined'); result = _.extendOwn({a: 1, 0: 2, 1: '5', length: 6}, {0: 1, 1: 2, length: 2}); deepEqual(result, {a: 1, 0: 1, 1: 2, length: 2}, 'assign should treat array-like objects like normal objects'); }); test('pick', function() { var result; result = _.pick({a: 1, b: 2, c: 3}, 'a', 'c'); deepEqual(result, {a: 1, c: 3}, 'can restrict properties to those named'); result = _.pick({a: 1, b: 2, c: 3}, ['b', 'c']); deepEqual(result, {b: 2, c: 3}, 'can restrict properties to those named in an array'); result = _.pick({a: 1, b: 2, c: 3}, ['a'], 'b'); deepEqual(result, {a: 1, b: 2}, 'can restrict properties to those named in mixed args'); result = _.pick(['a', 'b'], 1); deepEqual(result, {1: 'b'}, 'can pick numeric properties'); _.each([null, void 0], function(val) { deepEqual(_.pick(val, 'hasOwnProperty'), {}, 'Called with null/undefined'); deepEqual(_.pick(val, _.constant(true)), {}); }); deepEqual(_.pick(5, 'toString', 'b'), {toString: Number.prototype.toString}, 'can iterate primitives'); var data = {a: 1, b: 2, c: 3}; var callback = function(value, key, object) { strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]); strictEqual(object, data); return value !== this.value; }; result = _.pick(data, callback, {value: 2}); deepEqual(result, {a: 1, c: 3}, 'can accept a predicate and context'); var Obj = function(){}; Obj.prototype = {a: 1, b: 2, c: 3}; var instance = new Obj(); deepEqual(_.pick(instance, 'a', 'c'), {a: 1, c: 3}, 'include prototype props'); deepEqual(_.pick(data, function(val, key) { return this[key] === 3 && this === instance; }, instance), {c: 3}, 'function is given context'); ok(!_.has(_.pick({}, 'foo'), 'foo'), 'does not set own property if property not in object'); _.pick(data, function(value, key, obj) { equal(obj, data, 'passes same object as third parameter of iteratee'); }); }); test('omit', function() { var result; result = _.omit({a: 1, b: 2, c: 3}, 'b'); deepEqual(result, {a: 1, c: 3}, 'can omit a single named property'); result = _.omit({a: 1, b: 2, c: 3}, 'a', 'c'); deepEqual(result, {b: 2}, 'can omit several named properties'); result = _.omit({a: 1, b: 2, c: 3}, ['b', 'c']); deepEqual(result, {a: 1}, 'can omit properties named in an array'); result = _.omit(['a', 'b'], 0); deepEqual(result, {1: 'b'}, 'can omit numeric properties'); deepEqual(_.omit(null, 'a', 'b'), {}, 'non objects return empty object'); deepEqual(_.omit(undefined, 'toString'), {}, 'null/undefined return empty object'); deepEqual(_.omit(5, 'toString', 'b'), {}, 'returns empty object for primitives'); var data = {a: 1, b: 2, c: 3}; var callback = function(value, key, object) { strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]); strictEqual(object, data); return value !== this.value; }; result = _.omit(data, callback, {value: 2}); deepEqual(result, {b: 2}, 'can accept a predicate'); var Obj = function(){}; Obj.prototype = {a: 1, b: 2, c: 3}; var instance = new Obj(); deepEqual(_.omit(instance, 'b'), {a: 1, c: 3}, 'include prototype props'); deepEqual(_.omit(data, function(val, key) { return this[key] === 3 && this === instance; }, instance), {a: 1, b: 2}, 'function is given context'); }); test('defaults', function() { var options = {zero: 0, one: 1, empty: '', nan: NaN, nothing: null}; _.defaults(options, {zero: 1, one: 10, twenty: 20, nothing: 'str'}); equal(options.zero, 0, 'value exists'); equal(options.one, 1, 'value exists'); equal(options.twenty, 20, 'default applied'); equal(options.nothing, null, "null isn't overridden"); _.defaults(options, {empty: 'full'}, {nan: 'nan'}, {word: 'word'}, {word: 'dog'}); equal(options.empty, '', 'value exists'); ok(_.isNaN(options.nan), "NaN isn't overridden"); equal(options.word, 'word', 'new value is added, first one wins'); try { options = {}; _.defaults(options, null, undefined, {a: 1}); } catch(ex) {} equal(options.a, 1, 'should not error on `null` or `undefined` sources'); strictEqual(_.defaults(null, {a: 1}), null, 'result is null if destination is null'); strictEqual(_.defaults(undefined, {a: 1}), undefined, 'result is undefined if destination is undefined'); }); test('clone', function() { var moe = {name : 'moe', lucky : [13, 27, 34]}; var clone = _.clone(moe); equal(clone.name, 'moe', 'the clone as the attributes of the original'); clone.name = 'curly'; ok(clone.name === 'curly' && moe.name === 'moe', 'clones can change shallow attributes without affecting the original'); clone.lucky.push(101); equal(_.last(moe.lucky), 101, 'changes to deep attributes are shared with the original'); equal(_.clone(undefined), void 0, 'non objects should not be changed by clone'); equal(_.clone(1), 1, 'non objects should not be changed by clone'); equal(_.clone(null), null, 'non objects should not be changed by clone'); }); test('create', function() { var Parent = function() {}; Parent.prototype = {foo: function() {}, bar: 2}; _.each(['foo', null, undefined, 1], function(val) { deepEqual(_.create(val), {}, 'should return empty object when a non-object is provided'); }); ok(_.create([]) instanceof Array, 'should return new instance of array when array is provided'); var Child = function() {}; Child.prototype = _.create(Parent.prototype); ok(new Child instanceof Parent, 'object should inherit prototype'); var func = function() {}; Child.prototype = _.create(Parent.prototype, {func: func}); strictEqual(Child.prototype.func, func, 'properties should be added to object'); Child.prototype = _.create(Parent.prototype, {constructor: Child}); strictEqual(Child.prototype.constructor, Child); Child.prototype.foo = 'foo'; var created = _.create(Child.prototype, new Child); ok(!created.hasOwnProperty('foo'), 'should only add own properties'); }); test('isEqual', function() { function First() { this.value = 1; } First.prototype.value = 1; function Second() { this.value = 1; } Second.prototype.value = 2; // Basic equality and identity comparisons. ok(_.isEqual(null, null), '`null` is equal to `null`'); ok(_.isEqual(), '`undefined` is equal to `undefined`'); ok(!_.isEqual(0, -0), '`0` is not equal to `-0`'); ok(!_.isEqual(-0, 0), 'Commutative equality is implemented for `0` and `-0`'); ok(!_.isEqual(null, undefined), '`null` is not equal to `undefined`'); ok(!_.isEqual(undefined, null), 'Commutative equality is implemented for `null` and `undefined`'); // String object and primitive comparisons. ok(_.isEqual('Curly', 'Curly'), 'Identical string primitives are equal'); ok(_.isEqual(new String('Curly'), new String('Curly')), 'String objects with identical primitive values are equal'); ok(_.isEqual(new String('Curly'), 'Curly'), 'String primitives and their corresponding object wrappers are equal'); ok(_.isEqual('Curly', new String('Curly')), 'Commutative equality is implemented for string objects and primitives'); ok(!_.isEqual('Curly', 'Larry'), 'String primitives with different values are not equal'); ok(!_.isEqual(new String('Curly'), new String('Larry')), 'String objects with different primitive values are not equal'); ok(!_.isEqual(new String('Curly'), {toString: function(){ return 'Curly'; }}), 'String objects and objects with a custom `toString` method are not equal'); // Number object and primitive comparisons. ok(_.isEqual(75, 75), 'Identical number primitives are equal'); ok(_.isEqual(new Number(75), new Number(75)), 'Number objects with identical primitive values are equal'); ok(_.isEqual(75, new Number(75)), 'Number primitives and their corresponding object wrappers are equal'); ok(_.isEqual(new Number(75), 75), 'Commutative equality is implemented for number objects and primitives'); ok(!_.isEqual(new Number(0), -0), '`new Number(0)` and `-0` are not equal'); ok(!_.isEqual(0, new Number(-0)), 'Commutative equality is implemented for `new Number(0)` and `-0`'); ok(!_.isEqual(new Number(75), new Number(63)), 'Number objects with different primitive values are not equal'); ok(!_.isEqual(new Number(63), {valueOf: function(){ return 63; }}), 'Number objects and objects with a `valueOf` method are not equal'); // Comparisons involving `NaN`. ok(_.isEqual(NaN, NaN), '`NaN` is equal to `NaN`'); ok(_.isEqual(new Object(NaN), NaN), 'Object(`NaN`) is equal to `NaN`'); ok(!_.isEqual(61, NaN), 'A number primitive is not equal to `NaN`'); ok(!_.isEqual(new Number(79), NaN), 'A number object is not equal to `NaN`'); ok(!_.isEqual(Infinity, NaN), '`Infinity` is not equal to `NaN`'); // Boolean object and primitive comparisons. ok(_.isEqual(true, true), 'Identical boolean primitives are equal'); ok(_.isEqual(new Boolean, new Boolean), 'Boolean objects with identical primitive values are equal'); ok(_.isEqual(true, new Boolean(true)), 'Boolean primitives and their corresponding object wrappers are equal'); ok(_.isEqual(new Boolean(true), true), 'Commutative equality is implemented for booleans'); ok(!_.isEqual(new Boolean(true), new Boolean), 'Boolean objects with different primitive values are not equal'); // Common type coercions. ok(!_.isEqual(new Boolean(false), true), '`new Boolean(false)` is not equal to `true`'); ok(!_.isEqual('75', 75), 'String and number primitives with like values are not equal'); ok(!_.isEqual(new Number(63), new String(63)), 'String and number objects with like values are not equal'); ok(!_.isEqual(75, '75'), 'Commutative equality is implemented for like string and number values'); ok(!_.isEqual(0, ''), 'Number and string primitives with like values are not equal'); ok(!_.isEqual(1, true), 'Number and boolean primitives with like values are not equal'); ok(!_.isEqual(new Boolean(false), new Number(0)), 'Boolean and number objects with like values are not equal'); ok(!_.isEqual(false, new String('')), 'Boolean primitives and string objects with like values are not equal'); ok(!_.isEqual(12564504e5, new Date(2009, 9, 25)), 'Dates and their corresponding numeric primitive values are not equal'); // Dates. ok(_.isEqual(new Date(2009, 9, 25), new Date(2009, 9, 25)), 'Date objects referencing identical times are equal'); ok(!_.isEqual(new Date(2009, 9, 25), new Date(2009, 11, 13)), 'Date objects referencing different times are not equal'); ok(!_.isEqual(new Date(2009, 11, 13), { getTime: function(){ return 12606876e5; } }), 'Date objects and objects with a `getTime` method are not equal'); ok(!_.isEqual(new Date('Curly'), new Date('Curly')), 'Invalid dates are not equal'); // Functions. ok(!_.isEqual(First, Second), 'Different functions with identical bodies and source code representations are not equal'); // RegExps. ok(_.isEqual(/(?:)/gim, /(?:)/gim), 'RegExps with equivalent patterns and flags are equal'); ok(_.isEqual(/(?:)/gi, /(?:)/ig), 'Flag order is not significant'); ok(!_.isEqual(/(?:)/g, /(?:)/gi), 'RegExps with equivalent patterns and different flags are not equal'); ok(!_.isEqual(/Moe/gim, /Curly/gim), 'RegExps with different patterns and equivalent flags are not equal'); ok(!_.isEqual(/(?:)/gi, /(?:)/g), 'Commutative equality is implemented for RegExps'); ok(!_.isEqual(/Curly/g, {source: 'Larry', global: true, ignoreCase: false, multiline: false}), 'RegExps and RegExp-like objects are not equal'); // Empty arrays, array-like objects, and object literals. ok(_.isEqual({}, {}), 'Empty object literals are equal'); ok(_.isEqual([], []), 'Empty array literals are equal'); ok(_.isEqual([{}], [{}]), 'Empty nested arrays and objects are equal'); ok(!_.isEqual({length: 0}, []), 'Array-like objects and arrays are not equal.'); ok(!_.isEqual([], {length: 0}), 'Commutative equality is implemented for array-like objects'); ok(!_.isEqual({}, []), 'Object literals and array literals are not equal'); ok(!_.isEqual([], {}), 'Commutative equality is implemented for objects and arrays'); // Arrays with primitive and object values. ok(_.isEqual([1, 'Larry', true], [1, 'Larry', true]), 'Arrays containing identical primitives are equal'); ok(_.isEqual([/Moe/g, new Date(2009, 9, 25)], [/Moe/g, new Date(2009, 9, 25)]), 'Arrays containing equivalent elements are equal'); // Multi-dimensional arrays. var a = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}]; var b = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}]; ok(_.isEqual(a, b), 'Arrays containing nested arrays and objects are recursively compared'); // Overwrite the methods defined in ES 5.1 section 15.4.4. a.forEach = a.map = a.filter = a.every = a.indexOf = a.lastIndexOf = a.some = a.reduce = a.reduceRight = null; b.join = b.pop = b.reverse = b.shift = b.slice = b.splice = b.concat = b.sort = b.unshift = null; // Array elements and properties. ok(_.isEqual(a, b), 'Arrays containing equivalent elements and different non-numeric properties are equal'); a.push('White Rocks'); ok(!_.isEqual(a, b), 'Arrays of different lengths are not equal'); a.push('East Boulder'); b.push('Gunbarrel Ranch', 'Teller Farm'); ok(!_.isEqual(a, b), 'Arrays of identical lengths containing different elements are not equal'); // Sparse arrays. ok(_.isEqual(Array(3), Array(3)), 'Sparse arrays of identical lengths are equal'); ok(!_.isEqual(Array(3), Array(6)), 'Sparse arrays of different lengths are not equal when both are empty'); var sparse = []; sparse[1] = 5; ok(_.isEqual(sparse, [undefined, 5]), 'Handles sparse arrays as dense'); // Simple objects. ok(_.isEqual({a: 'Curly', b: 1, c: true}, {a: 'Curly', b: 1, c: true}), 'Objects containing identical primitives are equal'); ok(_.isEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), 'Objects containing equivalent members are equal'); ok(!_.isEqual({a: 63, b: 75}, {a: 61, b: 55}), 'Objects of identical sizes with different values are not equal'); ok(!_.isEqual({a: 63, b: 75}, {a: 61, c: 55}), 'Objects of identical sizes with different property names are not equal'); ok(!_.isEqual({a: 1, b: 2}, {a: 1}), 'Objects of different sizes are not equal'); ok(!_.isEqual({a: 1}, {a: 1, b: 2}), 'Commutative equality is implemented for objects'); ok(!_.isEqual({x: 1, y: undefined}, {x: 1, z: 2}), 'Objects with identical keys and different values are not equivalent'); // `A` contains nested objects and arrays. a = { name: new String('Moe Howard'), age: new Number(77), stooge: true, hobbies: ['acting'], film: { name: 'Sing a Song of Six Pants', release: new Date(1947, 9, 30), stars: [new String('Larry Fine'), 'Shemp Howard'], minutes: new Number(16), seconds: 54 } }; // `B` contains equivalent nested objects and arrays. b = { name: new String('Moe Howard'), age: new Number(77), stooge: true, hobbies: ['acting'], film: { name: 'Sing a Song of Six Pants', release: new Date(1947, 9, 30), stars: [new String('Larry Fine'), 'Shemp Howard'], minutes: new Number(16), seconds: 54 } }; ok(_.isEqual(a, b), 'Objects with nested equivalent members are recursively compared'); // Instances. ok(_.isEqual(new First, new First), 'Object instances are equal'); ok(!_.isEqual(new First, new Second), 'Objects with different constructors and identical own properties are not equal'); ok(!_.isEqual({value: 1}, new First), 'Object instances and objects sharing equivalent properties are not equal'); ok(!_.isEqual({value: 2}, new Second), 'The prototype chain of objects should not be examined'); // Circular Arrays. (a = []).push(a); (b = []).push(b); ok(_.isEqual(a, b), 'Arrays containing circular references are equal'); a.push(new String('Larry')); b.push(new String('Larry')); ok(_.isEqual(a, b), 'Arrays containing circular references and equivalent properties are equal'); a.push('Shemp'); b.push('Curly'); ok(!_.isEqual(a, b), 'Arrays containing circular references and different properties are not equal'); // More circular arrays #767. a = ['everything is checked but', 'this', 'is not']; a[1] = a; b = ['everything is checked but', ['this', 'array'], 'is not']; ok(!_.isEqual(a, b), 'Comparison of circular references with non-circular references are not equal'); // Circular Objects. a = {abc: null}; b = {abc: null}; a.abc = a; b.abc = b; ok(_.isEqual(a, b), 'Objects containing circular references are equal'); a.def = 75; b.def = 75; ok(_.isEqual(a, b), 'Objects containing circular references and equivalent properties are equal'); a.def = new Number(75); b.def = new Number(63); ok(!_.isEqual(a, b), 'Objects containing circular references and different properties are not equal'); // More circular objects #767. a = {everything: 'is checked', but: 'this', is: 'not'}; a.but = a; b = {everything: 'is checked', but: {that: 'object'}, is: 'not'}; ok(!_.isEqual(a, b), 'Comparison of circular references with non-circular object references are not equal'); // Cyclic Structures. a = [{abc: null}]; b = [{abc: null}]; (a[0].abc = a).push(a); (b[0].abc = b).push(b); ok(_.isEqual(a, b), 'Cyclic structures are equal'); a[0].def = 'Larry'; b[0].def = 'Larry'; ok(_.isEqual(a, b), 'Cyclic structures containing equivalent properties are equal'); a[0].def = new String('Larry'); b[0].def = new String('Curly'); ok(!_.isEqual(a, b), 'Cyclic structures containing different properties are not equal'); // Complex Circular References. a = {foo: {b: {foo: {c: {foo: null}}}}}; b = {foo: {b: {foo: {c: {foo: null}}}}}; a.foo.b.foo.c.foo = a; b.foo.b.foo.c.foo = b; ok(_.isEqual(a, b), 'Cyclic structures with nested and identically-named properties are equal'); // Chaining. ok(!_.isEqual(_({x: 1, y: undefined}).chain(), _({x: 1, z: 2}).chain()), 'Chained objects containing different values are not equal'); a = _({x: 1, y: 2}).chain(); b = _({x: 1, y: 2}).chain(); equal(_.isEqual(a.isEqual(b), _(true)), true, '`isEqual` can be chained'); // Objects without a `constructor` property if (Object.create) { a = Object.create(null, {x: {value: 1, enumerable: true}}); b = {x: 1}; ok(_.isEqual(a, b), 'Handles objects without a constructor (e.g. from Object.create'); } function Foo() { this.a = 1; } Foo.prototype.constructor = null; var other = {a: 1}; strictEqual(_.isEqual(new Foo, other), false, 'Objects from different constructors are not equal'); }); test('isEmpty', function() { ok(!_([1]).isEmpty(), '[1] is not empty'); ok(_.isEmpty([]), '[] is empty'); ok(!_.isEmpty({one : 1}), '{one : 1} is not empty'); ok(_.isEmpty({}), '{} is empty'); ok(_.isEmpty(new RegExp('')), 'objects with prototype properties are empty'); ok(_.isEmpty(null), 'null is empty'); ok(_.isEmpty(), 'undefined is empty'); ok(_.isEmpty(''), 'the empty string is empty'); ok(!_.isEmpty('moe'), 'but other strings are not'); var obj = {one : 1}; delete obj.one; ok(_.isEmpty(obj), 'deleting all the keys from an object empties it'); var args = function(){ return arguments; }; ok(_.isEmpty(args()), 'empty arguments object is empty'); ok(!_.isEmpty(args('')), 'non-empty arguments object is not empty'); // covers collecting non-enumerable properties in IE < 9 var nonEnumProp = {'toString': 5}; ok(!_.isEmpty(nonEnumProp), 'non-enumerable property is not empty'); }); if (typeof document === 'object') { test('isElement', function() { ok(!_.isElement('div'), 'strings are not dom elements'); ok(_.isElement(testElement), 'an element is a DOM element'); }); } test('isArguments', function() { var args = (function(){ return arguments; }(1, 2, 3)); ok(!_.isArguments('string'), 'a string is not an arguments object'); ok(!_.isArguments(_.isArguments), 'a function is not an arguments object'); ok(_.isArguments(args), 'but the arguments object is an arguments object'); ok(!_.isArguments(_.toArray(args)), 'but not when it\'s converted into an array'); ok(!_.isArguments([1, 2, 3]), 'and not vanilla arrays.'); }); test('isObject', function() { ok(_.isObject(arguments), 'the arguments object is object'); ok(_.isObject([1, 2, 3]), 'and arrays'); if (testElement) { ok(_.isObject(testElement), 'and DOM element'); } ok(_.isObject(function () {}), 'and functions'); ok(!_.isObject(null), 'but not null'); ok(!_.isObject(undefined), 'and not undefined'); ok(!_.isObject('string'), 'and not string'); ok(!_.isObject(12), 'and not number'); ok(!_.isObject(true), 'and not boolean'); ok(_.isObject(new String('string')), 'but new String()'); }); test('isArray', function() { ok(!_.isArray(undefined), 'undefined vars are not arrays'); ok(!_.isArray(arguments), 'the arguments object is not an array'); ok(_.isArray([1, 2, 3]), 'but arrays are'); }); test('isString', function() { var obj = new String('I am a string object'); if (testElement) { ok(!_.isString(testElement), 'an element is not a string'); } ok(_.isString([1, 2, 3].join(', ')), 'but strings are'); strictEqual(_.isString('I am a string literal'), true, 'string literals are'); ok(_.isString(obj), 'so are String objects'); strictEqual(_.isString(1), false); }); test('isNumber', function() { ok(!_.isNumber('string'), 'a string is not a number'); ok(!_.isNumber(arguments), 'the arguments object is not a number'); ok(!_.isNumber(undefined), 'undefined is not a number'); ok(_.isNumber(3 * 4 - 7 / 10), 'but numbers are'); ok(_.isNumber(NaN), 'NaN *is* a number'); ok(_.isNumber(Infinity), 'Infinity is a number'); ok(!_.isNumber('1'), 'numeric strings are not numbers'); }); test('isBoolean', function() { ok(!_.isBoolean(2), 'a number is not a boolean'); ok(!_.isBoolean('string'), 'a string is not a boolean'); ok(!_.isBoolean('false'), 'the string "false" is not a boolean'); ok(!_.isBoolean('true'), 'the string "true" is not a boolean'); ok(!_.isBoolean(arguments), 'the arguments object is not a boolean'); ok(!_.isBoolean(undefined), 'undefined is not a boolean'); ok(!_.isBoolean(NaN), 'NaN is not a boolean'); ok(!_.isBoolean(null), 'null is not a boolean'); ok(_.isBoolean(true), 'but true is'); ok(_.isBoolean(false), 'and so is false'); }); test('isFunction', function() { ok(!_.isFunction(undefined), 'undefined vars are not functions'); ok(!_.isFunction([1, 2, 3]), 'arrays are not functions'); ok(!_.isFunction('moe'), 'strings are not functions'); ok(_.isFunction(_.isFunction), 'but functions are'); ok(_.isFunction(function(){}), 'even anonymous ones'); if (testElement) { ok(!_.isFunction(testElement), 'elements are not functions'); } }); if (typeof Int8Array !== 'undefined') { test('#1929 Typed Array constructors are functions', function() { _.chain(['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array']) .map(_.propertyOf(typeof GLOBAL != 'undefined' ? GLOBAL : window)) .compact() .each(function(TypedArray) { // PhantomJS reports `typeof UInt8Array == 'object'` and doesn't report toString TypeArray // as a function strictEqual(_.isFunction(TypedArray), Object.prototype.toString.call(TypedArray) === '[object Function]'); }); }); } test('isDate', function() { ok(!_.isDate(100), 'numbers are not dates'); ok(!_.isDate({}), 'objects are not dates'); ok(_.isDate(new Date()), 'but dates are'); }); test('isRegExp', function() { ok(!_.isRegExp(_.identity), 'functions are not RegExps'); ok(_.isRegExp(/identity/), 'but RegExps are'); }); test('isFinite', function() { ok(!_.isFinite(undefined), 'undefined is not finite'); ok(!_.isFinite(null), 'null is not finite'); ok(!_.isFinite(NaN), 'NaN is not finite'); ok(!_.isFinite(Infinity), 'Infinity is not finite'); ok(!_.isFinite(-Infinity), '-Infinity is not finite'); ok(_.isFinite('12'), 'Numeric strings are numbers'); ok(!_.isFinite('1a'), 'Non numeric strings are not numbers'); ok(!_.isFinite(''), 'Empty strings are not numbers'); var obj = new Number(5); ok(_.isFinite(obj), 'Number instances can be finite'); ok(_.isFinite(0), '0 is finite'); ok(_.isFinite(123), 'Ints are finite'); ok(_.isFinite(-12.44), 'Floats are finite'); }); test('isNaN', function() { ok(!_.isNaN(undefined), 'undefined is not NaN'); ok(!_.isNaN(null), 'null is not NaN'); ok(!_.isNaN(0), '0 is not NaN'); ok(_.isNaN(NaN), 'but NaN is'); ok(_.isNaN(new Number(NaN)), 'wrapped NaN is still NaN'); }); test('isNull', function() { ok(!_.isNull(undefined), 'undefined is not null'); ok(!_.isNull(NaN), 'NaN is not null'); ok(_.isNull(null), 'but null is'); }); test('isUndefined', function() { ok(!_.isUndefined(1), 'numbers are defined'); ok(!_.isUndefined(null), 'null is defined'); ok(!_.isUndefined(false), 'false is defined'); ok(!_.isUndefined(NaN), 'NaN is defined'); ok(_.isUndefined(), 'nothing is undefined'); ok(_.isUndefined(undefined), 'undefined is undefined'); }); test('isError', function() { ok(!_.isError(1), 'numbers are not Errors'); ok(!_.isError(null), 'null is not an Error'); ok(!_.isError(Error), 'functions are not Errors'); ok(_.isError(new Error()), 'Errors are Errors'); ok(_.isError(new EvalError()), 'EvalErrors are Errors'); ok(_.isError(new RangeError()), 'RangeErrors are Errors'); ok(_.isError(new ReferenceError()), 'ReferenceErrors are Errors'); ok(_.isError(new SyntaxError()), 'SyntaxErrors are Errors'); ok(_.isError(new TypeError()), 'TypeErrors are Errors'); ok(_.isError(new URIError()), 'URIErrors are Errors'); }); test('tap', function() { var intercepted = null; var interceptor = function(obj) { intercepted = obj; }; var returned = _.tap(1, interceptor); equal(intercepted, 1, 'passes tapped object to interceptor'); equal(returned, 1, 'returns tapped object'); returned = _([1, 2, 3]).chain(). map(function(n){ return n * 2; }). max(). tap(interceptor). value(); equal(returned, 6, 'can use tapped objects in a chain'); equal(intercepted, returned, 'can use tapped objects in a chain'); }); test('has', function () { var obj = {foo: 'bar', func: function(){}}; ok(_.has(obj, 'foo'), 'has() checks that the object has a property.'); ok(!_.has(obj, 'baz'), "has() returns false if the object doesn't have the property."); ok(_.has(obj, 'func'), 'has() works for functions too.'); obj.hasOwnProperty = null; ok(_.has(obj, 'foo'), 'has() works even when the hasOwnProperty method is deleted.'); var child = {}; child.prototype = obj; ok(!_.has(child, 'foo'), 'has() does not check the prototype chain for a property.'); strictEqual(_.has(null, 'foo'), false, 'has() returns false for null'); strictEqual(_.has(undefined, 'foo'), false, 'has() returns false for undefined'); }); test('isMatch', function() { var moe = {name: 'Moe Howard', hair: true}; var curly = {name: 'Curly Howard', hair: false}; equal(_.isMatch(moe, {hair: true}), true, 'Returns a boolean'); equal(_.isMatch(curly, {hair: true}), false, 'Returns a boolean'); equal(_.isMatch(5, {__x__: undefined}), false, 'can match undefined props on primitives'); equal(_.isMatch({__x__: undefined}, {__x__: undefined}), true, 'can match undefined props'); equal(_.isMatch(null, {}), true, 'Empty spec called with null object returns true'); equal(_.isMatch(null, {a: 1}), false, 'Non-empty spec called with null object returns false'); _.each([null, undefined], function(item) { strictEqual(_.isMatch(item, null), true, 'null matches null'); }); _.each([null, undefined], function(item) { strictEqual(_.isMatch(item, null), true, 'null matches {}'); }); strictEqual(_.isMatch({b: 1}, {a: undefined}), false, 'handles undefined values (1683)'); _.each([true, 5, NaN, null, undefined], function(item) { strictEqual(_.isMatch({a: 1}, item), true, 'treats primitives as empty'); }); function Prototest() {} Prototest.prototype.x = 1; var specObj = new Prototest; equal(_.isMatch({x: 2}, specObj), true, 'spec is restricted to own properties'); specObj.y = 5; equal(_.isMatch({x: 1, y: 5}, specObj), true); equal(_.isMatch({x: 1, y: 4}, specObj), false); ok(_.isMatch(specObj, {x: 1, y: 5}), 'inherited and own properties are checked on the test object'); Prototest.x = 5; ok(_.isMatch({x: 5, y: 1}, Prototest), 'spec can be a function'); //null edge cases var oCon = {'constructor': Object}; deepEqual(_.map([null, undefined, 5, {}], _.partial(_.isMatch, _, oCon)), [false, false, false, true], 'doesnt falsey match constructor on undefined/null'); }); test('matcher', function() { var moe = {name: 'Moe Howard', hair: true}; var curly = {name: 'Curly Howard', hair: false}; var stooges = [moe, curly]; equal(_.matcher({hair: true})(moe), true, 'Returns a boolean'); equal(_.matcher({hair: true})(curly), false, 'Returns a boolean'); equal(_.matcher({__x__: undefined})(5), false, 'can match undefined props on primitives'); equal(_.matcher({__x__: undefined})({__x__: undefined}), true, 'can match undefined props'); equal(_.matcher({})(null), true, 'Empty spec called with null object returns true'); equal(_.matcher({a: 1})(null), false, 'Non-empty spec called with null object returns false'); ok(_.find(stooges, _.matcher({hair: false})) === curly, 'returns a predicate that can be used by finding functions.'); ok(_.find(stooges, _.matcher(moe)) === moe, 'can be used to locate an object exists in a collection.'); deepEqual(_.where([null, undefined], {a: 1}), [], 'Do not throw on null values.'); deepEqual(_.where([null, undefined], null), [null, undefined], 'null matches null'); deepEqual(_.where([null, undefined], {}), [null, undefined], 'null matches {}'); deepEqual(_.where([{b: 1}], {a: undefined}), [], 'handles undefined values (1683)'); _.each([true, 5, NaN, null, undefined], function(item) { deepEqual(_.where([{a: 1}], item), [{a: 1}], 'treats primitives as empty'); }); function Prototest() {} Prototest.prototype.x = 1; var specObj = new Prototest; var protospec = _.matcher(specObj); equal(protospec({x: 2}), true, 'spec is restricted to own properties'); specObj.y = 5; protospec = _.matcher(specObj); equal(protospec({x: 1, y: 5}), true); equal(protospec({x: 1, y: 4}), false); ok(_.matcher({x: 1, y: 5})(specObj), 'inherited and own properties are checked on the test object'); Prototest.x = 5; ok(_.matcher(Prototest)({x: 5, y: 1}), 'spec can be a function'); // #1729 var o = {'b': 1}; var m = _.matcher(o); equal(m({'b': 1}), true); o.b = 2; o.a = 1; equal(m({'b': 1}), true, 'changing spec object doesnt change matches result'); //null edge cases var oCon = _.matcher({'constructor': Object}); deepEqual(_.map([null, undefined, 5, {}], oCon), [false, false, false, true], 'doesnt falsey match constructor on undefined/null'); }); test('matcher', function() { var moe = {name: 'Moe Howard', hair: true}; var curly = {name: 'Curly Howard', hair: false}; var stooges = [moe, curly]; equal(_.matcher({hair: true})(moe), true, 'Returns a boolean'); equal(_.matcher({hair: true})(curly), false, 'Returns a boolean'); equal(_.matcher({__x__: undefined})(5), false, 'can match undefined props on primitives'); equal(_.matcher({__x__: undefined})({__x__: undefined}), true, 'can match undefined props'); equal(_.matcher({})(null), true, 'Empty spec called with null object returns true'); equal(_.matcher({a: 1})(null), false, 'Non-empty spec called with null object returns false'); ok(_.find(stooges, _.matcher({hair: false})) === curly, 'returns a predicate that can be used by finding functions.'); ok(_.find(stooges, _.matcher(moe)) === moe, 'can be used to locate an object exists in a collection.'); deepEqual(_.where([null, undefined], {a: 1}), [], 'Do not throw on null values.'); deepEqual(_.where([null, undefined], null), [null, undefined], 'null matches null'); deepEqual(_.where([null, undefined], {}), [null, undefined], 'null matches {}'); deepEqual(_.where([{b: 1}], {a: undefined}), [], 'handles undefined values (1683)'); _.each([true, 5, NaN, null, undefined], function(item) { deepEqual(_.where([{a: 1}], item), [{a: 1}], 'treats primitives as empty'); }); function Prototest() {} Prototest.prototype.x = 1; var specObj = new Prototest; var protospec = _.matcher(specObj); equal(protospec({x: 2}), true, 'spec is restricted to own properties'); specObj.y = 5; protospec = _.matcher(specObj); equal(protospec({x: 1, y: 5}), true); equal(protospec({x: 1, y: 4}), false); ok(_.matcher({x: 1, y: 5})(specObj), 'inherited and own properties are checked on the test object'); Prototest.x = 5; ok(_.matcher(Prototest)({x: 5, y: 1}), 'spec can be a function'); // #1729 var o = {'b': 1}; var m = _.matcher(o); equal(m({'b': 1}), true); o.b = 2; o.a = 1; equal(m({'b': 1}), true, 'changing spec object doesnt change matches result'); //null edge cases var oCon = _.matcher({'constructor': Object}); deepEqual(_.map([null, undefined, 5, {}], oCon), [false, false, false, true], 'doesnt falsey match constructor on undefined/null'); }); test('findKey', function() { var objects = { a: {'a': 0, 'b': 0}, b: {'a': 1, 'b': 1}, c: {'a': 2, 'b': 2} }; equal(_.findKey(objects, function(obj) { return obj.a === 0; }), 'a'); equal(_.findKey(objects, function(obj) { return obj.b * obj.a === 4; }), 'c'); equal(_.findKey(objects, 'a'), 'b', 'Uses lookupIterator'); equal(_.findKey(objects, function(obj) { return obj.b * obj.a === 5; }), undefined); strictEqual(_.findKey([1, 2, 3, 4, 5, 6], function(obj) { return obj === 3; }), '2', 'Keys are strings'); strictEqual(_.findKey(objects, function(a) { return a.foo === null; }), undefined); _.findKey({a: {a: 1}}, function(a, key, obj) { equal(key, 'a'); deepEqual(obj, {a: {a: 1}}); strictEqual(this, objects, 'called with context'); }, objects); var array = [1, 2, 3, 4]; array.match = 55; strictEqual(_.findKey(array, function(x) { return x === 55; }), 'match', 'matches array-likes keys'); }); test('mapObject', function() { var obj = {'a': 1, 'b': 2}; var objects = { a: {'a': 0, 'b': 0}, b: {'a': 1, 'b': 1}, c: {'a': 2, 'b': 2} }; deepEqual(_.mapObject(obj, function(val) { return val * 2; }), {'a': 2, 'b': 4}, 'simple objects'); deepEqual(_.mapObject(objects, function(val) { return _.reduce(val, function(memo,v){ return memo + v; },0); }), {'a': 0, 'b': 2, 'c': 4}, 'nested objects'); deepEqual(_.mapObject(obj, function(val,key,obj) { return obj[key] * 2; }), {'a': 2, 'b': 4}, 'correct keys'); deepEqual(_.mapObject([1,2], function(val) { return val * 2; }), {'0': 2, '1': 4}, 'check behavior for arrays'); deepEqual(_.mapObject(obj, function(val) { return val * this.multiplier; }, {multiplier : 3}), {'a': 3, 'b': 6}, 'keep context'); deepEqual(_.mapObject({a: 1}, function() { return this.length; }, [1,2]), {'a': 2}, 'called with context'); var ids = _.mapObject({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){ return n.id; }); deepEqual(ids, {'length': undefined, '0': '1', '1': '2'}, 'Check with array-like objects'); // Passing a property name like _.pluck. var people = {'a': {name : 'moe', age : 30}, 'b': {name : 'curly', age : 50}}; deepEqual(_.mapObject(people, 'name'), {'a': 'moe', 'b': 'curly'}, 'predicate string map to object properties'); _.each([null, void 0, 1, 'abc', [], {}, undefined], function(val){ deepEqual(_.mapObject(val, _.identity), {}, 'mapValue identity'); }); var Proto = function(){this.a = 1;}; Proto.prototype.b = 1; var protoObj = new Proto(); deepEqual(_.mapObject(protoObj, _.identity), {a: 1}, 'ignore inherited values from prototypes'); }); }()); underscore-1.8.3/test/utility.js000066400000000000000000000352001250726036100167160ustar00rootroot00000000000000(function() { var _ = typeof require == 'function' ? require('..') : window._; var templateSettings; QUnit.module('Utility', { setup: function() { templateSettings = _.clone(_.templateSettings); }, teardown: function() { _.templateSettings = templateSettings; } }); test('#750 - Return _ instance.', 2, function() { var instance = _([]); ok(_(instance) === instance); ok(new _(instance) === instance); }); test('identity', function() { var stooge = {name : 'moe'}; equal(_.identity(stooge), stooge, 'stooge is the same as his identity'); }); test('constant', function() { var stooge = {name : 'moe'}; equal(_.constant(stooge)(), stooge, 'should create a function that returns stooge'); }); test('noop', function() { strictEqual(_.noop('curly', 'larry', 'moe'), undefined, 'should always return undefined'); }); test('property', function() { var stooge = {name : 'moe'}; equal(_.property('name')(stooge), 'moe', 'should return the property with the given name'); equal(_.property('name')(null), undefined, 'should return undefined for null values'); equal(_.property('name')(undefined), undefined, 'should return undefined for undefined values'); }); test('propertyOf', function() { var stoogeRanks = _.propertyOf({curly: 2, moe: 1, larry: 3}); equal(stoogeRanks('curly'), 2, 'should return the property with the given name'); equal(stoogeRanks(null), undefined, 'should return undefined for null values'); equal(stoogeRanks(undefined), undefined, 'should return undefined for undefined values'); function MoreStooges() { this.shemp = 87; } MoreStooges.prototype = {curly: 2, moe: 1, larry: 3}; var moreStoogeRanks = _.propertyOf(new MoreStooges()); equal(moreStoogeRanks('curly'), 2, 'should return properties from further up the prototype chain'); var nullPropertyOf = _.propertyOf(null); equal(nullPropertyOf('curly'), undefined, 'should return undefined when obj is null'); var undefPropertyOf = _.propertyOf(undefined); equal(undefPropertyOf('curly'), undefined, 'should return undefined when obj is undefined'); }); test('random', function() { var array = _.range(1000); var min = Math.pow(2, 31); var max = Math.pow(2, 62); ok(_.every(array, function() { return _.random(min, max) >= min; }), 'should produce a random number greater than or equal to the minimum number'); ok(_.some(array, function() { return _.random(Number.MAX_VALUE) > 0; }), 'should produce a random number when passed `Number.MAX_VALUE`'); }); test('now', function() { var diff = _.now() - new Date().getTime(); ok(diff <= 0 && diff > -5, 'Produces the correct time in milliseconds');//within 5ms }); test('uniqueId', function() { var ids = [], i = 0; while (i++ < 100) ids.push(_.uniqueId()); equal(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids'); }); test('times', function() { var vals = []; _.times(3, function (i) { vals.push(i); }); deepEqual(vals, [0, 1, 2], 'is 0 indexed'); // vals = []; _(3).times(function(i) { vals.push(i); }); deepEqual(vals, [0, 1, 2], 'works as a wrapper'); // collects return values deepEqual([0, 1, 2], _.times(3, function(i) { return i; }), 'collects return values'); deepEqual(_.times(0, _.identity), []); deepEqual(_.times(-1, _.identity), []); deepEqual(_.times(parseFloat('-Infinity'), _.identity), []); }); test('mixin', function() { _.mixin({ myReverse: function(string) { return string.split('').reverse().join(''); } }); equal(_.myReverse('panacea'), 'aecanap', 'mixed in a function to _'); equal(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper'); }); test('_.escape', function() { equal(_.escape(null), ''); }); test('_.unescape', function() { var string = 'Curly & Moe'; equal(_.unescape(null), ''); equal(_.unescape(_.escape(string)), string); equal(_.unescape(string), string, 'don\'t unescape unnecessarily'); }); // Don't care what they escape them to just that they're escaped and can be unescaped test('_.escape & unescape', function() { // test & (&) seperately obviously var escapeCharacters = ['<', '>', '"', '\'', '`']; _.each(escapeCharacters, function(escapeChar) { var str = 'a ' + escapeChar + ' string escaped'; var escaped = _.escape(str); notEqual(str, escaped, escapeChar + ' is escaped'); equal(str, _.unescape(escaped), escapeChar + ' can be unescaped'); str = 'a ' + escapeChar + escapeChar + escapeChar + 'some more string' + escapeChar; escaped = _.escape(str); equal(escaped.indexOf(escapeChar), -1, 'can escape multiple occurances of ' + escapeChar); equal(_.unescape(escaped), str, 'multiple occurrences of ' + escapeChar + ' can be unescaped'); }); // handles multiple escape characters at once var joiner = ' other stuff '; var allEscaped = escapeCharacters.join(joiner); allEscaped += allEscaped; ok(_.every(escapeCharacters, function(escapeChar) { return allEscaped.indexOf(escapeChar) !== -1; }), 'handles multiple characters'); ok(allEscaped.indexOf(joiner) >= 0, 'can escape multiple escape characters at the same time'); // test & -> & var str = 'some string & another string & yet another'; var escaped = _.escape(str); ok(escaped.indexOf('&') !== -1, 'handles & aka &'); equal(_.unescape(str), str, 'can unescape &'); }); test('template', function() { var basicTemplate = _.template("<%= thing %> is gettin' on my noives!"); var result = basicTemplate({thing : 'This'}); equal(result, "This is gettin' on my noives!", 'can do basic attribute interpolation'); var sansSemicolonTemplate = _.template('A <% this %> B'); equal(sansSemicolonTemplate(), 'A B'); var backslashTemplate = _.template('<%= thing %> is \\ridanculous'); equal(backslashTemplate({thing: 'This'}), 'This is \\ridanculous'); var escapeTemplate = _.template('<%= a ? "checked=\\"checked\\"" : "" %>'); equal(escapeTemplate({a: true}), 'checked="checked"', 'can handle slash escapes in interpolations.'); var fancyTemplate = _.template('
    <% ' + ' for (var key in people) { ' + '%>
  • <%= people[key] %>
  • <% } %>
'); result = fancyTemplate({people : {moe : 'Moe', larry : 'Larry', curly : 'Curly'}}); equal(result, '
  • Moe
  • Larry
  • Curly
', 'can run arbitrary javascript in templates'); var escapedCharsInJavascriptTemplate = _.template('
    <% _.each(numbers.split("\\n"), function(item) { %>
  • <%= item %>
  • <% }) %>
'); result = escapedCharsInJavascriptTemplate({numbers: 'one\ntwo\nthree\nfour'}); equal(result, '
  • one
  • two
  • three
  • four
', 'Can use escaped characters (e.g. \\n) in JavaScript'); var namespaceCollisionTemplate = _.template('<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %>
<% }); %>'); result = namespaceCollisionTemplate({ pageCount: 3, thumbnails: { 1: 'p1-thumbnail.gif', 2: 'p2-thumbnail.gif', 3: 'p3-thumbnail.gif' } }); equal(result, '3 p3-thumbnail.gif
'); var noInterpolateTemplate = _.template('

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

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

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

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