Skip to content

Instantly share code, notes, and snippets.

@Sara3
Last active July 24, 2021 19:14
Show Gist options
  • Save Sara3/4ffb78773f9b2e765fc10bf5fd7ea9b8 to your computer and use it in GitHub Desktop.
Save Sara3/4ffb78773f9b2e765fc10bf5fd7ea9b8 to your computer and use it in GitHub Desktop.
question
Fetcher interface:
fetchAnimals(prefix: string, callback: function): void
fetchArticles(prefix: string, callback: function): void
fetchFruits(prefix: string, callback: function): void
Note: there are many more fetchers
Callback interface:
callback(results: string[]): void
*/
fetchAnimals('g', (results) => console.log(results));
// Might eventually print: ['gorilla', 'giraffe']
fetchFruits('g', (results) => {
// do something with results
alert(results);
});
// Might eventually print: ['grape', 'guava']
/* … and more! */
const fetchAll = combineFetchers([fetchAnimals, fetchFruits, /* … etc. */]);
const fetchMedia = combineFetchers([fetchVideos, fetchMovies, fetchBooks]);
fetchAll('g', (results) => console.log(results));
// Might eventually print: ['giraffe', 'gorilla', 'grape', 'guava', ...]
fetchAll('gi', (results) => console.log(results));
// Might eventually prints: ['giraffe']
// TODO: implement combineFetchers
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Input: array of functions
output: an array of result values of each function
function combineFetchers(fetchers) {
/*
return a function: input: prefix, function
*/
return function (prefix, func) {
let arr = []
for(let i = 0; i < fetchers.length; i++) {
fetchers[i](prefix, (results) => {
// handle results
for (const result of results) {
arr.push(result);
}
if (i == fetchers.length-1) {
func(arr);
}
});
}
}
}
@tuxido-feynman
Copy link

Notes: Implement a fetcher interface, as shown above, but the callback functions are the fetchAll, fetchMedia

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment