栈
const { log } = console;
function Stack() {
let schema = [];//用数组保存栈中的元素
//入栈
this.push = (item) => (schema.push(item))
//出栈
this.pop = () => (schema.pop())
//栈顶
this.top = () => (schema[schema.length - 1])
//是否为空栈
this.isEmpty = () => (schema.length === 0)
//移除栈里所有元素
this.clear = () => { schema.length = 0 } // or this.clear=()=>{schema=[]}
//返回栈中元素个数
this.size = () => (schema.length)
//元素输出
this.print = () => { log(schema.toString()) }
}
module.exports=Stack;
转换
const Stack= require('./stack');
const stack= new Stack();
const {log}=console;
function transfer(number=10,base=2){
let stackItem;
let result='';
let digits = '0123456789ABCDEF';
while(number>0){
stackItem=parseInt(number%base);
stack.push(stackItem);
number=parseInt(number/base);
}
while(!stack.isEmpty()){
result+=digits[stack.pop()] ;
}
return result;
}
log(transfer(10,16));//A
log(transfer());//1010