arrgh.js 104 KB
Newer Older
frank.xa.zhang's avatar
frank.xa.zhang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
/* exported arrgh */
/**
 * @license
 * MIT License
 * Copyright (c) 2017 Sander Rossel
 * 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.
 */
/**
 * Contains all collection classes used by arrgh.js.
 * @namespace arrgh
 */
(function (name, definition) {
    "use strict";
    if (typeof module !== "undefined") {
        module.exports = definition();
    }
    else if (typeof define === "function" && typeof define.amd === "object") {
        define(definition);
    }
    else {
        window[name] = definition();
    }
}("arrgh", function () {
	"use strict";
    return (function (undefined, MAX_SAFE_INTEGER) {
        // Helper functions

        /**
         * An accumulator function.
         *
         * @callback accumulator
         * @param {*} aggregate - The current aggregate.
         * @param {*} element - An item that should be aggregated to the aggregate.
         * @returns {*} - Returns the new aggregate.
         */

        /**
         * A function that is applied to each element in an enumerable.
         *
         * @callback forEachCallback
         * @param {*} element - The current element in the for loop.
         * @param {Number} index - The index of the current element.
         * @returns {bool} - Return false (or falsey, but not null or undefined) to jump out of the loop early.
         */

        /**
         * A function to test each element for a condition.
         *
         * @callback predicate
         * @param {*} element - The element to test for a condition.
         * @returns {Boolean} - Returns whether the current element satisfies the condition.
         */

        /**
         * A function to test each element for a condition.
         *
         * @callback indexPredicate
         * @param {*} element - The element to test for a condition.
         * @param {Number} [index] - The index of the current element.
         * @returns {Boolean} - Returns whether the current element satisfies the condition.
         */

        /**
         * A function that projects an element into a new form.
         *
         * @callback selector
         * @param {*} element - The element to project into a new form.
         * @returns {*} - A projection of the current element.
         */

        /**
         * A function that projects an element into a new form.
         *
         * @callback indexSelector
         * @param {*} element - The element to project into a new form.
         * @param {Number} [index] - The index of the current element.
         * @returns {*} - A projection of the current element.
         */

        /**
         * A function that projects an element into a collection.
         *
         * @callback collectionSelector
         * @param {*} element - The element to project into a collection.
         * @param {Number} [index] - The index of the current element.
         * @returns {Array|String|arrgh.Enumerable} - A collection obtained from the current element.
         */

        /**
         * A function that returns the key value from an element.
         *
         * @callback keySelector
         * @param {*} element - The element from which to select a key.
         * @returns {*} - The value of the key for the current element.
         */

        /**
         * A function that tests if an object is smaller than, greater than or equal to another object.
         * @callback compare
         * @param {*} x - The element to compare to another element.
         * @param {*} y - The element to compare to.
         * @returns {Number} - Returns a negative value if the first object is smaller, a positive value if the first object is greater and 0 if both objects are equal.
         */

        /**
         * A function that tests if two elements are equal.
         * @callback equals
         * @param {*} x - The element to test for equality.
         * @param {*} y - The element to test on.
         * @returns {Boolean} - Return whether the elements are equal.
         */

        /**
         * A function that creates a result value from a group of elements.
         * @callback groupByResultSelector
         * @param {*} key - The key that groups the elements.
         * @param {grouping} group - The elements in the group.
         * @returns {*} - Returns a result value from a group of elements.
         */

        /**
         * A function that creates a result value from a group of elements.
         * @callback groupJoinResultSelector
         * @param {*} element - The element that is joined.
         * @param {grouping} group - The elements that are joined with the element.
         * @returns {*} - Returns a result value from a group of elements.
         */

        /**
         * A function that creates a result value from two elements.
         * @callback joinResultSelector
         * @param {*} outer - The element that is joined.
         * @param {*} inner - The element that is joined with the outer element.
         * @returns {*} - Returns a result value from two matched elements.
         */

        /**
         * A function that creates a result value from each element in the intermediate collection.
         * @callback selectManyResultSelector
         * @param {*} element - The element whose collection is processed.
         * @param {*} intermediate - The current element of the intermediate collection.
         * @returns {*} - Returns a result value from an intermediate element.
         */

        /**
         * A function that creates a result value from two elements.
         * @callback zipResultSelector
         * @param {*} sourceElement - An element from the source collection.
         * @param {*} otherElement - An element from the other collection.
         * @returns {*} - Returns a result value from two elements.
         */

        /**
         * Returns a hash code for the specified object.
         * @callback getHash
         * @param {*} obj - The object for which a hash code is to be returned.
         * @returns {String} - A hash code for the specified object.
         */

        /**
         * Defines methods to support the comparison of objects for equality.
         * @name equalityComparer
         * @type {Object}
         * @property {equals} [equals=(===)] - A function that tests if two elements are equal.
         * @property {getHash} [getHash=getHash() || toString()] - A function that computes an element's hash code.
         */

        /**
         * A collection of objects that share a common key.
         * @name grouping
         * @type {arrgh.Enumerable}
         * @property {*} key - The key that the elements have in common.
         */

        /**
         * A result that defines whether an operation was a success and, if yes, holds the result of that operation.
         * @name tryResult
         * @type {Object}
         * @property {Boolean} success - Indicates whether an operation was a success.
         * @property {*} value - When successful, holds the result value of an operation. Otherwise undefined.
         */

        var Temp = function () {
            // This will shut up JSLint :-)
            // Minify will remove 'return' so no precious bytes are lost.
188
            return;
frank.xa.zhang's avatar
frank.xa.zhang committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656
        };

        function inherit(inheritor, inherited) {
            Temp.prototype = inherited.prototype;
            inheritor.prototype = new Temp();
            Temp.prototype = null;
            inheritor.prototype.constructor = inheritor;
        }

        function isArray(o) {
            return Object.prototype.toString.call(o) === "[object Array]";
        }

        function isNull(obj) {
            return obj === undefined || obj === null;
        }

        function isActualNaN(obj) {
            return obj !== obj;
        }

        function alwaysTrue() {
            return true;
        }

        function identity(x) {
            return x;
        }

        function defaultCompare(x, y) {
            if (isNull(x) || isNull(y)) {
                // Treat undefined as smaller than null
                // and both as smaller than anything else.
                var noVal = function (a, b, val) {
                    if (a === b) {
                        return 0;
                    }
                    if (a === val && b !== val) {
                        return -1;
                    }
                    if (a !== val && b === val) {
                        return 1;
                    }
                };
                var eq = noVal(x, y, undefined);

                if (eq === undefined) {
                    return noVal(x, y, null);
                }
                return eq;
            }

            // Treat NaN as smaller than anything else
            // except undefined and null.
            if (isActualNaN(x) && isActualNaN(y)) {
                return 0;
            }
            if (isActualNaN(x)) {
                return -1;
            }
            if (isActualNaN(y)) {
                return 1;
            }

            if (x > y) {
                return 1;
            }
            if (x < y) {
                return -1;
            }
            return 0;
        }

        var defaultEqComparer = {
            equals: function (x, y) {
                return x === y || (isActualNaN(x) && isActualNaN(y)); // NaN edge case.
            },
            getHash: function (obj) {
                var hash;
                if (obj === null) {
                    hash = "null";
                } else if (obj === undefined) {
                    hash = "undefined";
                } else if (isActualNaN(obj)) {
                    hash = "NaN";
                } else {
                    hash = typeof obj.getHash === "function" ?
                        obj.getHash() :
                        typeof obj.toString === "function" ? obj.toString() : Object.prototype.toString.call(obj);
                }
                return hash;
            }
        };

        function ensureEqComparer(eqComparer) {
            if (!eqComparer || eqComparer === defaultEqComparer) {
                return defaultEqComparer;
            }
            if (eqComparer.equals && eqComparer.getHash) {
                return eqComparer;
            }

            var fullEqComparer;
            if (typeof eqComparer === "function") {
                fullEqComparer = {
                    equals: eqComparer,
                    getHash: defaultEqComparer.getHash
                };
            } else {
                fullEqComparer = {
                    equals: eqComparer.equals || defaultEqComparer.equals,
                    getHash: eqComparer.getHash || defaultEqComparer.getHash
                };
            }
            return fullEqComparer;
        }

        function findElem(collection, predicate, xOrDefault) {
            if (!collection.any()) {
                throw new Error("Collection contains no elements.");
            }
            var def = {},
            elem = xOrDefault(predicate, def);
            if (elem === def) {
                throw new Error("Collection contains no matching element.");
            }
            return elem;
        }

        function findOrDefault(collection, onFound, predicate, defaultValue) {
            var temp = predicate;
            predicate = typeof predicate === "function" ? predicate : undefined;
            defaultValue = predicate ? defaultValue : temp;
            if (collection.any()) {
                var context = {
                    found: false,
                    elem: undefined
                };
                collection.forEach(function (elem) {
                    if (predicate) {
                        if (predicate(elem)) {
                            return onFound(context, elem);
                        }
                    } else {
                        return onFound(context, elem);
                    }
                });
                if (!context.found) {
                    return defaultValue;
                }
                return context.elem;
            }
            return defaultValue;
        }

        function sumCount(collection, selector, calculator) {
            selector = selector || identity;
            var sum = 0,
            count = 0;
            collection.forEach(function (elem) {
                sum += +selector(elem);
                count += 1;
            });

            if (count === 0) {
                throw new Error("Collection contains no elements.");
            }

            return calculator(sum, count);
        }

        /**
         * A parameterless function that moves the iterator to the next position.<br />
         * Returns false when no next position is found.
         * @function moveNext
         * @memberof arrgh.Iterator
         * @instance
         * @returns {Boolean} - Returns whether the Iterator has moved to the next position.
         */

        /**
         * A parameterless function that returns the value at the current position.<br />
         * Returns undefined when the iterator is at its initial position or when moveNext returns false.
         * @function current
         * @memberof arrgh.Iterator
         * @instance
         * @returns {*} - Returns the value at the current position of the Iterator.
         */

        /**
         * Supports iteration over a collection.
         * @memberof arrgh
         * @constructor
         * @param {function} moveNext - A parameterless function that moves the iterator to the next position.
         * @param {function} current - A parameterless function that returns the value at the current position.
         */
        var Iterator = function (moveNext, current) {
            this.moveNext = moveNext;
            this.current = current;
        };

        var getArrayIterator = function (arr) {
            var len = arr.length,
            index = -1;
            return new Iterator(function () {
                if (arr.length !== len) {
                    throw new Error("Collection was modified, enumeration operation may not execute.");
                }
                index += 1;
                return index < len;
            }, function () {
                return arr[index];
            });
        };

        // Enumerables

        /**
         * Returns an iterator that iterates through the collection.
         * @function getIterator
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Iterator} - Returns an iterator that iterates through the collection.
         */

        /**
         * Represents the base class for any collection.
         * @memberof arrgh
         * @constructor
         * @param {(Array|String|arrgh.Enumerable|Function|params)} [enumerable=[]] - An array, string or enumerable to add to the new collection or a parameterless function that returns an {@link arrgh.Iterator}.
         */
        var Enumerable = function (enumerable) {
            var iterable;
            if (arguments.length > 1) {
                iterable = Array.prototype.slice.call(arguments);
            } else {
                iterable = enumerable || [];
            }

            if (isArray(iterable) || typeof iterable === "string") {
                this.getIterator = function () {
                    return getArrayIterator(iterable);
                };
            } else if (iterable.getIterator) {
                this.getIterator = iterable.getIterator;
            } else if (typeof iterable === "function") {
                this.getIterator = iterable;
            } else {
                throw new Error("The input parameter for Enumerable was not valid.");
            }
        };

        /**
         * Represents a list of objects that can be accessed by index. Provides methods to manipulate the list.
         * @memberof arrgh
         * @constructor
         * @extends arrgh.Enumerable
         * @param {(Array|String|arrgh.Enumerable|params)} [enumerable=[]] - An array, string or enumerable whose elements are copied to the new list.
         */
        var List = function (enumerable) {
            var self = this,
            iterable,
            arr;

            Enumerable.call(this, function () {
                return getArrayIterator(self._.arr);
            });

            if (arguments.length > 1) {
                iterable = Array.prototype.slice.call(arguments);
            } else {
                iterable = enumerable || [];
            }

            if (isArray(iterable)) {
                arr = iterable.slice();
            } else if (typeof iterable === "string") {
                arr = iterable.split("");
            } else if (iterable.getIterator) {
                arr = [];
                iterable.forEach(function (elem) {
                    arr.push(elem);
                });
            } else {
                throw new Error("The input parameter for List was not valid.");
            }
            this._ = {
                arr: arr
            };
            this.length = arr.length;
        };
        inherit(List, Enumerable);

        /**
         * Represents a collection of keys and values.
         * @memberof arrgh
         * @constructor
         * @extends arrgh.Enumerable
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two objects are equal.
         */
        var Dictionary = function (eqComparer) {
            var self = this;

            Enumerable.call(self, function () {
                var iterator = self._.entries.getIterator();
                return new Iterator(function () {
                    return iterator.moveNext();
                }, function () {
                    var current = iterator.current();
                    if (current) {
                        return {
                            key: current.key,
                            value: current.value
                        };
                    }
                    return undefined;
                });
            });

            this.length = 0;
            this._ = {
                eqComparer: ensureEqComparer(eqComparer),
                keys: {},
                entries: new List()
            };
        };
        inherit(Dictionary, Enumerable);

        /**
         * Represents a collection of keys each mapped to one or more values.
         * @memberof arrgh
         * @private
         * @constructor
         * @extends arrgh.Enumerable
         * @param {arrgh.Enumerable} source - The collection to map to a lookup.
         * @param {keySelector} keySelector - A function that returns the key value from an element of the inner collection.
         * @param {selector} [elementSelector] - A function that projects an element into a new form.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two keys are equal.
         */
        var Lookup = function (source, keySelector, elementSelector, eqComparer) {
            var d;
            Enumerable.call(this, function () {
                var iterator = d.getIterator();
                return new Iterator(iterator.moveNext, function () {
                    var current = iterator.current();
                    if (isNull(current)) {
                        return current;
                    }
                    var group = current.value.asEnumerable();
                    group.key = current.key;
                    return group;
                });
            });

            if (typeof elementSelector !== "function") {
                eqComparer = elementSelector;
                elementSelector = null;
            }
            elementSelector = elementSelector || identity;

            d = new Dictionary(eqComparer);
            source.forEach(function (elem) {
                var key = keySelector(elem);
                var element = elementSelector(elem);
                if (d.containsKey(key)) {
                    d.get(key).add(element);
                } else {
                    d.add(key, new List([element]));
                }
            });

            this.length = d.length;

            /**
             * Gets the collection at the specified key.
             * @function get
             * @memberof arrgh.Lookup
             * @instance
             * @param {*} key - The key of the collection which should be retrieved.
             * @returns {grouping} - Returns the collection with the specified key or an empty collection if the key was not found.
             */
            this.get = function (key) {
                var group;
                if (d.containsKey(key)) {
                    group = d.get(key).asEnumerable();
                    group.key = key;
                } else {
                    group = new Enumerable();
                    group.key = key;
                }
                return group;
            };
        };
        inherit(Lookup, Enumerable);

        function stableQuicksort(map, startIndex, endIndex, compare) {
            var low = startIndex,
            high = endIndex,
            pindex = Math.floor((low + high) / 2),
            pivot = map[pindex],
            lindex,
            hindex,
            result,
            temp;
            while (low <= high) {
                lindex = map[low];
                result = compare(lindex, pivot);
                while (result < 0 || (result === 0 && lindex < pivot)) {
                    low += 1;
                    lindex = map[low];
                    result = compare(lindex, pivot);
                }

                hindex = map[high];
                result = compare(hindex, pivot);
                while (result > 0 || (result === 0 && hindex > pivot)) {
                    high -= 1;
                    hindex = map[high];
                    result = compare(hindex, pivot);
                }
                if (low <= high) {
                    temp = map[low];
                    map[low] = map[high];
                    map[high] = temp;
                    low += 1;
                    high -= 1;
                }
            }

            if (low < endIndex) {
                stableQuicksort(map, low, endIndex, compare);
            }
            if (high > startIndex) {
                stableQuicksort(map, startIndex, high, compare);
            }
        }

        /**
         * Represents an ordered collection that can be iterated over.
         * @memberof arrgh
         * @private
         * @constructor
         * @extends arrgh.Enumerable
         * @param {arrgh.Enumerable} source - The collection that needs to be sorted.
         * @param {keySelector} keySelector - A function to extract the key from an element.
         * @param {compare} [compare] - A function that tests if an object is smaller than, greater than or equal to another object.
         * @param {Boolean} descending - Indicated wheter the collection needs to be sorted ascending or descending.
         */
        var OrderedEnumerable = function (source, keySelector, compare, descending) {
            var self = this,
            keys;
            compare = compare || defaultCompare;
            descending = descending ? -1 : 1;

            self.getSource = function () {
                if (source.getSource) {
                    return source.getSource();
                }
                return source;
            };

            self.computeKeys = function (elements, count) {
                var arr = new Array(count),
                i;
                for (i = 0; i < count; i += 1) {
                    arr[i] = keySelector(elements[i]);
                }
                keys = arr;
                if (source.computeKeys) {
                    source.computeKeys(elements, count);
                }
            };
            self.compareKeys = function (i, j) {
                var result = 0;
                if (source.compareKeys) {
                    result = source.compareKeys(i, j);
                }
                if (result === 0) {
                    result = compare(keys[i], keys[j]) * descending;
                }
                return result;
            };
            Enumerable.call(this, function () {
                var sourceArr = self.getSource().toArray(),
                count = sourceArr.length,
                map = new Array(count),
                index;
                self.computeKeys(sourceArr, count);
                for (index = 0; index < count; index += 1) {
                    map[index] = index;
                }
                stableQuicksort(map, 0, count - 1, self.compareKeys);
                index = -1;
                return new Iterator(function () {
                    index += 1;
                    return index < count;
                }, function () {
                    return sourceArr[map[index]];
                });
            });
        };
        inherit(OrderedEnumerable, Enumerable);

        var getUnionIterator = function (first, second, eqComparer) {
            var firstIterator = first.getIterator(),
            secondIterator = second.getIterator(),
            current,
            moveFirst = true,
            d,
            alreadyUnioned,
            moveNext;

            var move = function (iterator) {
                var hasNext = iterator.moveNext();
                if (hasNext) {
                    current = iterator.current();
                    if (eqComparer && alreadyUnioned(current)) {
                        return moveNext(iterator);
                    }
                }
                return hasNext;
            };

            if (eqComparer) {
                d = new Dictionary(eqComparer);

                alreadyUnioned = function (elem) {
                    if (d.containsKey(elem)) {
                        return true;
                    }
                    d.add(elem);
                    return false;
                };
            }
            moveNext = function () {
                current = undefined;
                if (moveFirst) {
                    moveFirst = move(firstIterator);
                    if (!moveFirst) {
                        // If there is no next item
                        // move on to the second iterator.
                        return moveNext();
                    }

                    return true;
                }
                return move(secondIterator);
            };

            return new Iterator(moveNext, function () {
                return current;
            });
        };

        var empty = new Enumerable(),
        enumProto = Enumerable.prototype,
        aggregate = function (source, aggregator) {
            var iterator = source.getIterator();
            if (!iterator.moveNext()) {
                throw new Error("Collection contains no elements.");
            }
            var accumulate = iterator.current();
            while (iterator.moveNext()) {
                accumulate = aggregator(accumulate, iterator.current());
            }
            return accumulate;
        },
        aggregateSeed = function (source, seed, aggregator, resultSelector) {
            resultSelector = resultSelector || identity;
            var accumulate = seed,
            loopedOnce = false;
            source.forEach(function (elem) {
                loopedOnce = true;
                accumulate = aggregator(accumulate, elem);
            });
            if (!loopedOnce) {
                throw new Error("Collection contains no elements.");
            }
            return resultSelector(accumulate);
        };

        /**
         * Determines whether all elements of the collection satisfy a condition.<br />
         * When a result selector is passed to the function a seed should also be specified.
         * @param {*} [seed] - The initial accumulator value (mandatory if a result selector is specified).
         * @param {accumulator} accumulator - An accumulator function to be invoked on each element.
         * @param {selector} [resultSelector] - A function to transform the final accumulator value into the result value.
         * @function aggregate
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {*} - The final accumulator value.
         */
        enumProto.aggregate = function (seed, accumulator, selector) {
            if (accumulator) {
                return aggregateSeed(this, seed, accumulator, selector);
            }
            return aggregate(this, seed);
        };

        /**
         * Determines whether all elements of the collection satisfy a condition.
         * @param {predicate} predicate - A function to test each element for a condition.
         * @function all
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Boolean} - True if the list is empty or if all elements in the collection satisfy a condition, else false.
         */
        enumProto.all = function (predicate) {
            var all = true;
            this.forEach(function (elem) {
                all = predicate(elem);
                return all;
            });
            return all;
        };

        /**
         * Determines whether the collection contains any elements or if any elements satisfy a condition.
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @function any
         * @see {@link arrgh.Enumerable#some}
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Boolean} - True if the collection contains any elements or if any elements satisfy a condition, else false.
         */
        enumProto.any = function (predicate) {
            var any = false;
            this.forEach(function (elem, index) {
                if (predicate) {
                    any = predicate(elem, index);
                    return !any;
                }
                any = true;
                return false;
            });
            return any;
        };

        /**
         * Determines whether the collection contains any elements or if any elements satisfy a condition.
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @function some
         * @see {@link arrgh.Enumerable#any}
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Boolean} - True if the collection contains any elements or if any elements satisfy a condition, else false.
         */
        enumProto.some = enumProto.any;

        /**
         * Returns the input typed as Enumerable.
         * @function asEnumerable
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - The input collection as Enumerable.
         */
        enumProto.asEnumerable = function () {
            return new Enumerable(this.getIterator);
        };

        /**
         * Computes the average of a collection of values.<br />
         * Values are converted to numerics, but if this fails unexpected averages may occur.
         * @param {selector} [selector] - A function that projects an element into a new form.
         * @function average
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Number} - The average of all values in the collection, or NaN.
         * @throws Throws an error if the collection contains no elements.
         */
        enumProto.average = function (selector) {
            return sumCount(this, selector, function (sum, count) {
                return sum / count;
            });
        };

        /**
         * Concatenates two collections.
         * @param {other} other - The collection to concatenate to the current collection.
         * @function concat
         * @see {@link arrgh.Enumerable#unionAll}
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - A collection that contains all the elements of both the current and the other collection.
         */
        enumProto.concat = function (other) {
            var self = this;
            return new Enumerable(function () {
                return getUnionIterator(self, other);
            });
        };

        /**
         * Concatenates two collections.
         * @param {other} other - The collection to concatenate to the current collection.
         * @function unionAll
         * @see {@link arrgh.Enumerable#concat}
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - A collection that contains all the elements of both the current and the other collection.
         */
        enumProto.unionAll = enumProto.concat;

        /**
         * Determines whether a collection contains a specified element, optionally uses a custom equality comparer.
         * @param {*} elem - The element to locate in the collection.
         * @param {equals|equalityComparer} [eqComparer=(===)] - A function or object that tests if two elements are equal.
         * @function contains
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Boolean} - Returns whether the specified element is contained in the collection.
         */
        enumProto.contains = function (elem, eqComparer) {
            eqComparer = ensureEqComparer(eqComparer);
            var hasElem = false;
            this.forEach(function (item) {
                hasElem = eqComparer.equals(item, elem);
                return !hasElem;
            });
            return hasElem;
        };

        /**
         * Specifies how many elements the collection has, or how many satisfy a certain condition.
         * @function count
         * @memberof arrgh.Enumerable
         * @instance
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @returns {Number} - A number that specifies how many elements the collection has, or how many satisfy a certain condition.
         */
        enumProto.count = function (predicate) {
            var count = 0;
            predicate = predicate || alwaysTrue;

            this.forEach(function (elem) {
                if (predicate(elem)) {
                    count += 1;
                }
            });
            return count;
        };

        /**
         * Returns the elements of the specified collection or a collection containing only the default value if the collection is empty.
         * @function defaultIfEmpty
         * @memberof arrgh.Enumerable
         * @instance
         * @param {*} defaultValue - The default value to be returned when the collection is empty.
         * @returns {arrgh.Enumerable} - A new collection containing the elements of the specified collection or a new collection containing only the default value if the collection is empty.
         */
        enumProto.defaultIfEmpty = function (defaultValue) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator();
                var current;
                var empty = true;
                return new Iterator(function () {
                    current = undefined;
                    if (iterator.moveNext()) {
                        empty = false;
                        current = iterator.current();
                        return true;
                    }
                    if (empty) {
                        empty = false;
                        current = defaultValue;
                        return true;
                    }
                    return false;
                }, function () {
                    return current;
                });
            });
        };

        /**
         * Returns distinct elements from a collection by using the default or a custom equality comparer to compare values.
         * @function distinct
         * @memberof arrgh.Enumerable
         * @instance
         * @param {equals|equalityComparer} [eqComparer=(===)] - A function or object that tests if two elements are equal.
         * @returns {arrgh.Enumerable} - A new collection with unique elements.
         */
        enumProto.distinct = function (eqComparer) {
            return this.union(empty, eqComparer);
        };

        /**
         * Returns the element at a specified index.
         * @function elementAt
         * @memberof arrgh.Enumerable
         * @instance
         * @param {Number} index - The index of the element to find.
         * @returns {*} - The element at the specified index.
         * @throws Throws an error if the specified index is outside the bounds of the collection.
         */
        enumProto.elementAt = function (index) {
            var def = {};
            var elem = this.elementAtOrDefault(index, def);
            if (elem === def) {
                throw new Error("Index was outside the bounds of the collection.");
            }
            return elem;
        };

        /**
         * Returns the element at a specified index or a default value.
         * @function elementAtOrDefault
         * @memberof arrgh.Enumerable
         * @instance
         * @param {Number} index - The index of the element to find.
         * @param {*} [defaultValue] - The value that is returned when the specified index is not found.
         * @returns {*} - The element at the specified index or a default value.
         */
        enumProto.elementAtOrDefault = function (index, defaultValue) {
            if (index < 0) {
                return defaultValue;
            }

            var elem,
            elemSet = false;
            this.forEach(function (e, i) {
                if (i === index) {
                    elem = e;
                    elemSet = true;
                    return false;
                }
            });

            if (!elemSet) {
                return defaultValue;
            }
            return elem;
        };

        /**
         * Returns an empty singleton instance of enumerable.
         * @function empty
         * @memberof arrgh.Enumerable
         * @static
         * @returns {arrgh.Enumerable} - An empty singleton collection.
         */
        Enumerable.empty = function () {
            return empty;
        };

        /**
         * Produces the set difference of two collections.
         * @function except
         * @memberof arrgh.Enumerable
         * @instance
         * @param {arrgh.Enumerable} other - A collection whose elements that also occur in the first sequence will cause those elements to be removed from the returned collection.
         * @param {equals|equalityComparer} [eqComparer=(===)] - A function or object that tests if two elements are equal.
         * @returns {arrgh.Enumerable} - A collection that contains the set difference of the elements of two collections.
         */
        enumProto.except = function (other, eqComparer) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                d = new Dictionary(eqComparer),
                current;
                other.forEach(function (elem) {
                    if (!d.containsKey(elem)) {
                        d.add(elem);
                    }
                });
                return new Iterator(function () {
                    while (iterator.moveNext()) {
                        current = iterator.current();
                        if (!d.containsKey(current)) {
                            d.add(current);
                            return true;
                        }
                    }
                    current = undefined;
                    return false;
                }, function () {
                    return current;
                });
            });
        };

        /**
         * Returns the first element in a collection, or the first element that satisfies a condition.
         * @function first
         * @memberof arrgh.Enumerable
         * @instance
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @returns {*} - Returns the first element of the collection, or the first element that satisfies a condition.
         * @throws Throws an error if the collection is empty or when no element matches the condition.
         */
        enumProto.first = function (predicate) {
            var self = this;
            return findElem(this, predicate, function (predicate, defaultValue) {
                return self.firstOrDefault(predicate, defaultValue);
            });
        };

        /**
         * Returns the first element in a collection, or the first element that satisfies a condition.<br />
         * If the element is not found returns a default value.
         * @function firstOrDefault
         * @memberof arrgh.Enumerable
         * @instance
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @param {*} [defaultValue] - The value that is returned when the collection is empty or no element matches the condition.
         * @returns {*} - Returns the first element of the collection, or the first element that satisfies a condition, or a specified default value.
         */
        enumProto.firstOrDefault = function (predicate, defaultValue) {
            return findOrDefault(this, function (context, foundElem) {
                context.elem = foundElem;
                context.found = true;
                return false;
            }, predicate, defaultValue);
        };

        /**
         * Performs the specified action on each element of the collection.
         * @param {forEachCallback} callback - The callback that is applied to each element in the enumerable.
         * @function forEach
         * @memberof arrgh.Enumerable
         * @instance
         */
        enumProto.forEach = function (callback) {
            var iterator = this.getIterator(),
            cont = null,
            index = 0;
            while ((isNull(cont) || cont) && iterator.moveNext()) {
                cont = callback(iterator.current(), index);
                index += 1;
            }
        };

        /**
         * Groups the elements of a collection according to a specified key selector.
         * @param {keySelector} keySelector - A function that returns the key value from an element.
         * @param {selector} [elementSelector] - A function to project an element into a new form.
         * @param {groupByResultSelector} [resultSelector] - A function to create a result value from each group.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two keys are equal.
         * @function groupBy
         * @memberof arrgh.Enumerable
         * @instance
         * @arrgh.Enumerable - A collection where each object contains a collection of objects and a key.
         */
        enumProto.groupBy = function (keySelector) {
            var self = this,
            elementSelector,
            resultSelector,
            eqComparer,
            args = Array.prototype.slice.call(arguments),
            setArg = function (index) {
                var type = typeof args[index];
                if (type === "object") {
                    eqComparer = args[index];
                } else if (type === "function") {
                    if (args[index].length === 1) {
                        elementSelector = args[index];
                    } else {
                        resultSelector = args[index];
                    }
                }
            };
            setArg(1);
            setArg(2);
            setArg(3);

            elementSelector = elementSelector || identity;
            eqComparer = ensureEqComparer(eqComparer);

            return new Enumerable(function () {
                var iterator = self.toLookup(keySelector, elementSelector, eqComparer).getIterator();
                return new Iterator(iterator.moveNext, function () {
                    var current = iterator.current();
                    if (isNull(current)) {
                        return current;
                    }
                    if (resultSelector) {
                        return resultSelector(current.key, current);
                    }
                    return current;
                });
            });
        };

        /**
         * Correlates the elements of two collections based on equality of keys and groups the results.
         * @param {arrgh.Enumerable} inner - The collection to join with.
         * @param {keySelector} outerKeySelector - A function that returns the key value from an element of the outer collection.
         * @param {keySelector} innerKeySelector - A function that returns the key value from an element of the inner collection.
         * @param {groupJoinResultSelector} resultSelector - A function to create a result value from each group.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two keys are equal.
         * @function groupJoin
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - A collection that contains elements that are obtained by performing a grouped join on two collections.
         */
        enumProto.groupJoin = function (inner, outerKeySelector, innerKeySelector, resultSelector, eqComparer) {
            var self = this;
            eqComparer = ensureEqComparer(eqComparer);
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                innerLookup = inner.toLookup(innerKeySelector, eqComparer),
                moved = false;
                return new Iterator(function () {
                    moved = iterator.moveNext();
                    return moved;
                }, function () {
                    if (!moved) {
                        return undefined;
                    }
                    var current = iterator.current();
                    var outerKey = outerKeySelector(current);
                    return resultSelector(current, innerLookup.get(outerKey));
                });
            });
        };

        /**
         * Finds the first index at which a given element can be found in the collection, or -1 if it is not present.
         * @param {*} searchElem - The element to locate in the collection.
         * @param {Number} [fromIndex=0] - The index to start the search at.
         * @function indexOf
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Number} - The first index of the element in the array or -1 if not found.
         */
        enumProto.indexOf = function (searchElem, fromIndex) {
            fromIndex = fromIndex || 0;
            var foundIndex = -1;
            this.forEach(function (elem, index) {
                if (index >= fromIndex && defaultEqComparer.equals(searchElem, elem)) {
                    foundIndex = index;
                    return false;
                }
            });
            return foundIndex;
        };

        /**
         * Produces the set intersection of two collections.
         * @function intersect
         * @memberof arrgh.Enumerable
         * @instance
         * @param {arrgh.Enumerable} other - A collection whose elements that also occur in the first sequence will cause those elements to be included in the returned collection.
         * @param {equals|equalityComparer} [eqComparer=(===)] - A function or object that tests if two elements are equal.
         * @returns {arrgh.Enumerable} - A collection that contains the set intersection of the elements of two collections.
         */
        enumProto.intersect = function (other, eqComparer) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                d = new Dictionary(eqComparer);
                other.forEach(function (elem) {
                    if (!d.containsKey(elem)) {
                        d.add(elem);
                    }
                });
                var current;
                return new Iterator(function () {
                    while (iterator.moveNext()) {
                        current = iterator.current();
                        if (d.containsKey(current)) {
                            return d.remove(current);
                        }
                    }
                    current = undefined;
                    return false;
                }, function () {
                    return current;
                });
            });
        };

        /**
         * Correlates the elements of two collections based on equality of keys.
         * @param {arrgh.Enumerable} inner - The collection to join with.
         * @param {keySelector} outerKeySelector - A function that returns the key value from an element of the outer collection.
         * @param {keySelector} innerKeySelector - A function that returns the key value from an element of the inner collection.
         * @param {joinResultSelector} resultSelector - A function to create a result from two matched elements.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two keys are equal.
         * @function join
         * @memberof arrgh.Enumerable
         * @instance
         * returns {arrgh.Enumerable} - A collection that has elements that are obtained by performing an inner join on two collections.
         */
        enumProto.join = function (inner, outerKeySelector, innerKeySelector, resultSelector, eqComparer) {
            var self = this;
            eqComparer = ensureEqComparer(eqComparer);
            return new Enumerable(function () {

                var outerIterator = self.getIterator(),
                innerLookup = inner.toLookup(innerKeySelector, eqComparer),
                moved,
                innerIterator,
                outerCurrent,
                innerCurrent,
                moveNext;

                moveNext = function () {
                    if (innerIterator) {
                        moved = innerIterator.moveNext();
                        if (moved) {
                            innerCurrent = innerIterator.current();
                        } else {
                            innerIterator = undefined;
                            moveNext();
                        }
                    } else {
                        moved = outerIterator.moveNext();
                        if (moved) {
                            outerCurrent = outerIterator.current();
                            innerIterator = innerLookup.get(outerKeySelector(outerCurrent)).getIterator();
                            moveNext();
                        }
                    }
                    return moved;
                };
                return new Iterator(moveNext, function () {
                    if (!moved) {
                        return undefined;
                    }
                    return resultSelector(outerCurrent, innerCurrent);
                });
            });
        };

        /**
         * Returns the last element in a collection, or the last element that satisfies a condition.
         * @function last
         * @memberof arrgh.Enumerable
         * @instance
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @returns {*} - Returns the last element of the collection, or the last element that satisfies a condition.
         * @throws Throws an error when the collection is empty or when no element matches the condition.
         */
        enumProto.last = function (predicate) {
            var self = this;
            return findElem(this, predicate, function (predicate, defaultValue) {
                return self.lastOrDefault(predicate, defaultValue);
            });
        };

        /**
         * Finds the last index at which a given element can be found in the collection, or -1 if it is not present.
         * @param {*} searchElem - The element to locate in the collection.
         * @param {Number} [fromIndex=0] - The index to start the search at.
         * @function lastIndexOf
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Number} - The last index of the element in the array or -1 if not found.
         */
        enumProto.lastIndexOf = function (searchElem, fromIndex) {
            fromIndex = fromIndex || 0;
            var foundIndex = -1;
            this.forEach(function (elem, index) {
                if (index >= fromIndex && defaultEqComparer.equals(searchElem, elem)) {
                    foundIndex = index;
                }
            });
            return foundIndex;
        };

        /**
         * Returns the last element in a collection, or the last element that satisfies a condition.<br />
         * If the element is not found returns a default value.
         * @function lastOrDefault
         * @memberof arrgh.Enumerable
         * @instance
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @param {*} [defaultValue] - The value that is returned when the collection is empty or no element matches the condition.
         * @returns {*} - Returns the last element of the collection, or the last element that satisfies a condition, or a specified default value.
         */
        enumProto.lastOrDefault = function (predicate, defaultValue) {
            return findOrDefault(this, function (context, foundElem) {
                context.elem = foundElem;
                context.found = true;
            }, predicate, defaultValue);
        };

        /**
         * Returns the maximum value in a collection.<br />
         * Values are converted to numerics. If this fails and the value is NaN then NaN is treated as smaller than anything.
         * @param {selector} [selector] - A function that projects an element into a new form.
         * @function max
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {*} - Returns the maximum value in the collection or NaN.
         * @throws Throws an error when the collection is empty.
         */
        enumProto.max = function (selector) {
            selector = selector || identity;
            var max,
            first = true,
            hasNan = false;
            this.forEach(function (elem) {
                elem = selector(elem);
                if (!isNull(elem)) {
                    elem = +elem;
                    // Really weird behavior where NaN is smaller
                    // than anything else (except in the min function).
                    // And, of course, it can't be compared to anything...
                    if (isNaN(elem)) {
                        hasNan = true;
                    } else {
                        if (first) {
                            first = false;
                            max = elem;
                        } else {
                            if (defaultCompare(elem, max) > 0) {
                                max = elem;
                            }
                        }
                    }
                }
            });
            if (first) {
                if (hasNan) {
                    max = NaN;
                } else {
                    throw new Error("Collection contains no elements.");
                }
            }
            return max;
        };

        /**
         * Returns the minimum value in a collection.<br />
         * Values are converted to numerics. If this fails the function returns NaN.
         * @param {selector} [selector] - A function that projects an element into a new form.
         * @function min
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {*} - Returns the minimum value in the collection or NaN.
         * @throws Throws an error when the collection is empty.
         */
        enumProto.min = function (selector) {
            selector = selector || identity;
            var min,
            first = true;
            this.forEach(function (elem) {
                elem = selector(elem);
                if (!isNull(elem)) {
                    elem = +elem;
                    if (isNaN(elem)) {
                        // Really weird behavior where NaN is smaller
                        // than anything else (except in the min function).
                        first = false;
                        min = elem;
                        return false;
                    }
                    if (first) {
                        first = false;
                        min = elem;
                    } else {
                        if (defaultCompare(elem, min) < 0) {
                            min = elem;
                        }
                    }
                }
            });
            if (first) {
                throw new Error("Collection contains no elements.");
            }
            return min;
        };

        /**
         * Filters elements based on a specified type (constructor).<br />
         * Object and null do not evaluate to the same type and neither do undefined and null.
         * @param {*|undefined|null} type - The constructor of a type or undefined or null.
         * @function ofType
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - Returns a collection containing only values that are of the specified type.
         */
        enumProto.ofType = function (type) {
            var typeName;
            var getType;
            if (type === Boolean) {
                typeName = "boolean";
            } else if (type === Number) {
                typeName = "number";
            } else if (type === String) {
                typeName = "string";
            } else if (type === Function) {
                typeName = "function";
            } else if (type === Object) {
                getType = function (elem) {
                    return elem && typeof elem === "object";
                };
            } else if (type === undefined) {
                typeName = "undefined";
            } else if (type === null) {
                getType = function (elem) {
                    return elem === null;
                };
            } else {
                getType = function (elem) {
                    return elem instanceof type;
                };
            }
            getType = getType || function (elem) {
                return typeof elem === typeName;
            };
            return this.where(getType);
        };

        /**
         * Sorts the elements of a sequence in ascending order according to a key.
         * @function orderBy
         * @memberof arrgh.Enumerable
         * @instance
         * @param {keySelector} keySelector - A function to extract a key from an element.
         * @param {compare} [compare] - A function that tests if an object is smaller than, greater than or equal to another object.
         * @returns {arrgh.OrderedEnumerable} - Returns an ordered enumerable.
         */
        enumProto.orderBy = function (keySelector, compare) {
            return new OrderedEnumerable(this, keySelector, compare, false);
        };

        /**
         * Sorts the elements of a sequence in descending order according to a key.
         * @function orderByDescending
         * @memberof arrgh.Enumerable
         * @instance
         * @param {keySelector} keySelector - A function to extract a key from an element.
         * @param {compare} [compare] - A function that tests if an object is smaller than, greater than or equal to another object.
         * @returns {arrgh.OrderedEnumerable} - Returns an ordered enumerable.
         */
        enumProto.orderByDescending = function (keySelector, compare) {
            return new OrderedEnumerable(this, keySelector, compare, true);
        };

        /**
         * Generates a collection of integral numbers within a specified range.<br />
         * When no count is supplied the range will stop at 9007199254740991 (a.k.a. Number.MAX_SAFE_INTEGER).<br />
         * Depending on your start value your browser will probably flip though, so just provide a count.
         * @function range
         * @memberof arrgh.Enumerable
         * @static
         * @param {Number} start - The value of the first integer in the collection.
         * @param {Number} [count] - The number of sequential integers to generate.
         * @returns {arrgh.Enumerable} - A collection that contains a range of sequential integral numbers.
         * @throws Throws when count is lower than 0 or when the range exceeds 9007199254740991 (a.k.a. Number.MAX_SAFE_INTEGER).
         */
        Enumerable.range = function (start, count) {
            if (!isNull(count)) {
                if (count < 0) {
                    throw new Error("Count cannot be lower than 0.");
                }
                if (start + (count - 1) > MAX_SAFE_INTEGER) {
                    throw new Error("Start and count can not exceed " + MAX_SAFE_INTEGER + ".");
                }
            }
            return new Enumerable(function () {
                if (isNull(count)) {
                    var moved = false;
                    return new Iterator(function () {
                        if (!moved) {
                            moved = true;
                        } else {
                            start += 1;
                        }
                        return start <= MAX_SAFE_INTEGER;
                    }, function () {
                        if (!moved || start > MAX_SAFE_INTEGER) {
                            return undefined;
                        }
                        return start;
                    });
                } else {
                    var index = -1;
                    return new Iterator(function () {
                        index += 1;
                        return index < count;
                    }, function () {
                        if (index === -1 || index >= count) {
                            return undefined;
                        }
                        return start + index;
                    });
                }
            });
        };

        /**
         * Generates a collection that contains one repeated value.
         * @function repeat
         * @memberof arrgh.Enumerable
         * @static
         * @param {*} element - The element to repeat.
         * @param {Number} count - The number of times to repeat the element.
         * @returns {arrgh.Enumerable} - A collection that contains a one value count times.
         * @throws Throws when count is lower than 0.
         */
        Enumerable.repeat = function (element, count) {
            count = count || 0;
            if (count < 0) {
                throw new Error("Count cannot be lower than 0.");
            }
            return new Enumerable(function () {
                var index = -1;
                return new Iterator(function () {
                    index += 1;
                    return index < count;
                }, function () {
                    if (index === -1 || index >= count) {
                        return undefined;
                    }
                    return element;
                });
            });
        };

        /**
         * Reverses the order of the elements in a collection.
         * @function reverse
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - A collection that contains the original collection in reversed order.
         */
        enumProto.reverse = function () {
            var self = this;
            return new Enumerable(function () {
                var list = new List(self),
                length = list.length,
                index = length;
                return new Iterator(function () {
                    index -= 1;
                    return index >= 0;
                }, function () {
                    if (index < 0 || index === length) {
                        return undefined;
                    }
                    return list.get(index);
                });
            });
        };

        /**
         * Projects each element of a collection into a new form.
         * @param {indexSelector} selector - A function that projects an element into a new form.
         * @function select
         * @see {@link arrgh.Enumerable#map}
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - A collection whose elements are the result of invoking the transform function on each element of source.
         */
        enumProto.select = function (selector) {
            var self = this;
            return new Enumerable(function () {
                var index = -1,
                iterator = self.getIterator(),
                next;
                return new Iterator(function () {
                    index += 1;
                    next = iterator.moveNext();
                    return next;
                }, function () {
                    var current;
                    if (next) {
                        current = selector(iterator.current(), index);
                    }
                    return current;
                });
            });
        };

        /**
         * Projects each element of a collection into a new form.
         * @param {indexSelector} selector - A function that projects an element into a new form.
         * @function map
         * @see {@link arrgh.Enumerable#select}
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - A collection whose elements are the result of invoking the transform function on each element of source.
         */
        enumProto.map = enumProto.select;

        /**
         * Projects each element of a collection to an Enumerable and flattens the resulting collections into one collection.
         * @param {collectionSelector} collectionSelector - A function that projects an element into a new form.
         * @param {selectManyResultSelector} [resultSelector] - A function that creates a result value from each element in the intermediate collection.
         * @function selectMany
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.Enumerable} - A collection whose elements are the result of invoking the one-to-many transform function on each element of the input collection.
         */
        enumProto.selectMany = function (collectionSelector, resultSelector) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                innerIterator,
                outerCurrent,
                current,
                index = -1,
                moveNext;

                moveNext = function () {
                    current = undefined;
                    if (innerIterator) {
                        if (innerIterator.moveNext()) {
                            if (resultSelector) {
                                current = resultSelector(outerCurrent, innerIterator.current());
                            } else {
                                current = innerIterator.current();
                            }
                            return true;
                        } else {
                            innerIterator = null;
                            return moveNext();
                        }
                    }

                    if (iterator.moveNext()) {
                        index += 1;
                        outerCurrent = iterator.current();
                        innerIterator = new Enumerable(collectionSelector(outerCurrent, index)).getIterator();
                        return moveNext();
                    }
                    return false;
                };
                return new Iterator(moveNext, function () {
                    return current;
                });
            });
        };

        /**
         * Determines whether two collections are equal by comparing the elements, optionally using a custom equality comparer for their type.
         * @param {arrgh.Enumerable} other - Another collection to compare with.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two objects are equal.
         * @function sequenceEquals
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Boolean} - True if all elements in both collections match, otherwise false.
         */
        enumProto.sequenceEquals = function (other, eqComparer) {
            eqComparer = ensureEqComparer(eqComparer);

            var iterator = this.getIterator(),
            otherIterator = other.getIterator(),
            equal = true;
            while (iterator.moveNext() && equal) {
                if (!otherIterator.moveNext() || !eqComparer.equals(iterator.current(), otherIterator.current())) {
                    equal = false;
                }
            }
            equal = !otherIterator.moveNext();
            return equal;
        };

        /**
         * Returns the only element in a collection, or the only element that satisfies a condition.
         * @function single
         * @memberof arrgh.Enumerable
         * @instance
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @returns {*} - Returns the only element of the collection, or the only element that satisfies a condition.
         * @throws Throws an error when the collection is empty or when no element matches the condition or when the collection (or predicate) returns more than a single element.
         */
        enumProto.single = function (predicate) {
            var self = this;
            return findElem(this, predicate, function (predicate, defaultValue) {
                return self.singleOrDefault(predicate, defaultValue);
            });
        };

        /**
         * Returns the only element in a collection, or the only element that satisfies a condition.<br />
         * If the element is not found returns a default value.
         * @function singleOrDefault
         * @memberof arrgh.Enumerable
         * @instance
         * @param {predicate} [predicate] - A function to test each element for a condition.
         * @param {*} [defaultValue] - The value that is returned when the collection is empty or no element matches the condition.
         * @returns {*} - Returns the only element of the collection, or the only element that satisfies a condition, or a specified default value.
         * @throws Throws an error when the collection (or predicate) returns more than a single element.
         */
        enumProto.singleOrDefault = function (predicate, defaultValue) {
            return findOrDefault(this, function (context, foundElem) {
                if (context.found) {
                    throw new Error("Collection contains more than one matching element.");
                }
                context.elem = foundElem;
                context.found = true;
            }, predicate, defaultValue);
        };

        /**
         * Bypasses a specified number of elements in a collection and then returns the remaining elements.
         * @function skip
         * @memberof arrgh.Enumerable
         * @instance
         * @param {Number} count - The number of elements to skip.
         * @returns {arrgh.Enumerable} - A collection that contains the elements that occur after the specified index.
         */
        enumProto.skip = function (count) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                skipped = 0;
                return new Iterator(function () {
                    while (skipped < count) {
                        skipped += 1;
                        if (!iterator.moveNext()) {
                            return false;
                        }
                    }
                    return iterator.moveNext();
                }, function () {
                    return iterator.current();
                });
            });
        };

        /**
         * Bypasses elements in a collection as long as a specified condition is true and then returns the remaining elements.
         * @function skipWhile
         * @memberof arrgh.Enumerable
         * @instance
         * @param {indexPredicate} predicate - A function to test whether to skip the element.
         * @returns {arrgh.Enumerable} - A collection that contains the elements starting at the first element in the linear series that does not pass the test specified by predicate.
         */
        enumProto.skipWhile = function (predicate) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                index = -1,
                current,
                skipped = false;
                return new Iterator(function () {
                    current = undefined;
                    while (!skipped) {
                        index += 1;
                        if (iterator.moveNext()) {
                            current = iterator.current();
                            if (!predicate(current, index)) {
                                skipped = true;
                                return true;
                            }
                        } else {
                            skipped = true;
                            return false;
                        }
                    }
                    var next = iterator.moveNext();
                    current = iterator.current();
                    return next;
                }, function () {
                    return current;
                });
            });
        };

        /**
         * Computes the sum of a collection of values.<br />
         * If values are not numerics the result may be NaN or something unexpected (e.g. "2" + 2 will results 22).
         * @param {selector} [selector] - A function that projects an element into a new form.
         * @function sum
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Number} - The sum of all values in the collection, or NaN.
         * @throws Throws an error if the collection contains no elements.
         */
        enumProto.sum = function (selector) {
            return sumCount(this, selector, function (sum) {
                return sum;
            });
        };

        /**
         * Returns a specified number of elements from the start of a collection.
         * @function take
         * @memberof arrgh.Enumerable
         * @instance
         * @param {Number} count - The number of elements to take.
         * @returns {arrgh.Enumerable} - A collection that contains the elements that occur before the specified index.
         */
        enumProto.take = function (count) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                index = -1;
                return new Iterator(function () {
                    index += 1;
                    return index < count && iterator.moveNext();
                }, function () {
                    if (index === -1 || index >= count) {
                        return undefined;
                    }
                    return iterator.current();
                });
            });
        };

        /**
         * Returns elements from a collection as long as a specified condition is true.
         * @function takeWhile
         * @memberof arrgh.Enumerable
         * @instance
         * @param {indexPredicate} predicate - A function to test whether to take the element.
         * @returns {arrgh.Enumerable} - A collection that contains the elements that occur before the element at which the test no longer passes.
         */
        enumProto.takeWhile = function (predicate) {
            var self = this;
            return new Enumerable(function () {
                var iterator = self.getIterator(),
                take = true,
                current,
                index = -1;
                return new Iterator(function () {
                    take = take && iterator.moveNext();
                    if (take) {
                        index += 1;
                        current = iterator.current();
                        take = predicate(current, index);
                    }
                    return take;
                }, function () {
                    if (take) {
                        return current;
                    }
                });
            });
        };

        /**
         * Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.
         * @function thenBy
         * @memberof arrgh.OrderedEnumerable
         * @instance
         * @param {keySelector} keySelector - A function to extract a key from an element.
         * @param {compare} [compare] - A function that tests if an object is smaller than, greater than or equal to another object.
         * @returns {arrgh.OrderedEnumerable} - Returns an ordered enumerable.
         */
        OrderedEnumerable.prototype.thenBy = function (keySelector, compare) {
            return new OrderedEnumerable(this, keySelector, compare, false);
        };

        /**
         * Performs a subsequent ordering of the elements in a sequence in descending order according to a key.
         * @function thenByDescending
         * @memberof arrgh.OrderedEnumerable
         * @instance
         * @param {keySelector} keySelector - A function to extract a key from an element.
         * @param {compare} [compare] - A function that tests if an object is smaller than, greater than or equal to another object.
         * @returns {arrgh.OrderedEnumerable} - Returns an ordered enumerable.
         */
        OrderedEnumerable.prototype.thenByDescending = function (keySelector, compare) {
            return new OrderedEnumerable(this, keySelector, compare, true);
        };

        /**
         * Converts the collection to a JavaScript array.
         * @function toArray
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {Array} - Returns a JavaScript array.
         */
        enumProto.toArray = function () {
            var arr = [];
            this.forEach(function (elem) {
                arr.push(elem);
            });
            return arr;
        };

        /**
         * Converts the collection to a dictionary.
         * @function toDictionary
         * @memberof arrgh.Enumerable
         * @instance
         * @param {keySelector} keySelector - A function that returns the key value from an element of the inner collection.
         * @param {selector} [elementSelector] - A function that projects an element into a new form.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two keys are equal.
         * @returns {arrgh.Dictionary} - Returns a dictionary containing the keys and elements that are selected from the input collection.
         */
        enumProto.toDictionary = function (keySelector, elementSelector, eqComparer) {
            if (typeof arguments[1] === "function") {
                elementSelector = arguments[1];
                eqComparer = arguments[2];
            } else {
                eqComparer = arguments[1];
                elementSelector = undefined;
            }
            elementSelector = elementSelector || identity;
            eqComparer = ensureEqComparer(eqComparer);

            var d = new Dictionary(eqComparer);
            this.forEach(function (elem) {
                d.add(keySelector(elem), elementSelector(elem));
            });
            return d;
        };

        /**
         * Converts the collection to a list.
         * @function toList
         * @memberof arrgh.Enumerable
         * @instance
         * @returns {arrgh.List} - Returns a List containing all the elements from the input collection.
         */
        enumProto.toList = function () {
            return new List(this);
        };

        /**
         * Converts the collection to a collection of keys each mapped to one or more values.
         * @function toLookup
         * @memberof arrgh.Enumerable
         * @instance
         * @param {keySelector} keySelector - A function that returns the key value from an element of the inner collection.
         * @param {selector} [elementSelector] - A function that projects an element into a new form.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two keys are equal.
         * @returns {arrgh.Lookup} - Returns a collection of keys mapped to one or more values.
         */
        enumProto.toLookup = function (keySelector, elementSelector, eqComparer) {
            if (typeof arguments[1] === "function") {
                elementSelector = arguments[1];
                eqComparer = arguments[2];
            } else {
                eqComparer = arguments[1];
            }
            elementSelector = elementSelector || identity;
            eqComparer = ensureEqComparer(eqComparer);

            return new Lookup(this, keySelector, elementSelector, eqComparer);
        };

        /**
         * Produces the set union of two collections by using the default or a custom equality comparer to compare values.
         * @function union
         * @memberof arrgh.Enumerable
         * @instance
         * @param {arrgh.Enumerable} other - The other collection to union with.
         * @param {equalityComparer} [eqComparer=(===)] - An object that tests if two elements are equal.
         * @returns {arrgh.Enumerable} - A collection that contains distinct element from the two input collections.
         */
        enumProto.union = function (other, eqComparer) {
            var self = this;
            return new Enumerable(function () {
                return getUnionIterator(self, other, ensureEqComparer(eqComparer));
            });
        };

        /**
         * Filters a collection of values based on a predicate. Each element's index is used in the logic of the predicate function.
         * @function where
         * @see {@link arrgh.Enumerable#filter}
         * @memberof arrgh.Enumerable
         * @instance
         * @param {indexPredicate} predicate - A function to test each element for a condition.
         * @returns {arrgh.Enumerable} - A collection that contains all elements that satisfy the condition.
         */
        enumProto.where = function (predicate) {
            var self = this;
            return new Enumerable(function () {
                var index = -1,
                iterator = self.getIterator(),
                current;
                return new Iterator(function () {
                    while (iterator.moveNext()) {
                        index += 1;
                        current = iterator.current();
                        if (predicate(current, index)) {
                            return true;
                        }
                    }
                    current = undefined;
                    return false;
                }, function () {
                    return current;
                });
            });
        };

        /**
         * Filters a collection of values based on a predicate. Each element's index is used in the logic of the predicate function.
         * @function filter
         * @see {@link arrgh.Enumerable#where}
         * @memberof arrgh.Enumerable
         * @instance
         * @param {indexPredicate} predicate - A function to test each element for a condition.
         * @returns {arrgh.Enumerable} - A collection that contains all elements that satisfy the condition.
         */
        enumProto.filter = enumProto.where;

        /**
         * Applies a specified function to the corresponding elements of two collections, producing a collection of the results.
         * @function zip
         * @memberof arrgh.Enumerable
         * @instance
         * @param {arrgh.Enumerable} other - The collection to merge with.
         * @param {zipResultSelector} resultSelector - A function that creates a result value from two elements.
         * @returns {arrgh.Enumerable} - A collection that contains merged elements of two input collections.
         */
        enumProto.zip = function (other, resultSelector) {
            var self = this;
            return new Enumerable(function () {
                var sourceIterator = self.getIterator(),
                otherIterator = other.getIterator(),
                current;

                return new Iterator(function () {
                    current = undefined;
                    if (sourceIterator.moveNext() && otherIterator.moveNext()) {
                        current = resultSelector(sourceIterator.current(), otherIterator.current());
                        return true;
                    }
                    return false;
                }, function () {
                    return current;
                });
            });
        };

        var listProto = List.prototype;

        function throwIfOutOfBounds(index, upperBound) {
            if (index < 0 || index >= upperBound) {
                throw new Error("Index was out of range. Must be non-negative and less than the size of the collection.");
            }
        }

        function isRange(list, index, count) {
            if (count < 0) {
                throw new Error('Count cannot be negative.');
            }
            if (index === 0 && count === 0) {
                return false;
            }
            throwIfOutOfBounds(index, list.length);
            if (index + count > list.length) {
                throw new Error("Count is greater than the number of elements from index to the end of the source collection.");
            }
            return true;
        }

        /**
         * Adds an item to the list.
         * @function add
         * @memberof arrgh.List
         * @instance
         * @param {*} item - The item to add to the list.
         */
        listProto.add = function (item) {
            this._.arr.push(item);
            this.length += 1;
        };

        /**
         * Adds multiple items to the list.
         * @function addRange
         * @memberof arrgh.List
         * @instance
         * @param {Array|arrgh.Enumerable|params} items - The items to add to the list.
         */
        listProto.addRange = function (items) {
            if (arguments.length === 1 && items.getIterator) {
                var self = this;
                arguments[0].forEach(function (item) {
                    self._.arr.push(item);
                });
            } else {
                var arr = arguments.length === 1 && isArray(items) ? items : arguments;
                this._.arr.push.apply(this._.arr, arr);
            }
            this.length = this._.arr.length;
        };

        /**
         * Removes all items from the list.
         * @function clear
         * @memberof arrgh.List
         * @instance
         */
        listProto.clear = function () {
            this._.arr = [];
            this.length = 0;
        };

        /**
         * Gets the item at the specified index.
         * @function get
         * @memberof arrgh.List
         * @instance
         * @param {Number} index - The index at which the item should be retrieved.
         * @returns {*} - Returns the item at the specified index.
         * @throws Throws an error when the index is smaller than zero or equal or greater than the length of the collection.
         */
        listProto.get = function (index) {
            throwIfOutOfBounds(index, this.length);
            return this._.arr[index];
        };

        /**
         * Inserts an item in the list at the specified index.
         * @function insert
         * @memberof arrgh.List
         * @instance
         * @param {Number} index - The index at which the new item will be inserted.
         * @param {*} item - The object to insert into the list.
         * @throws Throws an error when the index is smaller than zero or greater than the length of the collection.
         */
        listProto.insert = function (index, item) {
            throwIfOutOfBounds(index, this.length + 1);
            this._.arr.splice(index, 0, item);
            this.length += 1;
        };

        /**
         * Inserts a range of items in the list at the specified index.
         * @function insertRange
         * @memberof arrgh.List
         * @instance
         * @param {Number} index - The index at which the new items will be inserted.
         * @param {Array|arrgh.Enumerable|params} items - The items to insert into the list.
         * @throws Throws an error when the index is smaller than zero or greater than the length of the collection.
         */
        listProto.insertRange = function (index, items) {
            throwIfOutOfBounds(index, this.length + 1);
            var arr = this._.arr,
            arrToInsert;
            if (items.getIterator) {
                arrToInsert = items.toArray();
            } else if (isArray(items)) {
                arrToInsert = items;
            } else {
                arrToInsert = Array.prototype.slice.call(arguments, 1);
            }
            arr.splice.apply(arr, [index, 0].concat(arrToInsert));
            this.length = arr.length;
        };

        /**
         * Removes the first occurrence of an item from the list.
         * @function remove
         * @memberof arrgh.List
         * @instance
         * @param {*} item - The item to remove from the list.
         * @returns {Boolean} - Returns whether the item was removed from the list.
         */
        listProto.remove = function (item) {
            var index = this.indexOf(item);

            if (index >= 0) {
                this._.arr.splice(index, 1);
                this.length -= 1;
                return true;
            }
            return false;
        };

        /**
         * Removes all the elements that match the conditions defined by the specified predicate.
         * @function removeAll
         * @memberof arrgh.List
         * @instance
         * @param {predicate} predicate - A function to test each element for a condition.
         * @returns {Number} - Returns the number of elements that were removed.
         */
        listProto.removeAll = function (predicate) {
            var arr = this._.arr,
            count = 0,
            i;

            for (i = arr.length - 1; i >= 0; i -= 1) {
                if (predicate(arr[i])) {
                    arr.splice(i, 1);
                    count += 1;
                }
            }
            this.length = arr.length;
            return count;
        };

        /**
         * Removes the element at the specified index.
         * @function removeAt
         * @memberof arrgh.List
         * @instance
         * @param {Number} index - The index of the element to remove.
         * @throws Throws an error when the index is smaller than zero or equal or greater than the length of the collection.
         */
        listProto.removeAt = function (index) {
            throwIfOutOfBounds(index, this.length);
            this._.arr.splice(index, 1);
            this.length -= 1;
        };

        /**
         * Removes a range of elements.
         * @function removeRange
         * @memberof arrgh.List
         * @instance
         * @param {Number} index - The starting index of the range of elements to remove.
         * @param {Number} count - The number of elements to remove.
         * @throws Throws an error when the index is smaller than zero or equal or greater than the length of the collection or when the index plus the count are greater than the length of the collection.
         */
        listProto.removeRange = function (index, count) {
            if (isRange(this, index, count)) {
                this._.arr.splice(index, count);
                this.length = this._.arr.length;
            }
        };

        /**
         * Sets an element at the specified index.
         * @function set
         * @memberof arrgh.List
         * @instance
         * @param {Number} index - The index of the element to overwrite.
         * @param {*} value - The value to set.
         * @throws Throws an error when the index is smaller than zero or equal or greater than the length of the collection.
         */
        listProto.set = function (index, value) {
            throwIfOutOfBounds(index, this.length);
            this._.arr[index] = value;
        };

        /**
         * Sorts the list.
         * @function sort
         * @memberof arrgh.List
         * @instance
         * @param {Number} [index=0] - The starting index of the range of elements to sort.
         * @param {Number} [count=list.length] - The length of the range to sort.
         * @param {compare} [compare] - A function that tests if an object is smaller than, greater than or equal to another object.
         * @throws Throws an error when the index is smaller than zero or equal or greater than the length of the collection or when the index plus the count are greater than the length of the collection.
         */
        listProto.sort = function (index, count, compare) {
            var arr = this._.arr,
            map = [],
            partToSort,
            compareOriginals,
            i;

            if (typeof index === "function") {
                compare = index;
                index = 0;
            } else if (typeof count === "function") {
                compare = count;
                count = undefined;
            } else {
                compare = compare;
            }
            index = isNull(index) ? 0 : index;
            count = isNull(count) ? arr.length - index : count;
            compare = compare || defaultCompare;

            if (!isRange(this, index, count)) {
                return;
            }

            partToSort = arr.splice(index, count);
            for (i = 0; i < partToSort.length; i += 1) {
                map.push(i);
            }

            compareOriginals = function (x, y) {
                return compare(partToSort[x], partToSort[y]);
            };

            stableQuicksort(map, 0, partToSort.length - 1, compareOriginals);

            var sorted = new Array(partToSort.length);
            for (i = 0; i < partToSort.length; i += 1) {
                sorted[i] = partToSort[map[i]];
            }

            this.insertRange(index, sorted);
        };

        listProto.count = function (predicate) {
            if (!predicate) {
                return this.length;
            } else {
                return Enumerable.prototype.count.call(this, predicate);
            }
        };

        listProto.elementAt = function (index) {
            throwIfOutOfBounds(index, this.length);
            return this._.arr[index];
        };

        listProto.elementAtOrDefault = function (index, defaultValue) {
            if (index < 0 || index >= this.length) {
                return defaultValue;
            }
            return this._.arr[index];
        };

        listProto.indexOf = function (searchElem, fromIndex) {
            fromIndex = fromIndex || 0;
            for (fromIndex; fromIndex < this.length; fromIndex += 1) {
                if (defaultEqComparer.equals(this._.arr[fromIndex], searchElem)) {
                    return fromIndex;
                }
            }
            return -1;
        };

        listProto.last = function (predicate) {
            if (this.length > 0 && !predicate) {
                return this._.arr[this.length - 1];
            } else {
                return Enumerable.prototype.last.call(this, predicate);
            }
        };

        listProto.lastIndexOf = function (searchElem, fromIndex) {
            fromIndex = fromIndex || 0;
            var i;
            for (i = this.length; fromIndex <= i; i -= 1) {
                if (defaultEqComparer.equals(this._.arr[i], searchElem)) {
                    return i;
                }
            }
            return -1;
        };

        listProto.lastOrDefault = function (predicate, defaultValue) {
            if (typeof arguments[0] === "function") {
                return Enumerable.prototype.lastOrDefault.call(this, predicate, defaultValue);
            } else {
                if (this.length > 0) {
                    return this._.arr[this.length - 1];
                } else {
                    return arguments[0];
                }
            }
        };

        listProto.toArray = function () {
            return this._.arr.slice();
        };

        var dictProto = Dictionary.prototype;

        function dictionaryContainsKey(dictionary, hash, key) {
            if (dictionary._.keys.hasOwnProperty(hash)) {
                return dictionary._.keys[hash].contains(key, function (x, y) {
                    return dictionary._.eqComparer.equals(x.key, y);
                });
            }
            return false;
        }

        function getPairByKey(dict, hash, key, whenNotExists) {
            var elem;
            if (!dict._.keys.hasOwnProperty(hash)) {
                whenNotExists();
            } else {
                var def = {};
                elem = dict._.keys[hash].firstOrDefault(function (kvp) {
                    return dict._.eqComparer.equals(kvp.key, key);
                }, def);
                if (elem === def) {
                    whenNotExists();
                }
            }
            return elem;
        }

        /**
         * Adds the specified key and value to the dictionary.
         * @function add
         * @memberof arrgh.Dictionary
         * @instance
         * @param {*} key - The key of the element to add.
         * @param {*} value - The value of the element to add.
         * @throws When a key is already present in the dictionary.
         */
        dictProto.add = function (key, value) {
            var hash = this._.eqComparer.getHash(key);
            if (dictionaryContainsKey(this, hash, key)) {
                throw new Error("Key [" + key + "] is already present in the dictionary.");
            }

            if (!this._.keys[hash]) {
                this._.keys[hash] = new List();
            }
            var pair = {
                key: key,
                value: value
            };
            this._.keys[hash].add(pair);
            this._.entries.add(pair);

            this.length += 1;
        };

        /**
         * Removes all items from the dictionary.
         * @function clear
         * @memberof arrgh.Dictionary
         * @instance
         */
        dictProto.clear = function () {
            this._.entries.clear();
            this._.keys = {};
            this.length = 0;
        };

        /**
         * Check whether a key is present in the dictionary.
         * @function containsKey
         * @memberof arrgh.Dictionary
         * @instance
         * @param {*} key - The key to locate.
         * @returns True if the key is present, otherwise false.
         */
        dictProto.containsKey = function (key) {
            var hash = this._.eqComparer.getHash(key);
            return dictionaryContainsKey(this, hash, key);
        };

        /**
         * Check whether a value is present in the dictionary.
         * @function containsValue
         * @memberof arrgh.Dictionary
         * @instance
         * @param {*} value - The value to locate.
         * @returns True if the value is present, otherwise false.
         */
        dictProto.containsValue = function (value) {
            return this.any(function (p) {
                return defaultEqComparer.equals(p.value, value);
            });
        };

        /**
         * Gets the item at the specified key.
         * @function get
         * @memberof arrgh.Dictionary
         * @instance
         * @param {*} key - The key of the element which should be retrieved.
         * @returns {*} - Returns the element with the specified key.
         * @throws Throws an error when the key is not present in the dictionary.
         */
        dictProto.get = function (key) {
            var hash = this._.eqComparer.getHash(key);
            return getPairByKey(this, hash, key, function () {
                throw new Error("Key [" + key + "] was not found in the dictionary.");
            }).value;
        };

        /**
         * Gets all keys in the dictionary.
         * @function getKeys
         * @memberof arrgh.Dictionary
         * @instance
         * @returns {Array} - An array containing all keys in the dictionary.
         */
        dictProto.getKeys = function () {
            var arr = [];
            this.forEach(function (p) {
                arr.push(p.key);
            });
            return arr;
        };

        /**
         * Gets all values in the dictionary.
         * @function getValues
         * @memberof arrgh.Dictionary
         * @instance
         * @returns {Array} - An array containing all values in the dictionary.
         */
        dictProto.getValues = function () {
            var arr = [];
            this.forEach(function (p) {
                arr.push(p.value);
            });
            return arr;
        };

        /**
         * Removes the value with the specified key from the dictionary.
         * @function remove
         * @memberof arrgh.Dictionary
         * @instance
         * @param {*} key - The key of the element to remove.
         * @returns {Boolean} - True if the key was successfully removed and false when the key was not found.
         */
        dictProto.remove = function (key) {
            var hash = this._.eqComparer.getHash(key),
            notFound,
            pair;

            pair = getPairByKey(this, hash, key, function () {
                notFound = true;
            });
            if (notFound) {
                return false;
            }

            var keys = this._.keys[hash];
            keys.remove(pair);
            this._.entries.remove(pair);
            if (!keys.any()) {
                delete this._.keys[hash];
            }
            this.length -= 1;
            return true;
        };

        /**
         * Sets the item at the specified key.
         * @function set
         * @memberof arrgh.Dictionary
         * @instance
         * @param {*} key - The key of the element to overwrite.
         * @param {*} value - The value to set.
         * @returns {*} - Returns the element with the specified key.
         * @throws Throws an error when the key is not present in the dictionary.
         */
        dictProto.set = function (key, value) {
            var hash = this._.eqComparer.getHash(key);
            getPairByKey(this, hash, key, function () {
                throw new Error("Key [" + key + "] was not found in the dictionary.");
            }).value = value;
        };

        /**
         * Removes the value with the specified key from the dictionary.
         * @function tryGet
         * @memberof arrgh.Dictionary
         * @instance
         * @param {*} key - The key at which the item should be retrieved.
         * @returns {tryResult} - A result specifying whether the key was found and, if yes, also contains the value for the key.
         */
        dictProto.tryGet = function (key) {
            var hash = this._.eqComparer.getHash(key),
            notFound,
            pair = getPairByKey(this, hash, key, function () {
                notFound = true;
            });
            if (notFound) {
                return {
                    success: false,
                    value: undefined
                };
            }
            return {
                success: true,
                value: pair.value
            };
        };

        dictProto.count = function (predicate) {
            if (!predicate) {
                return this.length;
            } else {
                return Enumerable.prototype.count.call(this, predicate);
            }
        };

        return {
            Enumerable: Enumerable,
            Dictionary: Dictionary,
            Iterator: Iterator,
            List: List
        };
    }(undefined, Number.MAX_SAFE_INTEGER || 9007199254740991));
}));