Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created February 26, 2020 16:26
Show Gist options
  • Save ycmjason/158ab0ea105852a4934c6967aec424f1 to your computer and use it in GitHub Desktop.
Save ycmjason/158ab0ea105852a4934c6967aec424f1 to your computer and use it in GitHub Desktop.
import { reactive, watch } from './reactivity';
// % in Javascript is remainder operator, e.g. -1 % 5 gives -1.
// The following is an implementation for modulus.
const mod = (x: number, y: number) => ((x % y) + y) % y
const MAX_ROAD_LENGTH = 10
const cars = [
reactive({
position: 0,
speed: 2,
}),
reactive({
position: 2,
speed: 1,
}),
]
setInterval(() => {
for (const car of cars) {
car.position = mod(car.position + car.speed, MAX_ROAD_LENGTH)
}
}, 1000)
let callCount = 0;
watch(() => {
const road = [...'_'.repeat(MAX_ROAD_LENGTH)]
for (const car of cars) {
road[car.position] = '🚗'
}
console.clear()
console.log(road.reverse().join(''))
console.log(`callCount: ${++callCount}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment