-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindIndex.js
More file actions
48 lines (40 loc) · 1.1 KB
/
findIndex.js
File metadata and controls
48 lines (40 loc) · 1.1 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
function findIndex(array, predicate, fromIndex = 0) {
if (fromIndex > array.length) {
return -1
}
if ( fromIndex < 0) {
fromIndex = Math.max(array.length + fromIndex , 0)
}
for ( let i = fromIndex; i < array.length ; i++) {
const isValid = predicate(array[i])
if (isValid) {
return i
}
}
return -1
}
console.log(findIndex([5, 12, 8, 130, 44] , (num) => num > 3, -2))
export default function findLastIndex(
array,
predicate,
fromIndex = array.length - 1,
) {
if (fromIndex > array.length) {
return array.length - 1
}
if ( fromIndex < 0) {
fromIndex = Math.max(array.length + fromIndex , 0)
}
for ( let i = fromIndex; i >= 0 ; i--) {
const isValid = predicate(array[i])
console.log(isValid)
if (isValid) {
return i
}
}
return -1
}
const arr = [5, 4, 3, 2, 1]
console.log( findLastIndex(arr, (num) => num > 3)) // => 1
console.log(findLastIndex(arr, (num) => num > 1, 3)); // => 3
console.log(findLastIndex(arr, (num) => num < 1, 2))