forked from Thatskat/southpark-quotes-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quotesController.js
43 lines (34 loc) · 1.08 KB
/
quotesController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
let quotes = require("./quotes.js");
function getRandom(quoteNumber) {
let quoteLimit = quoteNumber > quotes.length ? quotes.length : quoteNumber;
let response = new Array(quoteLimit);
let availableResponse = quotes.slice();
for (let i = 0; i < quoteLimit; i++) {
response[i] = availableResponse.splice(
Math.floor(Math.random() * availableResponse.length),
1
)[0];
}
return response;
}
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 filterIt(lowercaseArr, regex);
}
module.exports.getRandom = getRandom;
module.exports.searchQuotes = searchQuotes;