function solution(numbers, direction) {
var answer = [];
if ("right" == direction) {
numbers.unshift(numbers.pop());
} else {
numbers.push(numbers.shift());
}
answer = numbers;
return answer;
}
์ ์ผ ๋ฒ ์คํธ๋ผ๊ณ ์๊ฐํ๋ ์ฝ๋.
Array.prototype.pop()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
Array.pop() ์ ์ฌ์ฉํ๋ฉด ๋ณํํ Array์ ์์ค ๋ง์ง๋ง ๊ฐ ๋ ๋ค ์ป์ ์ ์๋ค.
const arr = [๐,๐,๐,๐];
arr.pop() ์ ํ๊ฒ ๋๋ฉด
arr = [ ๐,๐,๐] ์ด๊ณ ,
arr.pop()๊ฐ ๋ฐํํ๋ ๊ฐ์ ๐์ด๋ค.
Array.prototype.unshift()
unshift() ๋ฉ์๋๋ ์๋ก์ด ์์๋ฅผ ๋ฐฐ์ด์ ๋งจ ์์ชฝ์ ์ถ๊ฐํ๊ณ , ์๋ก์ด ๊ธธ์ด๋ฅผ ๋ฐํํฉ๋๋ค.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
arr = [ ๐,๐,๐] ๋ฅผ ๋ค์ ์๋ก ๋ค์๋ฉด,
arr.unshift(๐) ์ ํ๋ฉด,
arr = [ ๐,๐,๐,๐] ์ด๋ ๊ฒ ๋งจ ์์ ๋ฃ์ด์ค๋ค.
Array.prototype.shift()
shift() ๋ฉ์๋๋ ๋ฐฐ์ด์์ ์ฒซ ๋ฒ์งธ ์์๋ฅผ ์ ๊ฑฐํ๊ณ , ์ ๊ฑฐ๋ ์์๋ฅผ ๋ฐํํฉ๋๋ค. ์ด ๋ฉ์๋๋ ๋ฐฐ์ด์ ๊ธธ์ด๋ฅผ ๋ณํ๊ฒ ํฉ๋๋ค.
(pop ์ด๋ ๋ฐ๋๋ผ๊ณ ์๊ฐํ๋ฉด ๋๋ค.)
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
const arr = [๐,๐,๐,๐];
arr.shift() ์ ํ๊ฒ ๋๋ฉด
arr = [ ๐,๐,๐] ์ด๊ณ ,
arr.pop()๊ฐ ๋ฐํํ๋ ๊ฐ์ ๐์ด๋ค.
function solution(numbers, direction) {
let resultArr = [];
for (let i = 0; i < numbers.length; i++) {
if (direction === "right") {
i + 1 !== numbers.length ? resultArr[i + 1] = numbers[i] : resultArr[0] = numbers[i];
} else if (direction === "left") {
i - 1 < 0 ? resultArr[numbers.length - 1] = numbers[i] : resultArr[i - 1] = numbers[i];
}
}
console.log(resultArr);
return resultArr;
}
์ด๊ฑด ๋์ ์ฝ๋! ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ index๋ฅผ ์ ์ผ ๋์ผ๋ก ๋ณด๋ด์ฃผ๋ ๋ฐฉ์์ผ๋ก ์ฝ๋๋ฅผ ์งฐ๋๋ฐ, ์์ pop๊ณผ shift ํจ์๋ฅผ ์์๋ค๋ฉด ํจ์ฌ ๊ฐ๋จํ๊ฒ ์์ฑ์ด ๊ฐ๋ฅํ๋ค.