6 kyu

Array#reduce

4,238 of 4,412user578387

Description:

In this kata, you must define the Array.reduce method.

I have disabled the pre-existing reduce methods.

Here's how it works:

[1,2,3].reduce( function(sum, next){return sum+next}, 0) 
// => 6

['a','b','a'].reduce( function(obj, elem){if(!obj[elem]) obj[elem] = 0; obj[elem] += 1; return obj}, {})
// => {'a':2, 'b':1}
[1,2,3].reduce( ->(x,y){x+y}, 0) 
# => 6
[1 2 3].reduce((sum, next) -> sum + next , 0)
# => 6

["a" "b" "a" ].reduce ((obj, elem) ->
  obj[elem] = 0  unless obj[elem]
  obj[elem] += 1
  obj), {}
# => {'a':2, 'b':1}

Summary: The reduce method goes through each element of an array, applies the function to whatever the function returned last, and returns the last outcome. On the first iteration, it should pass the initial value to the function, as well as the first element of the array. If no initial value is passed, skip to the first element of the array.

Ruby methods should expect a lambda.

Functional Programming
Algorithms

Stats:

CreatedSep 11, 2014
PublishedSep 11, 2014
Warriors Trained6714
Total Skips503
Total Code Submissions41386
Total Times Completed4412
JavaScript Completions4238
CoffeeScript Completions28
Ruby Completions184
Total Stars68
% of votes with a positive feedback rating85% of 245
Total "Very Satisfied" Votes186
Total "Somewhat Satisfied" Votes45
Total "Not Satisfied" Votes14
Ad
Contributors
  • user578387 Avatar
  • xcthulhu Avatar
  • rsalgado Avatar
Ad