-
Notifications
You must be signed in to change notification settings - Fork 0
/
jan52021.js
79 lines (71 loc) · 1.85 KB
/
jan52021.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
let myArray = {};
myArray.length = 0;
const addElement = (value) => {
myArray[myArray?.length ?? 0] = value;
myArray.length++;
};
const deleteElement = () => {
if (myArray?.length > 0) {
delete myArray[myArray?.length - 1];
myArray.length--;
} else {
throw Error(`Can't pop the empty array`);
}
};
const maximumElement = () => {
if (myArray?.length > 1) {
let maxValue = myArray[0];
for (let index = 0; index < myArray.length; index++) {
if (myArray[index] > maxValue) {
maxValue = myArray[index];
}
}
console.log(maxValue, "is the maximum value!");
} else {
throw Error(`I need atleast two elements to find the maximum value`);
}
};
const searchByIndex = (inputIndex) => {
if (inputIndex >= 0 && inputIndex < myArray.length) {
console.log("Value at", inputIndex, "index is", myArray[inputIndex]);
} else {
throw Error(`Array Out Of Bound!`);
}
};
const searchByValue = (inputValue) => {
if (myArray?.length > 1) {
const recordIndex = null;
for (let index = 0; index < myArray.length; index++) {
if (myArray[index] === inputValue) {
recordIndex = index;
return;
}
}
if (recordIndex) {
console.log(
"Your input value",
inputValue,
"is at",
recordIndex,
"index"
);
} else {
console.log("Your value is not here!");
}
} else {
throw Error(`Empty Array. You can use pushElement function.`);
}
};
myArray.pushElement = addElement;
myArray.popElement = deleteElement;
myArray.getMax = maximumElement;
myArray.searchByIndex = searchByIndex;
myArray.searchByValue = searchByValue;
for (let index = 0; index < 7; index++) {
myArray.pushElement(Math.random() * 10);
}
console.clear();
myArray.getMax();
myArray.searchByIndex(0);
myArray.searchByValue(0);
console.log("array => ", myArray);