Created
January 24, 2023 12:25
-
-
Save WeslyG/8ad8b5775edc5097aecc47be163712f3 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
class Observable { | |
constructor(subscribe) { | |
this.observers = []; | |
if (subscribe) { | |
subscribe(this) | |
} | |
} | |
subscribe(observer) { | |
const index = this.observers.push(observer); | |
const del = () => { | |
this.observers.splice(index -1, 1) | |
} | |
return { | |
...this, | |
unsubscribe() { | |
del() | |
} | |
}; | |
} | |
next(data) { | |
if (this.observers.length === 0) return; | |
for (const observer of this.observers) { | |
observer(data); | |
} | |
} | |
} | |
const randomChar = () => String | |
.fromCharCode(Math.floor((Math.random() * 25) + 97)); | |
// Usage | |
const sourceStream = new Observable(subscriber => { | |
setInterval(() => { | |
const char = randomChar(); | |
subscriber.next(char); | |
}, 200); | |
}); | |
let count = 0; | |
const observer = (char) => { | |
process.stdout.write(`${char}\n`); | |
count++; | |
if (count > 50) { | |
process.stdout.write('\n\n'); | |
process.exit(0); | |
} | |
}; | |
const subscription = sourceStream.subscribe(observer); | |
sourceStream.subscribe(observer) | |
setTimeout(() => { | |
subscription.unsubscribe() | |
}, 1000) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment