Created
March 29, 2013 06:58
-
-
Save jeffchao/5269210 to your computer and use it in GitHub Desktop.
Basic implementation of Array.prototype.inject() in Ruby-like method in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.myinject = function () { | |
var obj = Object(this); | |
var base; | |
var callback; | |
if (arguments.length === 2) { | |
base = arguments[0]; | |
callback = arguments[1]; | |
} else if (arguments.length === 1) { | |
callback = arguments[0]; | |
} else { | |
return null; | |
} | |
if (typeof(callback) === 'undefined') return null; | |
if (obj.length === 0) return null; | |
switch (typeof(obj[0])) { | |
case 'number': | |
base = 0; | |
break; | |
case 'string': | |
base = ''; | |
break; | |
default: | |
return null; | |
} | |
for (var i = 0, o; o = obj[i]; i++) { | |
base = callback(base, o); | |
} | |
return base; | |
}; | |
describe('an Array', function () { | |
describe('#myinject', function () { | |
var arr; | |
var arr2; | |
beforeEach(function () { | |
arr = [1, 2, 3, 4, 5]; | |
arr2 = ['a', 'b', 'c']; | |
}); | |
it('should return nil if no block exists', function () { | |
expect(arr.myinject()).toBe(null); | |
}); | |
it('should return return 15 for accumulator + element', function () { | |
expect(arr.myinject(0, function (acc, e) { return acc + e })).toBe(15); | |
expect(arr.myinject(function (acc, e) { return acc + e })).toBe(15); | |
}); | |
it('should return aabaca for accumulator + element + a', function () { | |
expect(arr2.myinject('', function (acc, e) { return acc + e + 'a' })).toBe('aabaca'); | |
expect(arr2.myinject(function (acc, e) { return acc + e + 'a' })).toBe('aabaca'); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment