const API_BASE = "https://pokeapi.co/api/v2"; /** * Fetches JSON data from a given URL. * @param {string} url * @returns {Promise} */ 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} */ 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} - 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} */ 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