Работа со стеком и очередью задач

Стек stack - это структура данных, которая реализует технологию последним пришёл - первым вышел LIFO.

Очередь queue - это структура данных, которая реализует технологию первым пришел - первым ушел FIFO .

Используя методы массивов#pop#push#shift#unshift мы можем реализовать стек и очередь.

Реализация stack

function flatten(...stack) {
	const result = []
	while(stack.length) {
		const el = stack.shift() // берём первый элемент из массива и удалим его
		if (Array.isArray(el)) {
			stack.unshift() // положим в самое начало развёрнутый элемент
			continue
		}
		
		result.push(el) // добавим развернутый элемент в массив
	}
	
	return result
}
 
console.log(1, [2, [3]]], 4, 5, [6, [7]]))
function calculate(expression) {
	const arr = expression.split(' ');
	const stack = [];
	
	while(arr.length) {
		const el = arr.pop();
		const numberedEl = Number(el);
		
		if(!isNaN(numberedEl)){
			stack.push(numberedEl);
			continue;
		}
		
		const firstNum = stack.pop();
		const secondNum = stack.pop();
		
		switch(el) {
			case: '+':
			stack.push(firstNum + secondNum)
				break;
			case: '/':
			stack.push(firstNum / secondNum)
				break;
			case: '-':
			stack.push(firstNum - secondNum)
				break;
			case: '*':
			stack.push(firstNum * secondNum)
				break;			
		}
	}
	
	return stack[0]
}
 
console.log(calculate('+ 3 5'), 8)
console.log(calculate('* +2 2 3*'), 12)
console.log(calculate('/ + 3 5 * 2 2*'), 2)

Реализация queue

 
function queueTime(customers, n) {
	if(!customers.length) return 0;
	const queue = [...customers];
	const tills = Array(Math.min(n, customers.length)).fill(0)
	
	while(queue,length) {
		const customer = queue.shift();
		const tillMinId = tills.indexOf(Nath.min(...tills));
		tills[tillMinId] += customer;
	}
	return Math.max(...tills);
}
 
console.log(queueTime([], 1), 0)
console.log(queueTime([1, 2, 3, 4], 1), 10)
console.log(queueTime([2, 2, 3, 3, 4, 4], 2), 9)
console.log(queueTime([1, 2, 3, ,4, 5], 100), 5)