๋ฐ์ํ
์ฒ์ ํ์ด(์๊ฐ์ด๊ณผ)
const fs = require('fs');
let input = (fs.readFileSync('./test') + '').toString().trim().split('\n');
input.shift();
let stack = [];
input.map((cmd) => {
const cmdArr = cmd.split(' ');
const command = cmdArr[0];
switch (command) {
case 'push':
const number = cmdArr[1];
stack.push(parseInt(number));
break;
case 'top':
if (stack.length === 0) console.log(-1);
else console.log(stack[stack.length - 1]);
break;
case 'pop':
if (stack.length === 0) console.log(-1);
else console.log(stack.pop());
break;
case 'size':
console.log(stack.length);
break;
case 'empty':
if (stack.length === 0) console.log(1);
else console.log(0);
}
});
๊ฐ๊ฐ์ ๋ช ๋ น์ด์์ ๋นผ๊ณ ๋ํ๊ณ ๋๋ฆฌ๋ฅผ ํ๋ค.. ์ญ์๋ ์๊ฐ์ด๊ณผ...
๋ค๋ฅธ ํ์ด
๐ ์ฐธ๊ณ ๋ธ๋ก๊ทธ
const fs = require('fs');
const { isModuleNamespaceObject } = require('util/types');
let input = (fs.readFileSync('./test') + '').toString().trim().split('\n');
input.shift();
let stack = [];
const cmdObj = {
pop: () => stack.pop() || -1,
size: () => stack.length,
empty: () => (stack[0] ? 0 : 1),
top: () => stack[stack.length - 1] || -1,
push: (item) => {
stack.push(item.split(' ')[1]);
return '';
},
};
const result = input.reduce(
(acc, v) => acc + (cmdObj[v] ? `${cmdObj[v]()}\n` : cmdObj.push(v)),
''
);
console.log(result);
โจ ๋์ ๋ค๋ฅธ์
1. switch๋กํ์ง ์๊ณ ๊ฐ์ฒด ๋ฉ์๋๋ก ์ ๋ฌ
2. if ๋ฌธ์ผ๋ก ํ์ง ์๊ณ || ์ฐ์ฐ์ ์ฌ์ฉ
3. ํ์ดํํจ์ ๋ฉ์๋
4. reduce๋ฅผ ํ์ฉํ ans ์์ฑ
5. push๊ฐ ์๋๊ฒฝ์ฐ ๊ตณ์ด ๊ณต๋ฐฑ์ผ๋ก ๋๋์ง ์์
๐ฅณ ์ง์ง ๊ฐ๋จํ ์ฝ๋์์ ๋ง์ ์ ์ ๋ฐฐ์ ๋ค.
๋จ์ํ ๊ตฌํ์ด ๋๋ ์ฝ๋์ธ๊ฐ ์๋๋ฉด ๋ณด๊ธฐ ์ฝ๊ณ ํจ์จ์ ์ธ ์ฝ๋์ธ๊ฐ..?
'๐ ์๊ณ ๋ฆฌ์ฆ > ๋ฐฑ์ค JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] node.js/ 1302 ๋ฒ ์คํธ์ ๋ฌ (0) | 2021.10.19 |
---|---|
[๋ฐฑ์ค] node.js/ 10866 ๋ฑ (0) | 2021.10.18 |
[๋ฐฑ์ค] node.js/ 3986 ์ข์ ๋จ์ด (0) | 2021.10.14 |
[๋ฐฑ์ค] node.js/ 2164 ์นด๋2 (0) | 2021.10.13 |
[๋ฐฑ์ค] node.js / 1158 ์์ธํธ์ค ๋ฌธ์ (2) | 2021.10.12 |
๋๊ธ