-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs_stack.js
More file actions
59 lines (52 loc) · 1.42 KB
/
js_stack.js
File metadata and controls
59 lines (52 loc) · 1.42 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
/** A helper class to implement stack **/
class Stack {
constructor() {
this.items = [];
}
pop(){
return this.items.pop();
}
push(item){
this.items.push(item);
}
peek(){
return this.items[this.items.length-1];
}
isEmtpy(){
return this.items.length==0;
}
size(){
return this.items.length;
}
clear(){
this.items = [];
}
}
/** testing the stack **/
let stackItems = new Stack();
stackItems.push('233');
stackItems.push('232');
stackItems.push('2asd');
console.log(stackItems.pop());
console.log(stackItems.peek());
console.log(stackItems.size());
console.log(stackItems.isEmtpy());
stackItems.clear();
console.log(stackItems.isEmtpy());
/** implementing base converter to use stack concept. Converts decimal to binary, octal or hex **/
let baseConvertor = (decimalNumber, base) => {
let remainderStack = new Stack(), remainder, baseString = '',
digits = '0123456789ABCDEF';
while (decimalNumber > 0){
remainder = Math.floor(decimalNumber % base);
remainderStack.push(remainder);
decimalNumber = Math.floor(decimalNumber / base);
}
while (!remainderStack.isEmtpy()){
baseString += digits[remainderStack.pop()];
}
return baseString;
};
console.log('Binary: '+baseConvertor(10023,2));
console.log('Octal: '+baseConvertor(10023,8));
console.log('Hex: '+baseConvertor(10023,16));