Here's a TypeScript implementation of the k-medoids algorithm for data points that are sets of generic elements. This implementation uses the Euclidean distance as the distance metric and assumes that input data is an array of arrays containing numerical values.
typescript
type DataPoint<T> = T[];
type Cluster<T> = { medoid: DataPoint<T>; points: DataPoint<T>[] };
function euclideanDistance(a: number[], b: number[]): number {
let sum = 0;
for (let i = 0; i < a.length; i++) {
sum += Math.pow(a[i] - b[i], 2);
}
return Math.sqrt(sum);
}
function totalCost<T>(clusters: Cluster<T>[], distanceFn: (a: T[], b: T[]) => number): number {
let cost = 0;
for (const cluster of clusters) {
for (const point of cluster.points) {
cost += distanceFn(point, cluster.medoid);
}
}
return cost;
}
function findClosestMedoid<T>(point: DataPoint<T>, medoids: DataPoint<T>[], distanceFn: (a: T[], b: T[]) => number): number {
let closestIndex = 0;
let closestDistance = distanceFn(point, medoids[0]);
for (let i = 1; i < medoids.length; i++) {
const distance = distanceFn(point, medoids[i]);
if (distance < closestDistance) {
closestIndex = i;
closestDistance = distance;
}
}
return closestIndex;
}
function swapMedoids<T>(clusters: Cluster<T>[], i: number, j: number): void {
const tempMedoid = clusters[i].medoid;
clusters[i].medoid = clusters[j].medoid;
clusters[j].medoid = tempMedoid;
}
function kMedoids<T>(data: DataPoint<T>[], k: number, distanceFn: (a: T[], b: T[]) => number = euclideanDistance): Cluster<T>[] {
const initialMedoids: DataPoint<T>[] = [];
for (let i = 0; i < k; i++) {
initialMedoids.push(data[Math.floor(Math.random() * data.length)]);
}
let clusters: Cluster<T>[] = initialMedoids.map((medoid) => ({ medoid, points: [] }));
let oldCost = Infinity;
while (true) {
// Assign points to the closest medoid.
for (const point of data) {
const closestMedoidIndex = findClosestMedoid(point, clusters.map((c) => c.medoid), distanceFn);
clusters[closestMedoidIndex].points.push(point);
}
// Calculate the total cost of the current clustering.
const newCost = totalCost(clusters, distanceFn);
// If the cost hasn't changed, then we've converged to a local minimum.
if (newCost === oldCost) {
break;
}
oldCost = newCost;
// Try swapping each pair of medoids and see if it improves the cost.
for (let i = 0; i < k; i++) {
for (let j = i + 1; j < k; j++) {
swapMedoids(clusters, i, j);
const swapCost = totalCost(clusters, distanceFn);
if (swapCost >= oldCost) {
swapMedoids(clusters, i, j); // Undo the swap.
} else {
oldCost = swapCost;
}
}
}
// Reset the points in each cluster for the next iteration.
for (const cluster of clusters) {
cluster.points = [];
}
}
return clusters;
}
Here's an example of how to use this implementation:
“Implement k-medoids algorithm in TypeScript for data points that are sets of generic….” Conversation with mistral-large-2402, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m850za57wd3q8d39pyn06jwk