Following my previous post on streams, one can wonder what are streams fundamentaly ?
At the most basic, a stream is nothing more than an object that can be observed, they are in fact obervables.
Many objects can be observed, the particularity of streams is that they are composable observables.
Let's see if we can implement a very simple observable.
Our requirements are:
- use only function (no classes, no proxies...)
- passed value must be stored
- invocation must return the stored value
- no globals
How can a function can store a value?, that seems a little strange. A stream seems not to be a basic function...
The following function does not store anything.
When you invoke it without argument, it simply returns nothing.
function stream (value) {
let storedvalue = value
return storedvalue
}
What can we do then? We will use a particular feature of Javascript called closure.
Using closures is simple, the explanation on how they works internally is beyond my knowledege.
So here it is :
function Stream (value) {
let storedvalue = value
function stream (newvalue) {
if (arguments.length) {
storedvalue = newvalue
}
return storedvalue
}
return stream
}
let s = Stream(5)
console.log(s())
You can test it here stream
In Javascript, functions are first class citizens. They are treated like any other objects.
They can be passed as arguments to other functions, they can be returned from functions.
Closures allow returned functions to 'capture' a variable defined outer it, magic :-)
This function fullfill our requirements, in the next post, we will see how to "react" whenever a stream is "feeded" by a new value...
Thanks for reading
Top comments (0)