Skip to content

Commit

Permalink
Implement Get Pokemon by HP (Fix Issue developer-job-simulation#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunYuHuang committed Apr 11, 2023
1 parent 36977dc commit 098229e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ This is an Express JS Pokemon API based on PokeAPI. Your job is to fix 4 issues:
1. ~~Implement Get Pokemon by ID~~
1. ~~Implement Get Pokemon by Name~~
1. ~~Implement Get Pokemon by Type~~
1. Implement Get Pokemon by HP (with Query Params)
1. ~~Implement Get Pokemon by HP (with Query Params)~~

Please refer to the API Swagger documentation for clear specifications of the API's intended behavior. You can find the Swagger docs at http://localhost:3000/api-docs.

Expand Down
40 changes: 32 additions & 8 deletions src/routes/pokemon.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,37 @@ router.get("/", function (req, res, next) {
res.json(pokedex);
});

/* GET Pokemon by HP */
router.get("/hp", function (req, res, next) {
const validComparators = new Set(["lt", "gt", "lte", "gte"]);
const comparators = req.query;
const comparatorKeys = Object.keys(comparators);
for (let i = 0; i < comparatorKeys.length; i++) {
if (!validComparators.has(comparatorKeys[i]))
return res.status(400).json({
error: 'Invalid Operator. Must be one of ["gt","gte","lt","lte"]',
});
}
const comparatorToFn = {
lt: (l, r) => l < r,
gt: (l, r) => l > r,
lte: (l, r) => l <= r,
gte: (l, r) => l >= r,
};
function inHPRange(hp) {
for (const [comp, value] of Object.entries(comparators)) {
if (!comparatorToFn[comp](hp, Number(value))) return false;
}
return true;
}
const pokemons = pokedex.filter((el) => inHPRange(el.base.HP));

if (!pokemons || pokemons.length === 0)
return res.status(404).json({ error: "Not found" });

return res.status(200).json(pokemons);
});

/* GET Pokemon by Id. */
router.get("/:id", function (req, res, next) {
const { id } = req.params;
Expand All @@ -16,7 +47,7 @@ router.get("/:id", function (req, res, next) {
const pokemon = pokedex.find((el) => el.id === Number(id));
if (!pokemon) return res.status(404).json({ error: "Not found" });

console.log(pokemon);
// console.log(pokemon);
return res.status(200).json(pokemon);
});

Expand All @@ -42,11 +73,4 @@ router.get("/type/:type", function (req, res, next) {
return res.status(200).json(pokemons);
});

/* GET Pokemon by HP */
router.get("/hp", function (req, res, next) {
// TODO: Implement this route. See swagger docs for details, by visiting http://localhost:3000/api-docs
res.status(501).json({ message: "Not Implemented" });
return;
});

module.exports = router;

0 comments on commit 098229e

Please sign in to comment.