-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindKey.js
60 lines (49 loc) · 1.34 KB
/
findKey.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const assertEqual = function(actual, expected) {
if (actual === expected) {
console.log(`✅ Assertion Passed:${actual} === ${expected}`);
} else {
console.log(`🛑 Assertion Failed:${actual} !== ${expected}`);
}
};
const findKey = function(object, callback) { //defining function
//loop thru keys of object
for (let key of Object.keys(object)) {
//callback for current key value
if (callback(object[key])) {
return key; //return key if truthy
}
}
return undefined; // if no key found return undefined
};
findKey(
{
"Blue Hill": { stars: 1 },
Akaleri: { stars: 3 },
noma: { stars: 2 },
elBulli: { stars: 3 },
Ora: { stars: 2 },
Akelarre: { stars: 3 },
},
(x) => x.stars === 2
); // => "noma"
//TEST
const result1 = findKey(
{
"Blue Hill": { stars: 1 },
Akaleri: { stars: 3 },
noma: { stars: 2 },
elBulli: { stars: 3 },
Ora: { stars: 2 },
Akelarre: { stars: 3 },
}, (x) => x.stars === 2);
assertEqual(result1, "noma");// Should pass
const result2 = findKey(
{
"Blue Hill": { stars: 1 },
Akaleri: { stars: 3 },
noma: { stars: 2 },
elBulli: { stars: 3 },
Ora: { stars: 2 },
Akelarre: { stars: 3 },
}, (x) => x.stars === 5);
assertEqual(result2, undefined); // => "noma" // Should fail/undefined - there are no keys w/ 5 stars!