freeCodeCamp Challenge Guide: Vector dot product

Vector dot product


Solutions

Solution 1 (Click to Show/Hide)
function dotProduct(...vectors) {
  // If invalid input, return null
  if (vectors.length != 2) {
    return null;
  }
  if (vectors[0].length != vectors[1].length) {
    return null;
  }

  // Compute dot product
  let sum = 0;
  for (let i = 0; i < vectors[0].length; i++) {
    let prod = 1;
    for (let j = 0; j < 2; j++) {
      prod *= vectors[j][i];
    }
    sum += prod;
  }
  return sum;
}
Solution 2 (Click to Show/Hide)
function dotProduct(...vectors) {
    if (vectors.length != 2 || vectors[0].length != vectors[1].length) {
        return null
    }
    return vectors[0]
      .map((x, i) => x * vectors[1][i])
      .reduce((sum, curr) => sum + curr);
}