Skip to content

Commit

Permalink
Merge branch 'pr/28'
Browse files Browse the repository at this point in the history
  • Loading branch information
kolodny committed Jun 22, 2015
2 parents 933a46c + 4d66cee commit a6c328c
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 0 deletions.
18 changes: 18 additions & 0 deletions map/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
You might know about [map](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method, let's implement your own `map` one and name it, say `_map`.

`_map` should function like `map` does:

```js
require('./')() // <- this is the file you make;

var numbers = [1, 2, 3];

var doubles = numbers._map(function(number) {
return number * 2;
});

console.log(doubles); // [1, 4, 6]

```

More info: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
6 changes: 6 additions & 0 deletions map/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"private": true,
"scripts": {
"test": "node ../node_modules/mocha/bin/mocha"
}
}
83 changes: 83 additions & 0 deletions map/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
var assert = require('assert');

var NativeMap = Array.prototype.map;
var calledNativeMap;
Array.prototype.map = function() {
calledNativeMap = true;
return NativeMap.apply(this, arguments);
}

var map = require('./');



describe('map', function() {

it('should not use the native map', function() {
calledNativeMap = false;
['x'].map(function(x) { return x; });
assert(!calledNativeMap);
});

it('should return another array', function() {
var arr = [1, 2, 3];
var mapped = map(arr, function() {});

assert.notEqual(arr, mapped);
});

it('should return the right results', function() {
var arr = [1, 2, 3];
var mapped = map(arr, function(value) {
return value * 2;
});

assert.deepEqual(mapped, [2, 4, 6]);
});

it('callback will be called once for each element', function() {
var called = 0;
var arr = [1, 2, 3];

map(function(value) {
called++;
return value;
});

assert.equal(called, 3);
});

it('callback will be invoked with three arguments', function() {
var args;
var arr = [1];

map(arr, function() {
args = arguments.length;
});

assert.equal(args, 3);
});

it("callback's arguments (value, index, array) should have right values", function() {
var i = 0;
var arr = [1, 2, 3];

map(arr, function(value, index, array) {
assert.equal(value, arr[i]);
assert.equal(index, i);
assert.deepEqual(arr, array);
i++;
});
});

it('callback should gets called with context', function() {
var ctx;
var arr = [5];

map(arr, function() {
ctx = this;
}, 3);

assert.equal(ctx, 3);
});
});

0 comments on commit a6c328c

Please sign in to comment.