-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfillUndefined.js
89 lines (79 loc) · 2.71 KB
/
fillUndefined.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
let getNextDefinedNum = (i, arr) => {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] !== undefined) {
return { value: arr[j], index: j };
}
}
return null;
};
let getPreviousDefinedNum = (i, arr) => {
for (let j = i - 1; j >= 0; j--) {
if (arr[j] !== undefined) {
return { value: arr[j], index: j };
}
}
return null;
};
let getClosestDefinedNum = (i, arr) => {
const prevObj = getPreviousDefinedNum(i, arr);
const nextObj = getNextDefinedNum(i, arr);
if (!prevObj && !nextObj) {
return undefined;
}
const prevDistance = prevObj ? i - prevObj.index : Infinity;
const nextDistance = nextObj ? nextObj.index - i : Infinity;
if (prevDistance < nextDistance) {
return prevObj.value;
} else if (nextDistance < prevDistance) {
return nextObj.value;
} else {
// Distances are equal, choose the smallest value
return Math.min(prevObj.value, nextObj.value);
}
};
function fill(arr, method = 0) {
const result = arr.slice(); // Create a copy of the array to hold the results
if (method === -1) {
// Replace undefined values with closest int on the right
for (let i = 0; i < arr.length; i++) {
if (arr[i] === undefined) {
const nextObj = getNextDefinedNum(i, arr); // Use the original array
if (nextObj) {
result[i] = nextObj.value;
}
}
}
} else if (method === 0) {
// Replace undefined values with closest defined number, choose smallest if equidistant
for (let i = 0; i < arr.length; i++) {
if (arr[i] === undefined) {
const closestValue = getClosestDefinedNum(i, arr); // Use the original array
if (closestValue !== undefined) {
result[i] = closestValue;
}
}
}
} else if (method === 1) {
// Replace undefined values with closest int on the left
for (let i = 0; i < arr.length; i++) {
if (arr[i] === undefined) {
const prevObj = getPreviousDefinedNum(i, arr); // Use the original array
if (prevObj) {
result[i] = prevObj.value;
}
}
}
}
return result;
}
/*
Params:
arr is the array of numbers and undefined
method is either -1, 0, or 1
Return Value:
the array, but with all numbers filled in according to the rules.
Note the case where the first or last value is undefined and there is not suitable replacement, in which
case it just stays undefined
Example:
fill([undefined,1,1,1,2,undefined,undefined,2],1) => [1,1,1,1,2,2,2,2]
*/