Skip to content

Instantly share code, notes, and snippets.

@jeffchao
Created March 28, 2013 23:58
Show Gist options
  • Save jeffchao/5267801 to your computer and use it in GitHub Desktop.
Save jeffchao/5267801 to your computer and use it in GitHub Desktop.
Implementation of Array.prototype.map() in Javascript
// 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]);
});
});
});
@amithadary
Copy link

amithadary commented Aug 10, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment