-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInSearchEngine.js
More file actions
62 lines (57 loc) · 1.36 KB
/
InSearchEngine.js
File metadata and controls
62 lines (57 loc) · 1.36 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
class InMemorySearch {
constructor() {
this.documents = new Map();
}
addDocuments(...args) {
const key = args[0];
const val = args.filter((arg) => arg !== key);
if (!this.documents.has(key)) {
this.documents.set(key, val);
} else {
const present = this.documents.get(key);
const combinedVal = [...present, ...val];
this.documents.set(key, combinedVal);
}
}
search(nameSpace, callback, obj) {
const result = this.documents.get(nameSpace);
const filteredResults = result.filter(callback);
const sortedKey = obj.key;
const filteredResultsSorted = filteredResults.sort((a, b) => {
if (obj.asc === false) {
return b[sortedKey] - a[sortedKey];
}
return a[sortedKey] - b[sortedKey];
});
return filteredResultsSorted;
}
}
const searchEngine = new InMemorySearch();
searchEngine.addDocuments(
"Movies",
{ name: "Avenger", rating: 8.5, year: 2017 },
{ name: "Black Adam", rating: 8.7, year: 2022 },
{ name: "Jhon Wick 4", rating: 8.2, year: 2023 },
{ name: "Black Panther", rating: 9.0, year: 2022 }
);
console.log(
searchEngine.search("Movies", (e) => e.rating > 8.5, {
key: "rating",
asc: false,
})
);
// Output
/*
[
{
"name": "Black Panther",
"rating": 9,
"year": 2022
},
{
"name": "Black Adam",
"rating": 8.7,
"year": 2022
}
]
*/