This repository has been archived on 2023-11-10. You can view files and clone it, but cannot push or open issues or pull requests.
freecodecamp-projects/7-quality-assurance/4-sudoku-solver/routes/api.js

48 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-11-12 21:40:00 +00:00
"use strict";
2022-11-12 21:40:00 +00:00
const SudokuSolver = require("../controllers/sudoku-solver.js");
module.exports = function (app) {
let solver = new SudokuSolver();
2022-11-12 21:40:00 +00:00
app.route("/api/check").post((req, res) => {
if (!req.body.puzzle || !req.body.coordinate || !req.body.value) {
return res.json({ error: "Required field(s) missing" });
}
if (!(req.body.value > 0) || !(req.body.value < 10)) {
return res.json({ error: "Invalid value" });
}
if (!/^[A-I][1-9]$/.test(req.body.coordinate)) {
return res.json({ error: "Invalid coordinate" });
}
let validString = solver.validate(req.body.puzzle);
if (validString !== true) {
return res.json(validString);
}
let row = req.body.coordinate[0].charCodeAt(0) - 65;
let col = req.body.coordinate[1] - 1;
let conflict = [];
let valid;
if (!solver.checkRowPlacement(req.body.puzzle, row, col, req.body.value)) {
conflict.push("row");
}
if (!solver.checkColPlacement(req.body.puzzle, row, col, req.body.value)) {
conflict.push("column");
}
if (
!solver.checkRegionPlacement(req.body.puzzle, row, col, req.body.value)
) {
conflict.push("region");
}
conflict.length > 0 ? (valid = false) : (valid = true);
res.json({ valid: valid, conflict: conflict });
});
2022-11-12 21:40:00 +00:00
app.route("/api/solve").post((req, res) => {
if (!req.body.puzzle) {
return res.json({ error: "Required field missing" });
}
res.json(solver.solve(req.body.puzzle));
});
};