JavaScript style for optional callbacks

后端 未结 10 1727
日久生厌
日久生厌 2020-12-02 07:30

I have some functions which occasionally (not always) will receive a callback and run it. Is checking if the callback is defined/function a good style or is there a better w

10条回答
  •  感情败类
    2020-12-02 07:37

    Rather than make the callback optional, just assign a default and call it no matter what

    const identity = x =>
      x
    
    const save (..., callback = identity) {
      // ...
      return callback (...)
    }
    

    When used

    save (...)              // callback has no effect
    save (..., console.log) // console.log is used as callback
    

    Such a style is called continuation-passing style. Here's a real example, combinations, that generates all possible combinations of an Array input

    const identity = x =>
      x
    
    const None =
      Symbol ()
    
    const combinations = ([ x = None, ...rest ], callback = identity) =>
      x === None
        ? callback ([[]])
        : combinations
            ( rest
            , combs =>
                callback (combs .concat (combs .map (c => [ x, ...c ])))
            )
    
    console.log (combinations (['A', 'B', 'C']))
    // [ []
    // , [ 'C' ]
    // , [ 'B' ]
    // , [ 'B', 'C' ]
    // , [ 'A' ]
    // , [ 'A', 'C' ]
    // , [ 'A', 'B' ]
    // , [ 'A', 'B', 'C' ]
    // ]

    Because combinations is defined in continuation-passing style, the above call is effectively the same

    combinations (['A', 'B', 'C'], console.log)
    // [ []
    // , [ 'C' ]
    // , [ 'B' ]
    // , [ 'B', 'C' ]
    // , [ 'A' ]
    // , [ 'A', 'C' ]
    // , [ 'A', 'B' ]
    // , [ 'A', 'B', 'C' ]
    // ]
    

    We can also pass a custom continuation that does something else with the result

    console.log (combinations (['A', 'B', 'C'], combs => combs.length))
    // 8
    // (8 total combinations)
    

    Continuation-passing style can be used with surprisingly elegant results

    const first = (x, y) =>
      x
    
    const fibonacci = (n, callback = first) =>
      n === 0
        ? callback (0, 1)
        : fibonacci
            ( n - 1
            , (a, b) => callback (b, a + b)
            )
            
    console.log (fibonacci (10)) // 55
    // 55 is the 10th fibonacci number
    // (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...)

提交回复
热议问题