DEV Community

loading...

Reactive Sanitization with Javascript

yugely
Middle school education, 15 low grade felonies and live with my parents.
・Updated on ・1 min read

This is a short post going over how reactive design can help you manage data sanitization issues using just javascript. There are no plugins for this, its plain ol' js. The observable class is custom. I've been building out my Stork Client for my project (https://github.com/yugely/Stork).

I wanted to take some time from doing that to just give a quick tutorial on doing some reactive programming with js, as it is a bit of a different concept than other languages and observables. I'm not using rxjs as I'm not dealing with module import problems. So I have to build it on my own. Luckily it's easy.

Code:

//Still valid, I made edits, so the repo is changed as of..
//28 june 2021
class Observable { //custom
    constructor(functionObserved) {
      this._functionObserved = functionObserved
    }
    subscribe(observer) {
      return this._functionObserved(observer)
    }
}
let
 myObservable = new Observable((observer) => {//create observable
    setTimeout(() => {//timeout function
      observer.next(demoArray)//data being passed in, next is custom type
      observer.complete() //complete is custom type
    }, 100)
 })

//make array
var demoArray = [1,2,3,4,5,6,7,8,9,10]

//create sanitize function 
let sanitize = {
    next(demoArray) {//sanitize
        if (demoArray.length < 10) {
            //throw new Error("The array is less than 10")
           throw new Error("The array is less than 10")
        }
    },
  complete: () => {
      //complete if sanitized
        console.log("sanitized")
    }
  }
  myObservable.subscribe(sanitize)//startprocess
Enter fullscreen mode Exit fullscreen mode

It's commented out to explain it. Basically instead of observing a variable change, you observer functions to change data.

Discussion (0)