# Extra functions on Arrays, Maps, etc..

Rick Waldron waldron.rick at gmail.com
Sat Apr 7 16:40:34 PDT 2012

```Hi Adam,

Most of the methods that you listed are either already available in
identical form or the same logic can be created with existing methods, I've
noted each below

On Thu, Apr 5, 2012 at 11:26 AM, Adam Shannon <adam at ashannon.us> wrote:

> Hey all,
>
> Scala has a lot of really handy functions that are on arrays, maps,
> and a whole range of collections. (It's collection support is a lot
> bigger than ES's, anyway..) It would be nice to have these included
> (since we're already including .map, .foreach, etc..).
>
> drop(n) // Drops the first n elements
>

> var a = [1,2,3,4]
undefined
> a.slice( 2 )
[ 3, 4 ]

> dropRight(n) // Drops the last n elements
>

> var a = [1,2,3,4]
undefined
> a.slice( 0, a.length - 2 )
[ 1, 2 ]

> filter(fn) // Returns a sub-collection containing the elements that
> fn(elm) returned true
>

> var a = [1,2,3,4]
undefined
> a.filter(function( val ) { return val % 2 === 0; });
[ 2, 4 ]

> fold(newColl, fn) // Folds the elements of the original collection
> into newColl given the results of fn
>

Similar to reduce?

> var a = [1,2,3,4]
undefined
> a.reduce(function( cur, prev ) { return cur + prev }, 0);
10

> getOrElese // Sugar for (.get === undefined) ? fillerValue : .get
> partition(fn) // Splits the collection into two sub-collections given
> the result of fn(elm) being true or false.
>

These two are easily achieved with library code

> take(n) // Take only the first n elements
>

> var a = [1,2,3,4]
undefined
> a.slice( 0, 2 )
[ 1, 2 ]

> takeRight(n) // Take only the last n elements
>

> var a = [1,2,3,4]
undefined
> a.slice( -2 )
[ 3, 4 ]

> A.zip(B) // Creates a map from the two collections, treating A as the
> keys and B as the values
>

Easily achieved with library code

eg. http://documentcloud.github.com/underscore/#zip

> Of course, there are more than just these that I've listed.
>
> http://www.scala-lang.org/api/current/scala/collection/Map.html
>
> A simple use case for these are all over in ES6.
>
> var arr = document.getElementsByTagName("a");
> var externalElms = arr.filter(function(acc, item) {
> (/^https?:\/\//).test(item.href) });
>
> Or,
>
> var arr = document.querySelector("div")
> var divMap = arr.fold(new Map, function(acc, item) { acc.add(item.id,
> item); });
>

Nit: You'd still need to convert the NodeList into an array before using
any Array methods

Rick

>
> --
> Developer
> University of Northern Iowa
> Sophomore -- Computer Science B.S. & Mathematics
> http://ashannon.us
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120407/f3f1bb0d/attachment.html>
```