Skip to content

Instantly share code, notes, and snippets.

@bradparker
Created July 1, 2019 00:05
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 bradparker/72257d5e6036d38247c3aab489c4b6aa to your computer and use it in GitHub Desktop.
Save bradparker/72257d5e6036d38247c3aab489c4b6aa to your computer and use it in GitHub Desktop.
JS concurrency _stuff_
interface Person {
name: string;
age: number;
}
const people: Person[] = [{ name: "Bob", age: 100 }, { name: "Jane", age: 50 }];
const findPeople = (candidate: string): Promise<Person[]> => {
return new Promise(resolve => {
const timeout = Math.floor(Math.random() * 100);
setTimeout(() => {
console.log("Finding: ", candidate);
console.log("After: ", timeout);
resolve(people.filter(({ name }) => candidate === name));
}, timeout);
});
};
const fetchPeople = async (
candidates: string[]
): Promise<{ [key: string]: Person[] }> => {
const results: [string, Person[]][] = await Promise.all(
candidates.map(async candidate => {
const found = await findPeople(candidate);
const result: [string, Person[]] = [candidate, found];
return result;
})
);
return results.reduce(
(acc, [name, peeps]) => ({
...acc,
[name]: peeps
}),
{}
);
};
const fetchPeopleTwo = async (
candidates: string[]
): Promise<{ [key: string]: Person[] }> => {
return candidates.reduce(async (acc, candidate) => {
const results = await acc;
const peeps = await findPeople(candidate);
return {
...results,
[candidate]: peeps
};
}, Promise.resolve({}));
};
const time = async (action: () => Promise<void>): Promise<number> => {
const start = Date.now();
await action();
const end = Date.now();
return end - start;
};
const main = async () => {
console.log("Map reduce");
const mapReduceDuration = await time(async () => {
const result = await fetchPeople(["Bob", "Jane"]);
console.log(result);
});
console.log("Took", mapReduceDuration);
console.log("\nReduce");
const reduceDuration = await time(async () => {
const result = await fetchPeopleTwo(["Bob", "Jane"]);
console.log(result);
});
console.log("Took", reduceDuration);
};
// EXAMPLE OUTPUT:
//
// Map reduce
// Finding: Jane
// After: 26
// Finding: Bob
// After: 42
// { Bob: [ { name: 'Bob', age: 100 } ],
// Jane: [ { name: 'Jane', age: 50 } ] }
// Took 49
// Reduce
// Finding: Bob
// After: 39
// Finding: Jane
// After: 2
// { Bob: [ { name: 'Bob', age: 100 } ],
// Jane: [ { name: 'Jane', age: 50 } ] }
// Took 46
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment