-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteview.js
More file actions
113 lines (91 loc) · 2.29 KB
/
inteview.js
File metadata and controls
113 lines (91 loc) · 2.29 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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const array = [
1,
NaN,
undefined,
null,
2.3,
"7",
"",
false,
"-2",
"-3",
"This is a good day",
" ",
{ value: 20 },
{},
"to validate a test case.",
[],
true,
2.9,
"0",
[1, 2, 3],
];
function getSum() {
/**
* - remove all the values which are not numbers in the array.
* - add all the valid numbers after rounding off the values to the nearest integer.
* - numbers can be stored as strings as well, so consider a string as a number if it is a valid number.
* - return the sum of all the integers.
*/
return array.reduce((sum, curr) => {
const value = cleanUpValue(curr);
return sum + value;
}, 0);
}
function cleanUpValue(value) {
// const number = Number(value);
// if(Number.isNaN(number)){
// return 0
// }
// handling undefined and null
if (value === undefined || value === null) return 0;
// handling NaN
if (Number.isNaN(value)) return 0;
// handling strings
if (typeof value === "string") {
const maybeNumber = parseInt(value);
if (Number.isNaN(maybeNumber)) return 0;
return Math.round(maybeNumber);
}
// handling arrays and objects
if (typeof value === "object") {
return 0;
}
// handling booleans
if (value === true || value === false) {
return 0;
}
// handling numbers
const maybeNumber = Number(value);
if (Number.isNaN(maybeNumber)) return 0;
return Math.round(maybeNumber);
}
function cleanUpString(value) {
if (typeof value === "string") {
const maybeNumber = Number(value);
if (!Number.isNaN(maybeNumber)) return "";
return String(value);
}
if (value === undefined || value === null) return "";
if (Number.isNaN(value)) return "";
if (typeof value === "object") return "";
if (value === true || value === false) return "";
}
function getString() {
/**
* - remove any invalid string (i.e, objects, arrays, numbers, etc.).
* - you should also consider a number as string to be invalid.
* - trimmed empty strings are invalid as well.
* - return the concatenated string formed by all the strings, joined by a whitespace.
*/
return array.reduce((result, curr) => {
const value = cleanUpString(curr);
return result + value;
}, "");
}
module.exports = {
getSum,
getString,
};
getString();
// cleanUpString("this is a good day");