Skip to content

Commit 67406a4

Browse files
author
James Halliday
committed
readme, example, and failing test
0 parents  commit 67406a4

File tree

4 files changed

+76
-0
lines changed

4 files changed

+76
-0
lines changed

Diff for: example/sum.js

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
var reduce = require('../');
2+
var xs = [ 1, 2, 3, 4 ];
3+
var sum = reduce(xs, function (acc, x) { return acc + x }, 0);
4+
console.log(sum);

Diff for: index.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module.exports = function (xs, f, acc) {
2+
if (xs.reduce) return xs.reduce(f, acc);
3+
for (var i = 0; i < xs.length; i++) {
4+
if (!hasOwn.call(xs, i)) continue;
5+
acc = f(acc, xs[i], i);
6+
}
7+
return acc;
8+
};
9+
10+
var hasOwn = Object.prototype.hasOwnProperty;

Diff for: readme.markdown

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# array-reduce
2+
3+
`[].reduce()` for old browsers
4+
5+
# example
6+
7+
```
8+
var reduce = require('array-reduce');
9+
var xs = [ 1, 2, 3, 4 ];
10+
var sum = reduce(xs, function (acc, x) { return acc + x }, 0);
11+
console.log(sum);
12+
```
13+
14+
output:
15+
16+
```
17+
10
18+
```
19+
20+
# methods
21+
22+
``` js
23+
var reduce = require('array-reduce')
24+
```
25+
26+
## var res = reduce(xs, f, init)
27+
28+
Create a result `res` by folding `acc = f(acc, xs[i], i)` over each element in
29+
the array `xs` at element `i`. If `init` is given, the first `acc` value is
30+
`init`, otherwise `xs[0]` is used.
31+
32+
# install
33+
34+
With [npm](https://npmjs.org) do:
35+
36+
```
37+
npm install array-reduce
38+
```
39+
40+
# license
41+
42+
MIT

Diff for: test/reduce.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
var reduce = require('../');
2+
var test = require('tape');
3+
4+
test('numeric reduces', function (t) {
5+
t.plan(3);
6+
7+
var xs = [ 1, 2, 3, 4 ];
8+
t.equal(
9+
reduce(xs, function (acc, x) { return acc + x }, 0),
10+
10
11+
);
12+
t.equal(
13+
reduce(xs, function (acc, x) { return acc + x }, 100),
14+
110
15+
);
16+
t.equal(
17+
reduce(xs, function (acc, x) { return acc + x }),
18+
10
19+
);
20+
});

0 commit comments

Comments
 (0)