Last active
August 29, 2018 21:10
-
-
Save mhoyer/1663ceb84fe3422e4f3035b2d574ca6c to your computer and use it in GitHub Desktop.
Reverse stream processing when merging two streams
This file contains hidden or 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
import { from, zip, timer, Observable } from 'rxjs'; | |
const colors: any = { | |
'red ': 31, | |
'green ': 32, | |
'yellow ': 33, | |
'blue ': 34, | |
'magenta': 35, | |
'cyan ': 36, | |
'white ': 37, | |
}; | |
const colorKeys = Object.keys(colors); | |
const coloredNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(n => ({ | |
col: colorKeys[n % colorKeys.length], | |
num: n, | |
})); | |
const $coloredNumber = delayedFrom(coloredNumbers, 0, 250); | |
const coloredLetters = 'abcdefghij'.split('').map(l => ({ | |
col: colorKeys[l.charCodeAt(0) % colorKeys.length], | |
letter: l, | |
})); | |
const $coloredLetter = delayedFrom(coloredLetters, 70, 300); | |
$coloredNumber.subscribe(_ => console.log(`\x1b[${colors[_.col]}m${_.num} => ${_.col}\x1b[0m`)); | |
$coloredLetter.subscribe(_ => console.log(`\x1b[${colors[_.col]}m ${_.col} <= ${_.letter}\x1b[0m`)); | |
// HELPERS | |
// generates an observable from values of an array with delayed publication between each item | |
function delayedFrom<T>(values: T[], due: number, period: number): Observable<T> { | |
return zip( | |
from(values), | |
timer(due, period), | |
v => v as T | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your task:
$coloredNumberLetter
$coloredNumber
event pops up: stream-process all already happened events on$coloredLetter
streamand find the latest one that matches the same color of current
$coloredNumber
event.$coloredLetter
event pops up: stream-process all already happened events on$coloredNumber
streamand find the latest one that matches the same color of current
$coloredLetter
event.