Passing a math operator as a parameter

前端 未结 6 1300
长发绾君心
长发绾君心 2021-01-03 18:45

I\'d like to write a function in Javascript that allows me to pass in a mathematical operator and a list of ints and for each item in that list, apply the operator to it.

6条回答
  •  梦谈多话
    2021-01-03 18:58

    I know this is an old question. Just adding some more information.

    If you often use operators and need to reduce the results (accumulate), it is highly recommended to develop different helpers, so you can quickly use any input form to obtain the results.

    Although, this will not be always the case when you use reduce, the following helper will allow to pass the first element of your array as default value:

    reducer = (list, func) => list.slice(1).reduce(func, list.slice(0, 1).pop())
    

    The above, still has a function dependency, so you still need to declare the specific function that wraps your target operator:

    sum = list => reducer(list, (a, b) => a + b)
    sum([1, 2, 3, 4, 5])
    

    You could then redefine sum, for example, as per new input formats you see will be backwards compatible. In this example by using a new helper, flat (still experimental as per now; added the code):

    flat = (e) => Array.isArray(e) ? [].concat.apply([], e.map(flat)) : e
    
    sum = (...list)  => reducer(flat(list), (a, b) => a + b)
    mult = (...list) => reducer(flat(list), (a, b) => a * b)
    
    sum([1, 2, 3, 4, 5])
    sum(1, 2, 3, 4, 5)
    
    mult([1, 2, 3, 4, 5])
    mult(1, 2, 3, 4, 5)
    

    Then you can use reducer (or any variant you may find more useful) to simplify the definition of other helpers as well. Just one last example with matrix custom operators (in this case, they are functions):

    zip  = (...lists) => lists[0].map((_l, i) => lists.map(list => list[i]))
    dot_product = (a, b) => sum(zip(a, b).map(x => mult(x)))
    
    mx_transpose = (mx) => zip.apply([], mx)
    // the operator
    mx_product = (m1, m2) =>
        m1.map(row => mx_transpose(m2).map(
             col => dot_product(row, col) ))
    // the reducer
    mx_multiply = (...mxs) => reducer(mxs, (done, mx) => mx_product(done, mx))
    
    A = [[2, 3, 4],
         [1, 0, 0]]
    B = [[0, 1000],
         [1,  100],
         [0,   10]]
    C = [[2,   0],
         [0, 0.1]]
    
    JSON.stringify(AB   = mx_product (A,  B))
    JSON.stringify(ABC  = mx_product (AB, C))
    JSON.stringify(ABC2 = mx_multiply(A, B, C))
    

提交回复
热议问题