cosim
v1.0.4
Published
Compute the cosine similarity of two vectors. Fully typed, 0 dependencies.
Downloads
25
Maintainers
Readme
Cosim
Compute the cosine similarity of two vectors. Useful when working with LLMs. Fully typed, zero dependencies.
Install
npm install cosim
Usage
You can specify vectors as arrays, or as Javascript objects with string keys and number values.
Constraints:
- Both arguments must have the same type: you can't compare objects with arrays.
- Vectors must have the same length.
- Vector values must be numbers.
Example usage
With objects:
import { similarity } from "cosim"
const result = similarity(
{ x: 1, y: 3, z: -5},
{ x: 4, y: -2, z: -1 }
).toFixed(3); // 0.111
With arrays:
const result = similarity(
[0.1, 0.5, 0.9],
[0.3, 0.8, 0.2]
).toFixed(3); // 0.672
The library also exposes its helper for computing the dot product of two vectors:
const result = dotProduct({ x: -1, y: -2 }, { x: -3, y: -4 });
console.log(result) // 11
Contributing
This uses pnpm
for package management and tsup
for bundling.
To contribute:
pnpm install
- Make your changes in
src
pnpm build
- Add new tests in
test
- Submit a PR 🥳