diff --git a/index.js b/index.js index 704a2cf..60f4c30 100644 --- a/index.js +++ b/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; -}; \ No newline at end of file +}; + +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]; + } +} \ No newline at end of file diff --git a/test/index.js b/test/index.js index 3e4192a..8bcd8f0 100644 --- a/test/index.js +++ b/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]; @@ -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']); + }) }) \ No newline at end of file