[JavaScript] 기술면접 라이브 코딩 대비 I

Chaejung·2022년 7월 26일
50
post-thumbnail

JavaScript로 라이브 코딩을 하는 면접을 대비하여 문제를 정리합니다.
참고로 라이브 코딩할 때 쓰는 web IDE로는 codepen을 쓴다.

1. concat

<문제>

다음 함수를 구현하세요.

duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]

<답>

function duplicate(arr) {
  return arr.concat(arr);
}

2. closure+anonymous function

<문제>

다음 함수를 구현하세요.

sum(1)(2)(); /// 3
sum(1)(2)(3)(4)(); // 10

mul(2)(3)(4); // 24
mul(4)(3)(4); // 48

<답>
이 문제는 사실 처음 봤을 때 오타가 난 줄 알았다.
괄호 다음에 괄호...? 이게 뭔데...?
하지만 closure를 이용하면 구현 가능하다.

closure:
함수 내에서 함수를 바로 실행시키는 대신, 반환값으로 함수를 내보낸다.

function greeting() {
    let message = 'Hi';
    function sayHi() {
        console.log(message);
    }
    return sayHi;
}
let hi = greeting();
hi(); // === greeting()()

// 재귀+closure
const sum  = function (a) {
  return function (b) {
    if (b) {
      return sum(a+b);
    }
    return a; 
  }
};


// closure
function mul (x) {
  return function (y) { 
    return function (z) { 
      return x * y * z;
    };
  };
}

3. closure

<문제>

createBase(integer)를 구현하세요.

var addSix = createBase(6);
addSix(10); // returns 16
addSix(21); // returns 27

<답>
이 문제도 함수 밖에 선언된 수를 가져와야하기 때문에 closure를 이용하여 접근한다.

function createBase(baseNumber) {
  return function(N) {
    // 함수 바깥에서 선언된 N(==addSix(N))이라도,
    // Closure를 이용하면 가져올 수 있다.
    return baseNumber + N;
  }
}

4. 비동기

<문제>

delay 함수를 구현하세요.

const delay = () => {}

const main = async() => {
	console.log('1번')
  	delay(4)
    // 첫번째 콘솔('1번')이 찍힌 후 4초 후에 찍힘`
  	// output 
  	// '1번'
    // ...4초 후...
  	// '2번!!!'
    console.log('2번!!!')
  };
main();

<답>
main을 건들지 않고, 별도의 delay를 구현하려면,
비동기+closure로 풀면된다.

function delay(n) {
  return new Promise(function(resolve){
    setTimeout(resolve, n*1000);
  });
}

const main = async() => {
	console.log('1번')
  	await delay(4)
  	console.log('2번!!!')
  };
main();

// output 
// '1번'
// ...4초 후...
// '2번!!!'

5. array 중복 요소 제거

<문제>

array의 중복 요소를 제거한 뒤 출력하세요.

<답>

const exampleArray = [4, 2, 9, 2, 4, 6, 8, 9]

const uniqueArray = exampleArray.filter((element, index) => {
  	// indexOf는 array의 가장 처음에 나온 index를 반환하기 때문에 매개변수 index와 같지 않으면 뒤에 것들은 전부 탈락된다 
	return exampleArray.indexOf(element) === index;
})

console.log(uniqueArray) // [4,2,9,6,8]

6. str 중복 요소 제거

<문제>

문자열의 중복 요소를 제거한 뒤 출력하세요.

<답>

const exampleStr = 'aabbbeedudaacca'

// solution I
// 문자열을 하나씩 검사하기, indexOf를 이용하는 것은 5번과 동일
function removeRepeat(str) {
  let answer = ""
  for (let i=0; i<str.length; i++) {
    if (i === str.indexOf(str[i])) answer += str[i];
  }
  return answer;
}

console.log(removeRepeat(exampleStr)) // "abeduc"

// solution II
// 문자열을 리스트로 바꾸기
const uniqueStr = exampleStr
                  .split("")
                  .filter((element, index) => {
                    return exampleStr.indexOf(element) === index;
                  })
                  .join("")

console.log(uniqueStr) // "abeduc"

7. 문자열 뒤집기

<문제>

주어진 문자열을 뒤집어 출력하세요.

  1. 글자별로 뒤집기
  2. 단어별로 뒤집기

<답>

let string = "Hello! Welcome to my Velog. Ask me anything.";

function reverseBySeparator(string, separator) {
  return string.split(separator).reverse().join(separator);
}

let reverseEntireSentence = reverseBySeparator(string, "");

let letreverseEachWord = reverseBySeparator(reverseEntireSentence, " ");


