Created
March 28, 2013 23:58
-
-
Save jeffchao/5267801 to your computer and use it in GitHub Desktop.
Implementation of Array.prototype.map() in Javascript
This file contains 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
// Run using jasmine-node. | |
// e.g.: jasmine-node file_name.spec.js | |
Array.prototype.mymap = function (callback) { | |
var obj = Object(this); | |
if (obj.length === 0) return null; | |
if (typeof(callback) === 'undefined') return null; | |
for (var i = 0, o; o = obj[i]; i++) { | |
obj[i] = callback(o); | |
} | |
return obj; | |
}; | |
describe('An Array', function () { | |
describe('mymap', function () { | |
var arr; | |
beforeEach(function () { | |
arr = [1, 2, 3, 4, 5]; | |
}); | |
it('should return null if no arguments are used', function () { | |
expect(arr.mymap()).toBe(null); | |
}); | |
it('should return itself if the block does nothing', function () { | |
expect(arr.mymap(function (a) { return a })).toEqual([1, 2, 3, 4, 5]); | |
}); | |
it('should return +1 to each element', function () { | |
expect(arr.mymap(function (a) { return a + 1 })).toEqual([2, 3, 4, 5, 6]); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I think in line 5 you should use:
var obj = new this.constructor[Symbol.species](...this);
Since in the original implementation, if some class extends Array and sets [Symbol.species] getter to return something else, Array.map should create a mapped array using the supplies constructor