Hey! Do you want to use the standard JavaScript array algorithms such as map()
, filter()
, and yes, even reduce()
(left and right) in all browsers, not just the modern ones? Do you hate reading licenses to figure out if you can include a library in your project? Do you mistrust all code, including your own, until you've seen it pass an exhaustive suite of tests? Do you like standards? Then boy do I have the library for you!
The idea is simple: implement a compatability layer for all the array algorithms specified in the ECMA-262 5th edition standard: indexOf()
, lastIndexOf()
, every()
, some()
, forEach()
, filter()
, map()
, reduce()
, and reduceRight()
. None of these are implemented in IE6, 7, or 8 so you can't use any of them on the web unless you use a library. MDC provides copy-and-paste examples of these functions, but doesn't provide any unit tests or a deployable library. So, I implemented my own versions, following the standard closely, wrote a full suite of tests, put them all into one convenient, minified .js
file and released it in the public domain (or MIT license, for countries were "public domain" is meaningless.) That means you can it these wherever and however you like, worry-free.
And you should be using them! You see, while each of these algorithms is a convenience by itself, they also work extraordinarily well together. Informally speaking, they form an orthonormal basis for all array algorithms. By chaining map, filter, and reduce calls, you're able to clearly, safely, and correctly manipulate arrays. More importantly, thinking about arrays in this way is very powerful and very easy: even very complex problems can be quickly solved if you have these algorithms and your fingertips.
A programming language serves two related purposes: it provides a vehicle for the programmer to specify actions to be executed, and it provides a set of concepts for the programmer to use when thinking about what can be done. -Bjarne Stroustrup
Now if only JavaScript had equivalent algorithms for associative arrays...
- Oran Looney March 2nd 2011
Thanks for reading. This blog is in "archive" mode and comments and RSS feed are disabled. We appologize for the inconvenience.