console.log(reverseEntireSentence) // ".gnihtyna em ksA .goleV ym ot emocleW !olleH"
console.log(letreverseEachWord) // "!olleH emocleW ot ym .goleV ksA em .gnihtyna"

8. Math.max⭐️

<문제>

숫자형 array를 매개변수로 갖게 하고, Math.max를 활용해 최댓값을 출력하세요.
(단, 스프레드 연산자를 쓰지 않고)

<답>

여기서 apply를 쓰지 않고, Math.max(null, exampleArray)를 하면 NaN이 출력된다.
왜냐하면, Math.max()는 숫자형만 파라미터로 갖기 때문이다.

따라서 array로 Math.max를 호출하는 형태를 가지는 apply를 쓰거나,

자세한 apply 사용법

하나씩 검사해서 그때그때 최댓값을 반환하는 reduce를 써야한다.

이 둘의 차이는 apply는 상대적으로 적은 개수의 원소에서만 적용해야한다는 것.

왜냐하면 apply(그리고 스프레드 연산자 포함)는 array 원소를 함수 파라미터로 넘기려하기 때문이다.
정확히는 10,000개 이상의 원소(라고 하지만 직접 실행해본 결과 10만 개 이상)일 때 이들이 함수 인수로 전부 넘어가 버리면 JS의 엔진의 인수 한계에 부딪히기 때문에 오류 또는 잘못된 값이 나올 수 있다.

출처: mdb web docs_Function.prototype.apply()

그래서 원소 값이 대략 10만 개가 넘어간다면, reduce로 구현하는 게 맞다.

const exampleArray = [4, 2, 8, 1, 1, 3]

// solution I
console.log(Math.max.apply(null, exampleArray)) // 8


// solution II
const max = exampleArray.reduce(function(a, b) {
  return Math.max(a, b);
}, -Infinity);

console.log(max) // 8

9. Is Array?

<문제>

어떤 데이터의 타입이 array인지 아닌지 판별하세요.

<apply와 call의 차이>
작동은 거의 동일하나, call은 인수들의 모음을 받고, apply는 인수들의 모음의 단일 리스트를 받는다
ex. func.apply(this, ['eat', 'bananas']), func.call(this, 'eat', 'bananas')

출처: mdn web docs_Function.prototype.call()

<답>


let example01 = []
let example02 = ['Hi']
let example03 = 'Hi'
let example04 = 17

// solution I
function isArray01 (arrayList) {
  // 데이터의 타입을 뱉어내는 'Object.prototype'
  if(Object.prototype.toString.call(arrayList) === '[object Array]') {
    console.log('Array!');
	} else {
    console.log('Not Array!');
   }
}

// solution II
function isArray02 (arrayList) {
  	// isArray() 메서드 이용하기
	console.log(Array.isArray(arrayList))
}

isArray01(example01) // "Array!"
isArray02(example01) // true
isArray01(example02) // "Array!"
isArray02(example02) // true
isArray01(example03) // "Not Array!"
isArray02(example03) // false
isArray01(example04) // "Not Array!"
isArray02(example04) // false

출처

25+ JavaScript Coding Interview Questions (SOLVED with CODE)

JavaScript Interview Questions

profile
프론트엔드 기술 학습 및 공유를 활발하게 하기 위해 노력합니다.

11개의 댓글

comment-user-thumbnail
2022년 8월 5일

안녕하세요 글 너무 잘봤습니다! 혹시 여기서 써주신 문제들 출처는 어디인지 알수 있을까요?
이런식으로 함수 짜는 법을 연습을 하고싶은데 이런 문제들을 좀 더 접하고싶어서요..! 답변해주시면 정말 감사합니다!

1개의 답글
comment-user-thumbnail
2022년 8월 5일

저도 클로저함수 짜는 법 공부를 하고 싶었는데 코드가 너무 도움이 되었습니다!! 감사해요ㅎㅎ

1개의 답글
comment-user-thumbnail
2023년 7월 22일

Nice Information, For more such JavaScript concepts, check this JavaScript Coding Interview Questions

1개의 답글
comment-user-thumbnail
2023년 9월 19일

우왕 타몽님!! 저 기억하실지 모르겠지만 예전에 테오 스프린트 잠깐동안 같이 했었던 엘라라고 해요! 라이브코테 준비하는 블로그 찾고있었는데 타몽님 블로그가 나왔네요 신기해용!!(어디서 많이 본 프사라고 생각했었는데 깃허브 프사였어유!!) 블로그 덕분에 도움 많이 받고 가요~!! 감사합니다 :)

답글 달기