paldepind / flyd

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

Sum Example: Validating Stream Values #113

Closed thurt closed 8 years ago

thurt commented 8 years ago

Hello, I just started looking at flyd so I would like to know suggestions for how to validate stream values before allowing side-effects.

For the Sum example, I was submitting values to the x and y streams through the console and noticed it wasn't validating input; inputting x('boo'), for instance, would still result in updating DOM.

I modified Sum so that it validates values before updating DOM.

      var valid_x = flyd.combine(function(x) {
        if (typeof x() === 'number') {
          return x()
        }
        else {
          console.log('Numbers only, please!');
        }
      }, [x])
      var valid_y = flyd.combine(function(y) {
        if (typeof y() === 'number') {
          return y()
        }
        else {
          console.log('Numbers only, please!');
        }
      }, [y])
      var sum = flyd.combine(function(x, y) {
          return valid_x() + valid_y();
      }, [valid_x, valid_y]);
      flyd.map(function(sum) {
        sumBox.innerHTML = sum;
      }, sum);
      flyd.map(function(valid_x) {
        xBox.innerHTML = valid_x;
      }, valid_x);
      flyd.map(function(valid_y) {
        yBox.innerHTML = valid_y;
      }, valid_y);

Would this be a typical strategy to validate values? Are there other ways? Thanks

c-dante commented 8 years ago

Handling errors and validation within a stream were discussed here: #20 , #103 , #35 , and #69, and a pull request with a possible implementation (by build Either into flyd): #104

TL;DR, seems flyd is not concerned with errors -- the way you're dealing with them here is a fine solution, and tons of other options exist (the Either monad is an example from the PR).

I don't think that the examples need to be updated for this, but an example demonstrating some error handling strategies wouldn't be a bad idea.

thurt commented 8 years ago

Thanks @c-dante I will look over the links.

an example demonstrating some error handling strategies wouldn't be a bad idea.

:+1: I think that would be a "nice to have" since validating user input can be a significant part of certain projects.

thurt commented 8 years ago

Closing this issue. @c-dante has provided a good summary on discussions surrounding how to validate/error check while using flyd streams.