coding, javascript

Map Reduce is fun and practical in JavaScript

I’ll be honest, i’ve never used map..reduce in javascript. I wrote it in java and ruby (so far). So i had to try and i had an challenge in front of me that i needed to complete.

I turned to Mozilla for their wonderful JavaScript documentation.

This is an implementation of <array>.map

if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = new Array(len);
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      // NOTE: Absolute correctness would demand Object.defineProperty
      //       be used.  But this method is fairly new, and failure is
      //       possible only if Object.prototype or Array.prototype
      //       has a property |i| (very unlikely), so use a less-correct
      //       but more portable alternative.
      if (i in t)
        res[i] = fun.call(thisArg, t[i], i, t);
    }

    return res;
  };
}

Now the fun part, how do i FILTER data, then map, then reduce and get the result back.

 

Challenge:

1. A bunch of data with object such as this:  ({name: “it”, salary: 100} )

2. Filter data by name “it”

3. Provide a total sum of all salaries for that name

 

Clearly this can be achieved in an simple data.forEach(function(item….)  but with map reduce + filter its a lot more elegant , though probably not as fast.

Here is my solution (after i sat down and refactored what i wrote during the challenge earlier )

 

var data = []

while( data.length < 100) {
   data.push({name: "it", salary: 33*data.length});
}
data.push({name: "accounting", salary: 100});

data.push({name: "acc", salary: 100});
var sum = data.filter(function(val){
	return val.name == "it"
})
.map(function(curr){
	return curr.salary;
})
.reduce(function(prev, curr){
	return prev +curr;
})

console.log(sum);

I generated a bunch of data and it prints the sum of all salaries for a name “it”.

For some reason, i thought that map and reduce would executed in parallel and would have a callback but that just means how heavily i am into NodeJS . On the next post, ill share how i truly write async code an how sorting, filtering, map/reduce can be achieved with callbacks.

 

Thanks and happy coding.

 

 

Share This:

coding, ruby

Ruby interview challenge

I had a pleasure of getting an interview with an upcoming startup (i won’t disclose which one). Besides implementing fizz buzz in ruby, i was asked to write a method that would check for input to be a palindrome.

Palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or backward.

Keep in mind: using reverse is not allowed 🙂

I wrote two versions since i wasn’t pleased with my first one.

 

Rspec – testing driven development

require 'spec_helper'
require 'blah'

describe "Blah" do 

	it "should match reversed order of the word " do
		palindrome("abba").should == true
		palindrome("abcba").should == true
	end
	it "should reject if reversed order doesnt match" do 
		palindrome("abbac").should_not == true
	end

	it "should handle empty string with passing" do 
		palindrome("").should == true
	end

	it "should handle various cases " do
		palindrome("AbbA").should == true
	end

	it "should handle empty spaces " do
		palindrome("   Ab  bA").should == true
	end
end

 

Version 1

def palindrome2(word)

i = 0
last = -1
word.each_char do |c|
	if word[i] != word[last]
		return false
	end
	i+=1
	last -=1
end

return true

end

 

Version 2

def palindrome(word)
	word = word.downcase.gsub(" ","").chars 
	word.each{|c| return false if  word.shift != word.pop  }
	true
end

I have a feeling there is a better way of writing this.

Thanks

Share This: