diff --git a/.gitignore b/.gitignore index 48a2e24..aa6fd7c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ components build +node_modules \ No newline at end of file diff --git a/Makefile b/Makefile index 0f14dac..71e373c 100644 --- a/Makefile +++ b/Makefile @@ -6,6 +6,11 @@ components: component.json @component install --dev clean: - rm -fr build components template.js + rm -fr build components -.PHONY: clean +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec + +.PHONY: clean test diff --git a/component.json b/component.json index 2c61db3..ae371d8 100644 --- a/component.json +++ b/component.json @@ -1,8 +1,8 @@ { "name": "reduce", "repo": "redventures/reduce", - "description": "array reduce", - "version": "0.0.0", + "description": "Array reduce component", + "version": "0.0.1", "keywords": ["array", "reduce"], "dependencies": {}, "development": {}, diff --git a/index.js b/index.js index 28a7104..26deede 100644 --- a/index.js +++ b/index.js @@ -9,15 +9,15 @@ * TODO: combatible error handling? */ -module.exports = function(arr, fn, initial){ +module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial - : arr[0]; + : arr[idx++]; - while (++idx < len) { - curr = fn.call(null, curr, arr[idx], idx, arr); + while (idx < len) { + curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; diff --git a/package.json b/package.json new file mode 100644 index 0000000..4c9716e --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "reduce", + "description": "Array reduce component", + "version": "0.0.1", + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "component": { + "scripts": { + "reduce": "index.js" + } + } +} \ No newline at end of file diff --git a/test/reduce.js b/test/reduce.js new file mode 100644 index 0000000..d44af28 --- /dev/null +++ b/test/reduce.js @@ -0,0 +1,49 @@ + +var reduce = require('..'); + +describe('reduce', function(){ + + describe('when adding prev and current', function(){ + it('should be sum all the values', function(){ + var numbers = [2,2,2]; + var fn = function(prev, curr){ + return prev + curr; + }; + + var a = numbers.reduce(fn); + var b = reduce(numbers, fn); + + a.should.equal(6); + b.should.equal(a); + }); + }); + + describe('when passing in an initial value', function(){ + it('should default to it', function(){ + var items = []; + var fn = function(prev){ + return prev; + }; + + var a = items.reduce(fn, 'foo'); + var b = reduce(items, fn, 'foo'); + + a.should.equal('foo'); + b.should.equal(a); + }); + + it('should start with it', function(){ + var items = [10, 10]; + var fn = function(prev, curr){ + return prev + curr; + }; + + var a = items.reduce(fn, 10); + var b = reduce(items, fn, 10); + + a.should.equal(30); + b.should.equal(a); + }); + }); + +}); \ No newline at end of file