LeetCode JavaScript 30 Days Challenge – Day8 – 2666. Allow One Function Call

    LeetCode JavaScript 30 Days ChallengeLeetCode Js-Array

    Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.
    The first time the returned function is called, it should return the same result as fn.
    Every subsequent time it is called, it should return undefined.

    給予一個函式 fn,回傳一個新的且與原始函數相同的函式,而它確保 fn 最多被調用一次。
    第一次呼叫回傳的函式時,它應該回傳與 fn 相同的結果。
    隨後每次呼叫它時,它都應該回傳 undefined。
    

    Example 1:

    Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
    Output: [{"calls":1,"value":6}]
    

    Example 2:

    Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
    Output: [{"calls":1,"value":140}]
    

    solution:
    建立 condition 的變數來存放 Boolean,以表達狀態的切換,當第一次執行 fn 時,
    即觸發狀態變更,並於之後的陣列元素傳入時回傳 undefined。

    Code 1: BigO(1)

    var once = function(fn) {
        let condition = false
    
        return function(...args) {
            if (condition) {
                return undefined;
            } else {
                condition = true
                return fn(...args);
            }
        }
    };
    

    FlowChart:
    Example 1

    Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
    
    condition = false, condition = true, return fn(...args) //1 + 2 + 3
    condition = true, return undefined
    

    Example 2

    Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
    
    condition = false, condition = true, return fn(...args) //5 * 7 * 4
    condition = true, return undefined
    condition = true, return undefined
    

    Code 2: BigO(1)

    var once = function(fn) {
      let hasBeenCalled = false;
      return function(...args){
        if (!hasBeenCalled) {
          hasBeenCalled = true;
          return fn(...args);
        }
      }
    };
    

    Code 3: BigO(1)

    var once = function(fn) {
        let condition = false
    
        return function(...args) {
            if (condition) {
                return undefined;
            } else {
                condition = true
                return fn.apply(this, args);
            }
        }
    };