diff --git a/src/first.js b/src/first.js new file mode 100644 index 0000000..1eb54b3 --- /dev/null +++ b/src/first.js @@ -0,0 +1,18 @@ +/** + * Returns the first element to be returned by an Observable + * + * @param {Observable} input Input Observable + * @return {Observable} New Observable + */ + +const first = input => { + let out; + input.subscribe(x => { + if (!out) out = x; + }); + return out; +}; + +first._name = 'first'; + +export default first; diff --git a/src/index.js b/src/index.js index 7aaaa2d..f50ab43 100644 --- a/src/index.js +++ b/src/index.js @@ -8,6 +8,7 @@ import defer from './defer'; import delay from './delay'; import error from './error'; import filter from './filter'; +import first from './first'; import flatMap from './flatMap'; import forEach from './forEach'; import fromEvent from './fromEvent'; @@ -37,6 +38,7 @@ const addAll = (target = Observable) => { debounce, delay, filter, + first, flatMap, forEach, map, @@ -67,6 +69,7 @@ export { delay, error, filter, + first, flatMap, forEach, fromEvent, diff --git a/test/first.js b/test/first.js new file mode 100644 index 0000000..e456ece --- /dev/null +++ b/test/first.js @@ -0,0 +1,11 @@ +import { expect } from 'chai'; +import first from '../src/first'; +import apiCheck from './common/apiCheck'; + +describe('(First) defer', () => { + apiCheck(first); + + it('emits the first element of an Observable', () => { + expect(first(Observable.of(1, 2, 3))).to.eql(1); + }); +});