문제

Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.

https://leetcode.com/problems/array-prototype-last/

 

예시

0.1초 후 then 안에 있는 함수가 실행된다.

 

코드

/**
 * @param {number} millis
 * @return {Promise}
 */
async function sleep(millis) {
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            resolve();
        }, millis);
    });
}

/** 
 * let t = Date.now()
 * sleep(100).then(() => console.log(Date.now() - t)) // 100
 */

sleep 함수가 Promise 객체를 반환하도록 하였다. sleep 함수의 인자로 들어온 millis 만큼 지연시킨 후, then에 있는 함수를 실행해야 하기 때문에 setTimeout을 이용하였다. millis 만큼의 시간이 흐르면 일이 성공적으로 끝났음을 알리는 resolve() 함수를 호출한다. 요구사항에서 value를 넘기는 것은 필요하지 않아서 resolve 함수의 인자로 아무 것도 넣어주지 않았다.

728x90

문제

Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.

You may assume the array is the output of JSON.parse.

https://leetcode.com/problems/array-prototype-last/

 

예시

배열의 마지막 원소인 3 이 출력된다.

 

배열이 비어있기 때문에 -1이 출력된다.

 

코드

/**
 * @return {null|boolean|number|string|Array|Object}
 */
Array.prototype.last = function () {
    if (this.length === 0) return -1;

    return this[this.length - 1];
};

/**
 * const arr = [1, 2, 3];
 * arr.last(); // 3
 */

배열이 비어있을 때는 -1을 리턴하고, 나머지 경우에는 배열의 마지막 원소를 리턴하면 되기 때문에 length가 0인 지를 먼저 확인한다. 0일 때 -1을 리턴하도록 하고, 그 외의 경우에는 배열의 마지막 원소를 리턴한다.

728x90

1. gitlab url 클론하기

git clone [gitlab url]

 

2. 클론한 gitlab 프로젝트 안으로 들어가서 원격 저장소 url 변경하기

cd [gitlab 최상단 폴더명]
git remote set-url origin [github url]

 

3. 원격 저장소에 push 하기

git push -u origin master

 

728x90

문제

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).

https://leetcode.com/problems/counter/

 

예시

n이 10일 때, 처음 counter() 메소드를 호출하면 10이 나오고, 또 counter() 메소드를 호출하면 11이 나오고, 또 counter() 메소드를 호출하면 12가 출력된다. 

 

n이 -2일 때 counter()를 5번 호출하면 -2, -1, 0, 1, 2가 출력된다.

 

코드

function createCounter(n: number): () => number {
    return function() {
        return n++;
    }
}


/** 
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */

createCounter의 인수로 n이 들어오고, createCounter는 함수를 리턴한다. 리턴된 함수가 counter 변수에 담긴다.

counter 함수가 호출될 때마다 n을 증가시켜야 하므로, n을 증가시키는 코드가 필요하다. 처음 호출될 때는 n이 출력되어야 하므로, n++로 후위 증감 연산자를 이용한다.

728x90

문제

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

https://leetcode.com/problems/merge-strings-alternately/

 

예시

word1부터 번갈아가면서 string을 합쳐주면 된다. 이때, 더이상 번갈아 합칠 수 없으면, 긴 string의 나머지 부분은 그대로 더해진다.


코드

/**
 * @param {string} word1
 * @param {string} word2
 * @return {string}
 */
var mergeAlternately = function(word1, word2) {
    let words = "";

    const minLen = Math.min(word1.length, word2.length);

    // minLen 만큼은 번갈아 가면서
    for(let i = 0; i < minLen; i++){
        words += word1[i] + word2[i];
    }

    // 나머지 긴 string은 붙이기
    words += word1.length > word2.length ? word1.slice(minLen) : word2.slice(minLen);

    return words;

};

word1과 word2 중 짧은 길이만큼 번갈아서 더해주었다.

그 후, word1과 word2 중 더 긴 길이를 가진 string의 남은 부분을 더해주었다.

Array.prototype.slice() 를 사용하면 배열의 원하는 인덱스부터 끝까지 자를 수 있다.

 

728x90

+ Recent posts