Sponsored Link

Sunday, April 6, 2014

map() function in JavaScript, Scala etc

These are absolutely awesome functions. They allow you to apply a function on every element of an array and return a new array with the result of the function.

In theory these are called higher-order functions, i.e they can take one or more function as an argument.

Consider the following JavaScript function:

var array = [1,2,3,4,5];
var twoTimesArray = array.map(function(n) {return n*2;});
console.log(twoTimesArray);

output: [2, 4, 6, 8, 10]

So that just multiplies every element of array by 2 and returns the resulting array.

Without map functions you would have done something like this:

var array = [1,2,3,4,5];
var twoTimesArray = [];
for(var i = 0; i < array.length; i++ ) {
    twoTimesArray[i] = array[i] * 2;
}
console.log(twoTimesArray);

Clearly, that is a lot of code compared to the previous one.

And, if you use Scala, code becomes much more concise.

scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)

scala> l.map(x => x*2)



Imagine doing the same thing in Java. First we will look at Java 6

List<Integer> array = Arrays.asList(1,2,3,4,5);
List<Integer> twoTimesArray = new ArrayList<Integer>();
for(Integer i: array) {
    twoTimesArray.add(i*2);
}



And in Java 8:

List<Integer> array = Arrays.asList(1,2,3,4,5);
List<Integer> twoTimesArray = new ArrayList<Integer>();
array.stream().forEach((string) -> {
    twoTimesArray.add(string*2);
});



The difference between for-each loop and using stream api (collection.stream()) in Java 8 is that we can easily implement parallelism when using the stream api with collection.parallelStream(). Whereas, in for-each loop you will have to handle threads on your own.

Programming becomes fun when we add bit of functional style into OO languages.

Related Posts Plugin for WordPress, Blogger...