Created
December 28, 2020 15:24
-
-
Save nirkaufman/589ccea7ab93c8ed98c5e784147e36e9 to your computer and use it in GitHub Desktop.
Adventures in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ******************************* | |
// Just a wrapper around callbacks, | |
// So we can use the same API - and state of mind | |
// ******************************* | |
// helper to create observable | |
function createObservable(subscribe) { | |
return { | |
subscribe, | |
pipe: function (operator) { | |
return operator(this) | |
} | |
} | |
} | |
// functions to manipulate observable values | |
function map(mapFn) { | |
return function (inputCollection) { | |
return createObservable(function(callbacks){ | |
inputCollection.subscribe({ | |
next: (data) => callbacks.next(mapFn(data)), | |
complete: callbacks.complete | |
}) | |
}) | |
} | |
} | |
function filter(filterFn) { | |
return function (inputCollection) { | |
return createObservable(function (callbacks) { | |
inputCollection.subscribe({ | |
next: v => filterFn(v) && callbacks.next(v), | |
complete: callbacks.complete | |
}) | |
}) | |
} | |
} | |
// helpers to wrap callbacks with observable | |
function fromArray(array) { | |
return createObservable(function(callbacks){ | |
for(let item of array) { | |
callbacks.next(item) | |
} | |
callbacks.complete() | |
}) | |
} | |
function fromEvent(domElement, eventName) { | |
return createObservable(function(callbacks){ | |
domElement.addEventListener(eventName, callbacks.onData) | |
}) | |
} | |
function fromPromise(promise) { | |
return createObservable(function(callbacks){ | |
promise | |
.then(callback.onData, callbacks.onerror) | |
.finally(callbacks.onDone) | |
}) | |
} | |
// ******************************* | |
// Runtime | |
// ******************************* | |
const nums = fromArray([1,2,3,4,5]) | |
// create from a DOM event | |
const button = document.createElement('button'); | |
const clicks = fromEvent(button, 'click') | |
const data = fromPromise(fetch('//')); | |
// suite of functions that observe state | |
const observer = { | |
next: function (v) { | |
console.log(v); | |
}, | |
error: function (e){ | |
console.log(e); | |
}, | |
complete: function () { | |
console.log("done"); | |
} | |
} | |
nums | |
.pipe(map(v => v* 10)) | |
.pipe(filter(v => v * 25)) | |
.subscribe(observer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment