Skip to content

Instantly share code, notes, and snippets.

@viciouslabs
Last active November 22, 2017 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viciouslabs/90daa9dc917ad00cbc8461e1ada526da to your computer and use it in GitHub Desktop.
Save viciouslabs/90daa9dc917ad00cbc8461e1ada526da to your computer and use it in GitHub Desktop.
Play around with RxJS: http://jsbin.com/xumejor/edit?js
/**
* Solving the problem:
* In a circular race of 1200 m length, A and B start with speeds of 18kmph and 27 kmph starting
* at the same time from the same point. When will they meet for the first time at the starting
* point when running in the same direction?
*/
// converts kmph to mps
function convertToMetersPerSecond(speedInKmph) {
return (1000/3600) * speedInKmph
}
// calculates distance
function getDistanceConvered(time, speed) {
return time * speed
}
// returnss position on track relative to the start point
function findRelativePositionOnTrack(distance, trackLength) {
return distance % trackLength
}
// prints distance observations of the runners
function areRunnersAtSamePosition(relativeDistanceA, relativeDistanceB) {
if (relativeDistanceA === relativeDistanceB) {
console.log(`Runners are at the same point in ${timeLapsed} seconds.`)
return true
} else {
console.log(`The two runners are at ${relativeDistanceA}m & ${relativeDistanceB}m in ${timeLapsed} seconds.`)
return false
}
}
// speeds in kmph
const speedA = convertToMetersPerSecond(18)
const speedB = convertToMetersPerSecond(27)
// length in m
const trackLength = 1200
// time lapsed in seconds
let timeLapsed = 0
/**
* Creates an observer that emulates the running of a runner.
* Emits the distance covered by the runner every second.
* The emulator scales the time. 10 milliseconds = 1 sec.
*/
const createRunner = speed => Rx.Observable.timer(0, 10)
.map(secondsLapsed => getDistanceConvered(secondsLapsed + 1, speed))
.map(distance => findRelativePositionOnTrack(distance, trackLength))
const runnerA = createRunner(speedA)
const runnerB = createRunner(speedB)
const runnerObserver = runnerB.withLatestFrom(runnerA)
const runnerSubscription = runnerObserver.subscribe(distances => {
timeLapsed++
const [relativeDistanceB, relativeDistanceA] = distances
if (areRunnersAtSamePosition(relativeDistanceA, relativeDistanceB)) {
runnerSubscription.unsubscribe()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment