Processing math: 100%

문제

Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions.

The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))).

The function composition of an empty list of functions is the identity function f(x) = x.

You may assume each function in the array accepts one integer as input and returns one integer as output.

https://leetcode.com/problems/function-composition/

 

예시

functions에 있는 각 함수들을 뒤에서부터 실행하면 된다. 주어진 x 값을 이용하여 x의 값을 업데이트한다.

 

코드

/**
 * @param {Function[]} functions
 * @return {Function}
 */

Array.prototype.myReverse = function(){
    return this.map((item,idx) => this[this.length-1-idx]);
}

var compose = function(functions) {
    
    return function(x) {
        let value = x;
        
        functions.myReverse().forEach((fn)=>{
            value = fn(value);
        });
        
        return value;
    }
};

/**
 * const fn = compose([x => x + 1, x => 2 * x])
 * fn(4) // 9
 */

 

함수 배열의 순서를 바꾼 뒤, 바뀐 함수 배열을 돌면서 value 값을 업데이트 했다.

Array.prototype.reverse()가 존재하지만, 직접 구현해보고 싶었다. (추가적으로, reverse()가 좀 느리지 않을까라는 생각이 들었다. 관련해서는 참고 링크를 보면 좋을 것 같다.)

 

 

참고 링크

https://medium.com/@toaonly42/array-prototype-reverse-%EA%B0%80-%EC%B5%9C%EC%84%A0%EC%9D%B8%EA%B0%80-5acb17e315d3

 

Array.prototype.reverse 가 최선인가?

🤔 뜬금없는 의문,

medium.com

https://gurtn.tistory.com/121

 

[JS] 반복문 (for, forEach 등) 속도 비교

JavaScript의 반복문으로 for loop 문, forEach 메서드, map 메서드, reduce 메서드, .each(Jquery).forloopforEachmapreduce.each 속도 비교에 사용할

gurtn.tistory.com

 

728x90

문제

Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element.

This result is achieved through the following operations: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The ultimate value of val is then returned.

If the length of the array is 0, the function should return init.

Please solve it without using the built-in Array.reduce method.

https://leetcode.com/problems/array-reduce-transformation/

 

예시

input으로 nums 배열과 reduce로 실행할 함수, 그리고 초기 값을 받는다. accum은 fn에서 리턴한 값이 들어가고, curr은 nums 배열에 있는 숫자가 들어간다.

 

코드

/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function(nums, fn, init) {
    if(nums.length === 0) return init;
    
    let accum = init;
    nums.forEach((num)=>{
        accum = fn(accum, num);
    });
    
    return accum;
};

문제에 적혀있는 대로, nums 배열의 길이가 0이면 초기 값을 리턴한다.

fn(accum, curr)에서 accum은 앞선 실행됐던 fn의 결과 값이고, curr은 현재 nums 배열에 있는 숫자이다. for문을 돌면서 nums에서 각 숫자가 fn의 curr로 들어갈 수 있도록 하였고, fn의 결과를 accum 변수에 저장해주었다.

728x90

문제

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

+ Recent posts