프로그래밍 언어/JS TS

JS 코딩테스트 준비하기

트리맨스 2022. 9. 24. 18:23
반응형


최근에 코딩테스트를 보면서 알고리즘이 말도 안되게 부족하다는 것을 많이 느꼈다. 그래서 외부 에디터를 사용할 수 있는 환경이라는 상황에서 코딩 결과물을 빠르게 확인할 수 있는 환경을 꾸며볼려고 한다.

JS 코딩테스트 환경 꾸미기


목표는 지속적인 테스트와 신속히 결과물을 내는 것이다. 여기서 사용할 것은 nodemon이다. nodemon은 파일이 저장될 때 마다 js파일을 다시 실행켜준다. 그래서 명령어를 따로 입력하여 결과물을 보는 과정이 생략이 된다. node 환경이 설치되어 있다는 기준으로 설명을 할 것이다.

임의 폴더를 하나 생성 후, 다음과 같은 명령어를 입력한다.

npm init
npm i nodemon


이후에 package.json 파일에 스크립트를 하나 추가한다.

...
  "scripts": {
    "nodemon": "npx nodemon --exec node ./index.js"
  },
...


그리고 상위 폴더에 index.js 파일을 만든 뒤에 아무거나 콘솔 로그를 찍고, yarn nodemon을 터미널에 입력 후 실행하게 되면 코딩테스트에 최적화된 환경이 만들어지게 된다. 파일을 수정할 때 마다 프로그램이 실행되어서, 따로 컴파일을 할 필요가 없어지고 결과도 바로바로 나오게 된다.

대강 이런 식으로 뜬다.

다음으로는 많이 쓰는 JS 스킬을 정리하자.

 

 

 

알아두면 좋은 잡지식


 

컨벤션 통일하기

// 개인적으로 var는 사용하지 않는다. mutable하면 let, immutable하면 const
let a = 1;
const b = 2;

// js는 세미콜론 안써도 된다고 하지만, 쓰는 것을 적극 권장함
let c = 3 	// (x)
let d = 3;

외부 에디터를 사용 가능하게하는 환경이라면, vscode에 prettier나 eslint 정도는 설정해 두자.

세미콜론을 써야하는 이유 : 코드 맨 왼쪽에 소괄호 또는 중괄호로 시작하는 곳이 있을 때, 바로 윗줄 코드와 섞일 수 있다!
https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/

 

Why explicit semicolons are important in JavaScript

> I am in "Effective JavaScript" training at @PayPalEng [https://twitter.com/PayPalEng?ref_src=twsrc%5Etfw] by Douglas Crockford and cannot express what an enlightening experience it has been! I realized today why using explicit semi-colons is so important

www.freecodecamp.org

 

변수의 이름과 내용 같이 보이게 하기

const value = '안녕하세요'
console.log({ value })

 

테스트 값 바로 사용하기

const solution = (input) => {
	const {x, y} = input;
    
    // 전체내용 복사&붙여넣기
}

const case1 = {
	x : 1,
	y : 2
}

solution(case1)

 

배열 미리 정의하기 (탐색 문제)

// 10 크기 가지는 빈 배열 arr
let arr = new Array(10)

// arr는 10x10의 이중 배열, 모든 값이 true
for(let i = 0; i < arr.length; i++) {
	arr[i] = new Array(arr.length).fill(true)
}

 

 

스택

const stack = [];

// 스택 push
stack.push(1);

// 스택 pop
const back = stack.pop()

 

const queue = [];

// push
queue.push(1);

// pop
const front = queue.shift();

주의할 점은, shift 방식은 링크드 리스트 방식이 아닌, 배열을 이용해서 queue를 흉내 내는 것이기 때문에 컴파일러에서 어느정도 시간복잡도 보정이 들어가겠지만, 이론상 O(N) 의 시간 복잡도를 가진다. 즉, queue의 적절한 크기 내에서는 shift()를 사용해도 크게 문제는 없으나, queue의 크기가 커질수록 시간복잡도가 늘어날 것이다.
https://stackoverflow.com/questions/22614237/javascript-runtime-complexity-of-array-functions

 

JavaScript runtime complexity of Array functions

Is the runtime complexity defined by the JS standard on common Array functions like push, pop, shift, slice or splice? Esp. I'm interested in removing and inserting entries at random positions. If ...

stackoverflow.com

 

 

명시적 boolean 반환하기

const a = undefined;
const b = NaN;
const c = null;
const d = [];
const e = {};
const f = Infinity;

console.log(!!a); // false
console.log(!!b); // false
console.log(!!c); // false
console.log(!!d); // true
console.log(!!e); // true
console.log(!!e.value); // false
console.log(!!f); // true

 

진수 변환하기

// 10진수 -> n진수
const a = 127;
console.log({ a });
const b = a.toString(2);
console.log({ b });
const c = a.toString(4);
console.log({ c });
const d = a.toString(16);
console.log({ d });


/*
{ a: 127 }
{ b: '1111111' }
{ c: '1333' }
{ d: '7f' }
*/

// n진수 -> 10진수
const e = parseInt(b, 2);
console.log({ e });
const f = parseInt(c, 4);
console.log({ f });

/*
{ e: 127 }
{ f: 127 }
*/

number에서 진수변환을 한 결과는 string이 된다.

2^n 판별하기

const a = 128;
const is2N = !(a & (a - 1));
console.log({ is2N });

2의 n승을 2진수로 변환해보자.

2^2 = 4 = '100'
2^4 = 16 = '10000'
2^5 = 32 = '100000'

모든 숫자들이 첫째 자리를 제외하고 모두 0이다. 이 숫자들에서 1을 뺀 숫자들은 모두 1을 가질 것이다. 즉, 100 & 011 => 000 , 10000 & 01111 => 00000 결과가 나오게 된다. 이를 응용하면 비트연산으로 쉽게 구할 수 있다.

함수 인자 변경하지 않기

함수 인자는 예상치 못한 결과를 가져올 수도 있기 때문이다. (Side Effect : 통상적으로 의도하지 않은 결과라는 뜻이다) 새로운 객체를 만들어서 복사한 다음 사용하자.

배열 내 중복 원소 제거하기

const arr = [1, 2, 3, 4, 3, 4, 2, 1];
console.log({ arr });
const newArr = Array.from(new Set(arr));
console.log({ newArr });

/*
{
  arr: [
    1, 2, 3, 4,
    3, 4, 2, 1
  ]
}
{ newArr: [ 1, 2, 3, 4 ] }
*/

 

합집합, 교집합, 차집합

const set1 = new Set([1, 2, 3]);
const set2 = new Set([1, 4, 6]);

// 합집합
const union = new Set([...set1, ...set2]);
// 교집합
const intersection = new Set([...set1].filter((x) => set2.has(x)));
// 차집합 (A-B)
const difference1 = new Set([...set1].filter((x) => !set2.has(x)));
// 차집합 (B-A)
const difference2 = new Set([...set2].filter((x) => !set1.has(x)));

 

참고자료


https://developer.mozilla.org/ko/docs/Web/JavaScript

 

JavaScript | MDN

JavaScript (JS)는 가벼운, 인터프리터 혹은 just-in-time 컴파일 프로그래밍 언어로, 일급 함수를 지원합니다. 웹 페이지를 위한 스크립트 언어로 잘 알려져 있지만, Node.js, Apache CouchDB, Adobe Acrobat처럼

developer.mozilla.org

 

반응형