[Leetcode/30days of JS] ToBe Or NotToBe

Song·2024년 7월 9일
post-thumbnail

🎯 About Problem

/**
 * @param {string} val
 * @return {Object}
 */
var expect = function(val) {
    return {
        x : val,
        notToBe : function(key){
            if (this.x === key) {
                throw new Error("Equal");
            }
            return true;
        },
        toBe : function(key){
            if (this.x !== key) {
                throw new Error("Not Equal");
            }
            return true;
        }
    }
};

The problem was about writing a function that returns an object with two functions
1. toBe returns true when two given numbers are equal otherwise throw error with a message 'Not Equal'
2. notToBe returns true when two given number are not equal otherwise throw error with a message 'Equal'

The function expect, above the code, acts as a factory function, a function returning an object (in this case, with two functions).

Its time complexity is O(1) as it only creates an object and does not perform any iterative or recurssive action.

The space complexity is also O(1) as it only creates exactly one object with two methods regardless the size or the complexity of input value. Therefore, the amount of memory to execute this function does not need to scale the size, resulting in constant space complexity.

👩‍💻 What I Learned

Higer-Order Function

  • operates other functions either by taking them as arguement or returning them

Factory Function

  • returns an object instance
  • crucial in functional programme as it provides a way to encapsulate and reuse code

Method Chaining

  • performs multiple methods in one statement
  • this is possible when each method returns an object

The problem and the answer themselves are very simple.
Yet, it taught me a fundemental javascript.

Coding might be simple but explaining how code works technically is another challenge.

Keep learning, own the technique

profile
Learn From Yesterday, Live Today, Hope for Tomorrow

0개의 댓글