-
-
Save ycmjason/158ab0ea105852a4934c6967aec424f1 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
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