Created
May 18, 2022 01:57
-
-
Save DubAvenXP/cd0b845a552ee56e9a327d0870a2e159 to your computer and use it in GitHub Desktop.
Chuck Norris - Technical Test
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 { Request, Response } from "express"; | |
import axios from "axios"; | |
import { err, success } from "../../helpers"; | |
// average time for 15 jokes: 400ms - 800ms | |
// @route GET api/chucknorris/jokes | |
export async function list(req: Request, res: Response) { | |
try { | |
const jokes = await getJokes(15, []); | |
success(req, res, jokes, 200); | |
} catch (error) { | |
console.error(error); | |
err(req, res, error, 500); | |
} | |
} | |
async function verifyDuplicate(jokes: any[], jokeToVerify: any): Promise<any> { | |
// Count the number of times the joke appears in the array | |
const count = jokes.filter( | |
(joke: any) => joke.joke === jokeToVerify.joke | |
).length; | |
if (count === 1) { | |
return false; | |
} | |
return true; | |
} | |
async function getJokes(quantity: number, jokes: any[]): Promise<any> { | |
try { | |
const API_URL = "https://api.chucknorris.io/jokes/random"; | |
const promises = []; | |
// Create a promise for each joke | |
for (let i = 0; i < quantity; i++) { | |
promises.push(axios.get(API_URL)); | |
} | |
// Wait for all the promises to resolve | |
const newJokes = await Promise.all(promises).then((results) => { | |
return results.map((result) => { | |
return { | |
id: result.data.id, | |
value: result.data.value, | |
url: result.data.url, | |
}; | |
}); | |
}); | |
// Concatenate the new jokes with the existing ones | |
jokes = jokes.concat(newJokes); | |
// Get unique jokes | |
jokes = jokes.filter(async (joke) => { | |
const isDuplicate = await verifyDuplicate(jokes, joke); | |
return isDuplicate ? null : joke; | |
}); | |
if (jokes.length === quantity) { | |
// Return the unique jokes | |
return jokes; | |
} else { | |
// Recursively call the function until the quantity of jokes is reached | |
const newQuantity = quantity - jokes.length; | |
getJokes(newQuantity, jokes); | |
} | |
} catch (error) { | |
console.error(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment