diff options
Diffstat (limited to 'js')
-rw-r--r-- | js/poke-chain.js | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/js/poke-chain.js b/js/poke-chain.js new file mode 100644 index 0000000..2e227b6 --- /dev/null +++ b/js/poke-chain.js @@ -0,0 +1,58 @@ +const API_BASE = "https://pokeapi.co/api/v2"; + +/** + * Fetches JSON data from a given URL. + * @param {string} url + * @returns {Promise<any>} + */ +const fetchJSON = (url) => + fetch(url).then((res) => res.ok ? res.json() : Promise.reject(`Error: ${res.status}`)); + +/** + * Fetches a Pokémon's species data to get the evolution chain URL. + * @param {string|number} identifier - Pokémon name or ID. + * @returns {Promise<string>} + */ +const getEvolutionChainUrl = (identifier) => + fetchJSON(`${API_BASE}/pokemon-species/${identifier}`) + .then((data) => data.evolution_chain.url); + +/** + * Fetches and extracts evolution chain details. + * @param {string} url - Evolution chain API URL. + * @returns {Promise<string[]>} - Evolution chain sequence. + */ +const getEvolutionChain = (url) => + fetchJSON(url).then((data) => extractEvolutionChain(data.chain)); + +/** + * Recursively extracts evolution names from chain data. + * @param {Object} chain + * @returns {string[]} + */ +const extractEvolutionChain = (chain) => { + const evolutions = [chain.species.name]; + let next = chain.evolves_to; + + while (next.length) { + evolutions.push(next[0].species.name); + next = next[0].evolves_to; + } + + return evolutions; +}; + +/** + * Gets the evolution chain of a given Pokémon by name or ID. + * @param {string|number} identifier + * @returns {Promise<void>} + */ +const getPokemonEvolutionChain = (identifier) => + getEvolutionChainUrl(identifier) + .then(getEvolutionChain) + .then((evolutions) => console.log(`Evolution chain: ${evolutions.join(" → ")}`)) + .catch((error) => console.error(`Failed to fetch evolution chain: ${error}`)); + +// Test cases +getPokemonEvolutionChain("pikachu"); // Pikachu's evolution chain +getPokemonEvolutionChain(40); // Pokémon with ID 40 |