From da46c6340e61bb28cbf2c7854cf6c0eb59da5055 Mon Sep 17 00:00:00 2001 From: Alvis HT Tang Date: Thu, 1 Mar 2018 11:56:00 +0000 Subject: [PATCH 1/2] feat: provide isNil(x) for checking if x is the end of stream marker This provides a very simple, and yet essential, function for type checking, as _.nil is not a primitive variable but an object. This function is particularly useful in a consume handler which has a signature of `consume(f: (err: Error, x: R | Highland.Nil, push: (err: Error | null, value?: U | Highland.Nil) => void, next: () => void) => void): Stream`. Only with this function and an updated typescript or flow definition, x can be distinguished between R and Highland.Nil. Example: ``` source.consume(function (err, x, push, next) { if (err) { // pass errors along the stream and consume next value push(err); next(); } else if (_.isNil(x)) { // type guard is only possible with this function // pass nil (end event) along the stream push(null, x); } else { // pass on the value only if the value passes the predicate if (f(x)) { push(null, x); } next(); } }); ``` --- lib/index.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/index.js b/lib/index.js index f06c7f8..9c05665 100755 --- a/lib/index.js +++ b/lib/index.js @@ -917,6 +917,20 @@ function StreamRedirect(to) { this.to = to; } +/** + * Returns true if `x` is the end of stream marker. + * + * @id isNil + * @section Streams + * @name _.isNil(x) + * @param x - the object to test + * @api public + */ + +_.isNil = function (x) { + return x === _.nil; +}; + /** * Returns true if `x` is a Highland Stream. * From ae3ec9c744230adeec56a9c4db5bc08edebac1c8 Mon Sep 17 00:00:00 2001 From: Alvis HT Tang Date: Tue, 13 Mar 2018 09:58:28 +0000 Subject: [PATCH 2/2] test: add a test for isNil() --- test/test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/test.js b/test/test.js index 1e0c3a7..9ebf8a6 100755 --- a/test/test.js +++ b/test/test.js @@ -324,6 +324,19 @@ exports.seq = function (test) { test.done(); }; +exports.isNilTest = function (test) { + test.ok(_.isNil(_.nil)); + test.ok(!_.isNil()); + test.ok(!_.isNil(undefined)); + test.ok(!_.isNil(null)); + test.ok(!_.isNil(123)); + test.ok(!_.isNil({})); + test.ok(!_.isNil([])); + test.ok(!_.isNil('foo')); + test.ok(!_.isNil(_())); + test.done(); +}; + exports.isStream = function (test) { test.ok(!_.isStream()); test.ok(!_.isStream(undefined));