QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Dot Product

Computes the dot product of two vectors, which is the sum of the products of corresponding elements.

  • math
  • vector-algebra

Install

npx shadcn@latest add https://quicksnip.dev/r/dot-product.json

This snippet is not verified yet. Review it before use, or help verify it.

Code

function dotProduct(a, b) {
    if (a.length !== b.length) {
        throw new Error('Vectors must be of the same length');
    }

    return a.reduce((sum, value, index) => sum + value * b[index], 0);
}

Usage

dotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32