Repository navigation
Expand file tree
/
Copy pathdataFunctions.js
More file actions
62 lines (57 loc) · 1.85 KB
/
Copy pathdataFunctions.js
File metadata and controls
62 lines (57 loc) · 1.85 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
export const getSearchTerm = () => {
const rawSearchTerm = document.getElementById("search").value.trim();
const regex = /[ ]{2,}/gi;
const searchTerm = rawSearchTerm.replaceAll(regex, " ");
return searchTerm;
};
export const retrieveSearchResults = async (searchTerm) => {
const wikiSearchString = getWikiSearchString(searchTerm);
const wikiSearchResults = await requestData(wikiSearchString);
let resultArray = [];
if (wikiSearchResults.hasOwnProperty("query")) {
resultArray = processWikiResults(wikiSearchResults.query.pages);
}
return resultArray;
};
const getWikiSearchString = (searchTerm) => {
const maxChars = getMaxChars();
const rawSearchString = `https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=${searchTerm}&gsrlimit=20&prop=pageimages|extracts&exchars=${maxChars}&exintro&explaintext&exlimit=max&format=json&origin=*`;
const searchString = encodeURI(rawSearchString);
return searchString;
};
const getMaxChars = () => {
const width = window.innerWidth || document.body.clientWidth;
let maxChars;
if (width < 414) maxChars = 65;
if (width >= 414 && width < 1400) maxChars = 100;
if (width >= 1400) maxChars = 130;
return maxChars;
};
const requestData = async (searchString) => {
try {
const response = await fetch(searchString);
const data = await response.json();
return data;
} catch (err) {
console.error(err);
}
};
const processWikiResults = (results) => {
const resultArray = [];
Object.keys(results).forEach((key) => {
const id = key;
const title = results[key].title;
const text = results[key].extract;
const img = results[key].hasOwnProperty("thumbnail")
? results[key].thumbnail.source
: null;
const item = {
id: id,
title: title,
img: img,
text: text
};
resultArray.push(item);
});
return resultArray;
};