Skip to content

Commit

Permalink
completed search function
Browse files Browse the repository at this point in the history
  • Loading branch information
Thatskat committed Jul 1, 2023
1 parent 3fb6127 commit 0d9144c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ const limit = rateLimit({
});

// GET RANDOM FUNCTION FROM ./QUOTESCONTROLLER
const { getRandom } = require("./quotesController");
const { getRandom, searchQuotes } = require("./quotesController");

// IMPORT QUOTES ARRAY
const quotes = require('./quotes');

// IMPLEMENT MIDDLEWARE
app.use(helmet());
Expand All @@ -38,6 +41,10 @@ app.get("/v1/quotes/:num?", function (req, res, next) {
res.send(getRandom(req.params.num || 1));
});

app.get("/v1/quotes/search/:term", function (req, res,) {
res.send(searchQuotes(quotes, req.params.term));
})

// USE ERROR MIDDLEWARE
app.use(error)

Expand Down
23 changes: 20 additions & 3 deletions quotesController.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,27 @@ function getRandom(quoteNumber) {
return response;
}

function searchQuotes(searchTerm) {
const regEx = new RegExp(searchTerm, "i");
function filterIt(arr, searchTerm) {
return arr.filter(function (obj) {
return Object.keys(obj).some(function (key) {
return obj[key].includes(searchTerm);
});
});
}

function searchQuotes(arr, searchTerm) {
let regex = new RegExp(searchTerm, "i");
regex = regex.toString().replace(/^\/|\/[a-z]*$/gi, "");

let lowercaseArr = arr.map(function (i) {
let lowercaseObjects = {};
Object.entries(i).forEach(function ([key, value]) {
lowercaseObjects[key] = value.toLowerCase();
});
return lowercaseObjects;
});

return quotes.filter(quote && quote.match(regEx));
return filterIt(lowercaseArr, regex);
}

module.exports.getRandom = getRandom;
Expand Down

0 comments on commit 0d9144c

Please sign in to comment.