-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecursionProblems.js
62 lines (47 loc) · 1.13 KB
/
RecursionProblems.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
// Recursion Problems
// implement lodash get problem
// implement deepclone functionlity
// implement power
// implement fib
// someRecursive Solution
//lodash get problem
function getProp( object, keys, defaultVal ){
keys = Array.isArray( keys )? keys : keys.split('.');
object = object[keys[0]];
if( object && keys.length>1 ){
return getProp( object, keys.slice(1));
}
return object === undefined? defaultVal : object;
}
// fib 0,1,1,2,3,5,8
function fibRecursive(num){
if(num < 2){
return num
}
return fib(num-1) + fib(num-2);
}
//for 1 fib will always be 1, cause 0+1
function fibItrative(num){
let sumArr = [0,1]
for(let i=0;i<=num; i++){
if(i > 1){
const a = sumArr[i-1]
const b = sumArr[i-2]
sumArr.push(a+b)
}
}
return sumArr
}
// someRecursive([1,2,3,4], isOdd) // true
// someRecursive([4,6,8,9], isOdd) // true
// someRecursive([4,6,8], isOdd) // false
// someRecursive([4,6,8], val => val > 10); // false
function someRecursive(arr, cb){
if(arr.length === 0){
return
}
const val = arr.shift()
const res = cb(val)
someRecursive(arr, cb)
return res
}