Skip to content

Commit 2a9e7e0

Browse files
authored
Merge pull request #1 from maniator/scan-reduce
Create scan and reduce functionality
2 parents 6aab560 + aecdb4c commit 2a9e7e0

File tree

4 files changed

+49
-1
lines changed

4 files changed

+49
-1
lines changed

example/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,3 @@ inputObservable$
3535
inputObservable$
3636
.do((text) => div.textContent = text)
3737
.subscribe();
38-

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ export * from './operators/first';
1515
export * from './operators/toPromise';
1616
export * from './operators/flatMap';
1717
export * from './operators/switchMap';
18+
export * from './operators/scan';
19+
export * from './operators/reduce';
1820

1921
// add on observable types
2022
export * from './observables/fromEvent';

src/operators/reduce.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { Observable } from '../Observable';
2+
import { scan } from './scan';
3+
4+
export const reduce = function (source$, scanCallback, startValue = 0) {
5+
return new Observable(function ({next, error, complete }) {
6+
let lastValue = 0;
7+
const subscription = scan(source$, scanCallback, startValue).subscribe({
8+
next (value) {
9+
lastValue = value;
10+
},
11+
error,
12+
complete () {
13+
next(lastValue);
14+
complete();
15+
}
16+
});
17+
18+
return () => subscription.unsubscribe();
19+
});
20+
};
21+
22+
Observable.prototype.reduce = function (scanCallback, startValue) {
23+
return reduce(this, scanCallback, startValue);
24+
};

src/operators/scan.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { Observable } from '../Observable';
2+
3+
export const scan = function (source$, scanCallback, startValue = 0) {
4+
return new Observable(function ({ next, error, complete }) {
5+
let previousValue = startValue;
6+
7+
const subscription = source$.subscribe({
8+
next (value) {
9+
previousValue = scanCallback(previousValue, value);
10+
11+
next(previousValue);
12+
},
13+
error,
14+
complete
15+
});
16+
17+
return () => subscription.unsubscribe();
18+
});
19+
};
20+
21+
Observable.prototype.scan = function (scanCallback, startValue) {
22+
return scan(this, scanCallback, startValue);
23+
};

0 commit comments

Comments
 (0)