# Set Similarity

> NumKong for JavaScript

Binary metrics operate on packed storage rather than on generic boolean arrays.

```ts
import { toBinary, hamming, jaccard } from "numkong";

const a = toBinary(new Float32Array([1, -2, 3, -4, 5, -6, 7, -8]));
const b = toBinary(new Float32Array([1, 2, -3, -4, 5, 6, -7, -8]));

console.log(hamming(a, b));
console.log(jaccard(a, b));
```

This is a natural model for sign-quantized embeddings and semantic hashes.

`import * as numkong from 'numkong';`

## hamming

Computes the bitwise Hamming distance between two vectors.

```typescript
function hamming(
    a: Uint8Array | BinaryArray | TensorBase,
    b: Uint8Array | BinaryArray | TensorBase,
): number
```

Both vectors are treated as bit-packed, u1 dtype, where each byte holds 8 bits.

Use [`toBinary`](#toBinary) to convert numeric arrays to bit-packed format.

- `a`: The first bit-packed vector, as Uint8Array, BinaryArray, or TensorBase.
- `b`: The second bit-packed vector, matching the length of `a`.

## jaccard

Computes the bitwise Jaccard distance between two vectors.

```typescript
function jaccard(
    a: Uint8Array | BinaryArray | TensorBase,
    b: Uint8Array | BinaryArray | TensorBase,
): number
```

Both vectors are treated as bit-packed, u1 dtype, where each byte holds 8 bits.

Use [`toBinary`](#toBinary) to convert numeric arrays to bit-packed format.

- `a`: The first bit-packed vector, as Uint8Array, BinaryArray, or TensorBase.
- `b`: The second bit-packed vector, matching the length of `a`.

## toBinary

Quantizes a numeric vector into a bit-packed binary representation.

```typescript
function toBinary(
    vector: Float32Array | Float64Array | Int8Array,
): Uint8Array
```

Converts each element to a single bit, 1 for positive values and 0 for non-positive ones, with
element 0 in the most significant bit of byte 0, matching [`BinaryArray`](https://www.unum.cloud/docs/numkong/javascript/scalar-types.md#BinaryArray) and the C
`nk_u1x8_t`. This is the required format for [`hamming`](#hamming) and [`jaccard`](#jaccard) distance
functions. Dimension count must be a multiple of 8, the dimensions per byte.

- `vector`: The vector to quantize and pack.

Examples: ```
const vec = new Float32Array([1.5, -2.3, 0.0, 3.1, -1.0, 2.0, 0.5, -0.5]);
const binary = toBinary(vec);
// Result: Uint8Array([0b10010110]) = [0x96]
//   bits 7..0: [1, 0, 0, 1, 0, 1, 1, 0] for elements [+, -, 0, +, -, +, +, -]

// Use with Hamming distance
const a = toBinary(new Float32Array([1, 2, 3, 4, 5, 6, 7, 8]));
const b = toBinary(new Float32Array([1, -2, 3, 4, 5, 6, 7, 8]));
const dist = hamming(a, b); // Counts differing bits
```

