codewar--刷题日记

1.Multiplication Tables

Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.
Example:
multiplication_table(3,3)
1 2 3
2 4 6
3 6 9
–>[[1,2,3],[2,4,6],[3,6,9]]
Each value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.

solution 01

function multiplicationTable(row,col){
  out = []
  for (var i = 1; i <= row; i++)
  {
    temp = []
    // console.log(temp)
    for (var j = 1; j <= col; j++)
    {
      temp.push(i*j)
    }
    out.push(temp)
  }
  return out
}

solution 02

function multiplicationTable(row,col){
  return [...Array(row)].map((_, i) =>
    [...Array(col)].map((_, j) => (i + 1) * (j + 1))
  );
}

2.Unary function chainer

Your task is to write a higher order function for chaining together a list of unary functions. In other words, it should return a function that does a left fold on the given functions.
chained([a,b,c,d])(input)
Should yield the same result as
d(c(b(a(input))))

solution

function chained(functions) {
  return function(input) {
    return functions.reduce(function(pre, cur){
      return cur(pre)
    }, input)
  }
}

你可能感兴趣的:(js)