Last active
July 24, 2021 19:14
-
-
Save Sara3/4ffb78773f9b2e765fc10bf5fd7ea9b8 to your computer and use it in GitHub Desktop.
question
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
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); | |
} | |
}); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notes: Implement a fetcher interface, as shown above, but the callback functions are the fetchAll, fetchMedia