paldepind / flyd

The minimalistic but powerful, modular, functional reactive programming library in JavaScript.
MIT License
1.56k stars 84 forks source link

Switch Latest without Ramda Dependency #230

Closed NoelAbrahams closed 7 months ago

NoelAbrahams commented 7 months ago

Hi

Is there a simple way to replace ramda/drop in the following without breaking anything?

var flyd = require('../../lib');
var takeUntil = require('../takeuntil');
var drop = require('ramda/src/drop');

var dropCurrentValue = flyd.transduce(drop(1));

module.exports = function(s) {
  return flyd.combine(function(stream$, self) {
    var value$ = stream$();
    flyd.on(self, takeUntil(value$, dropCurrentValue(stream$)));
  }, [s]);
};

This is the only module that I've run into so far with an external dependency, which I'd like to avoid if possible. Any help would be much appreciated. Thanks

nordfjord commented 7 months ago

Should be possible to implement it as

function dropCurrentValue(s) {
  var dropped = false
  return flyd.combine(function(stream$, self) {
    if (!dropped) {
      dropped = true
      return
    }
    self(stream$.val)
  }, [s])
}
NoelAbrahams commented 7 months ago

Ah, thanks @nordfjord. You have literally saved me 100 LOC after my attempt to rework this!

I've also tried to convert this to switchMap:

flyd.switchMap = projector => stream => switchLatest(flyd.map(projector, stream));

For usage in pipe, like this:

const stream = flyd.stream<number>();
stream.pipe(
    flyd.switchMap(value => flyd.stream(value * 10)))
    .map(value => {
        console.error(value); // '10'
    });

stream(1);

I'm about 90% sure that's not the way to define switchMap?!

nordfjord commented 7 months ago

Did you write a small suite of tests to ensure it does what you want it to? 😜

NoelAbrahams commented 7 months ago

Haha. Test cases are for losers.

But actually you do me an injustice. It's quite well tested. It's currently doing what I want it to do. But I have concerns that it won't conform to how the other modules are defined. I'm using it in pipe as above, but I also notice that some modules allow the stream to be passed in. TBH the modules don't really seem to be very consistent.

nordfjord commented 7 months ago

FWIW I think that’s a fine implementation of switchMap, simple composition goes a long way.

as for the consistency of modules, yes, agreed

NoelAbrahams commented 7 months ago

Thanks for the sanity check @nordfjord. Appreciate your help with this.