Skip to content

Instantly share code, notes, and snippets.

@hekystyle
Last active November 12, 2023 18:46
Show Gist options
  • Select an option

  • Save hekystyle/c5d33d344a6c919eed993f2328c4565b to your computer and use it in GitHub Desktop.

Select an option

Save hekystyle/c5d33d344a6c919eed993f2328c4565b to your computer and use it in GitHub Desktop.
Solution of parallel search for fastest horse from Google interview.
export interface Speedy {
speed: number;
}
export class FastestItemsFinder {
constructor(
private readonly config = {
workersCount: 5,
fastestCount: 3,
},
) {}
private fastestItems: Speedy[] = [];
async test(items: readonly Speedy[]): Promise<Speedy[]> {
this.fastestItems = [];
const queue = [...items];
const workers = Array.from({ length: this.config.workersCount }, (_, index) => this.worker(queue, index));
await Promise.all(workers);
return this.fastestItems;
}
private async worker(queue: Speedy[], index: number) {
console.log(`Worker ${index + 1} started`);
while (queue.length) {
const item = queue.shift();
console.log(`Worker ${index + 1} is testing item ${item?.speed}`);
if (item) this.testAgainstFastest(item);
// for demonstration purposes only
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log(`Worker ${index + 1} finished`);
}
private testAgainstFastest(item: Speedy) {
const { fastestCount } = this.config;
for (let i = 0; i < fastestCount; i++) {
const fastestItem = this.fastestItems[i];
if (!fastestItem || item.speed > fastestItem.speed) {
this.fastestItems.splice(i, 0, item);
this.fastestItems = this.fastestItems.slice(0, fastestCount);
break;
}
}
}
}
new FastestItemsFinder()
.test([
{ speed: 8 },
{ speed: 1 },
{ speed: 3 },
{ speed: 4 },
{ speed: 9 },
{ speed: 5 },
{ speed: 2 },
{ speed: 10 },
{ speed: 7 },
{ speed: 6 },
])
.then(fastestHorses => {
fastestHorses.forEach((horse, index) => {
console.log(`Fastest ${index + 1}. horse has speed ${horse.speed}`);
});
console.log('Done!');
})
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment