Skip to content

Commit

Permalink
add stringtoFunction
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Sep 19, 2012
1 parent ae78847 commit e9a0fb5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
20 changes: 19 additions & 1 deletion index.js
@@ -1,8 +1,26 @@

module.exports = function(arr, fn){
var ret = [];
fn = toFunction(fn);
for (var i = 0; i < arr.length; ++i) {
ret.push(fn(arr[i], i));
}
return ret;
};
};

function toFunction(obj) {
switch (typeof obj) {
case 'function':
return obj;
case 'string':
return stringToFunction(obj);
default:
throw new TypeError('invalid callback "' + obj + '"');
}
}

function stringToFunction(str) {
return function(obj){
return obj[str];
}
}
10 changes: 10 additions & 0 deletions test/index.js
@@ -1,6 +1,10 @@

var map = require('..');

var loki = { name: 'loki', age: 1 };
var tobi = { name: 'tobi', age: 2 };
var jane = { name: 'jane', age: 8 };

describe('map(arr, fn)', function(){
it('should map values', function(){
var arr = [1,2,3];
Expand All @@ -13,4 +17,10 @@ describe('map(arr, fn)', function(){
arr = map(arr, function(n, i){ return i });
arr.should.eql([0, 1, 2]);
})

it('should support property strings', function(){
var users = [tobi, loki, jane];
var arr = map(users, 'name');
arr.should.eql(['tobi', 'loki', 'jane']);
})
})

0 comments on commit e9a0fb5

Please sign in to comment.