Created
January 13, 2016 11:39
-
-
Save bouzuya/5962a5fa094fdbefcf05 to your computer and use it in GitHub Desktop.
RxJS 4 Observable.prototype.pairwise 的な関数を RxJS 5 で
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import assert from 'power-assert'; | |
import { Observable } from 'rxjs'; | |
import pairwise from '../src/pairwise'; | |
describe('pairwise', function() { | |
context('when []', function() { | |
it('works', function() { | |
const source = Observable.fromArray([]); | |
pairwise(source) | |
.toArray() | |
.subscribe(array => { | |
assert(array.length === 0); | |
}); | |
}); | |
}); | |
context('when [1]', function() { | |
it('works', function() { | |
const source = Observable.fromArray([1]); | |
pairwise(source) | |
.toArray() | |
.subscribe(array => { | |
assert(array.length === 0); | |
}); | |
}); | |
}); | |
context('when [1, 2, 3, 4]', function() { | |
it('works', function() { | |
const source = Observable.fromArray([1, 2, 3, 4]); | |
pairwise(source) | |
.toArray() | |
.subscribe(array => { | |
assert(array.length === 3); | |
const [i1, i2, i3] = array; | |
assert.deepEqual(i1, [1, 2]); | |
assert.deepEqual(i2, [2, 3]); | |
assert.deepEqual(i3, [3, 4]); | |
}); | |
}); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Observable } from 'rxjs'; | |
export default function pairwise<T>( | |
observable: Observable<T> | |
): Observable<[T, T]> { | |
return observable | |
.scan<{ hp: boolean; p: T; pair: [T, T] }>(({ hp, p }, x) => { | |
return { hp: true, p: x, pair: (hp ? [p, x] : null) }; | |
}, { hp: false, p: null, pair: null }) | |
.map(({ pair }) => pair) | |
.filter(pair => pair !== null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/Reactive-Extensions/RxJS/blob/v4.0.7/doc/api/core/operators/pairwise.md
https://github.com/bouzuya/rxjs-operator-examples/tree/bbc49fc2d9c43c3279960de78f114f59270359dc