UNPKG

@allemandi/embed-utils

Version:

Fast, type-safe utilities for vector embedding comparison and search.

3 lines (2 loc) 2.14 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).allemandi=t.allemandi||{},t.allemandi.embedUtils={}))}(this,function(t){"use strict";function e(t,e){let n=0,o=0,i=0;for(let r=0;r<t.length;r++){const s=t[r],l=e[r];n+=s*l,o+=s*s,i+=l*l}const r=Math.sqrt(o)*Math.sqrt(i);return 0===r?0:n/r}function n(t,e){let n=0;for(let o=0;o<t.length;o++){const i=t[o]-e[o];n+=i*i}return Math.sqrt(n)}function o(t,e){let n=0;for(let o=0;o<t.length;o++)n+=Math.abs(t[o]-e[o]);return n}t.computeCosineSimilarity=e,t.computeEuclideanDistance=n,t.computeManhattanDistance=o,t.findNearestNeighbors=function(t,i,r={}){const{topK:s,threshold:l,method:a="cosine"}=r,c=void 0!==s?s:void 0!==l?i.length:1,f=[];let u,d,h;switch(a){case"euclidean":u=n,d=!0,h="distance";break;case"manhattan":u=o,d=!0,h="distance";break;default:u=e,d=!1,h="similarityScore"}for(const e of i){const n=u(t,e.embedding);if(void 0!==l){(d?n<=l:n>=l)&&f.push({...e,[h]:n})}else f.push({...e,[h]:n})}return f.sort((t,e)=>{if("similarityScore"===h||"distance"===h){const n=t[h]??0,o=e[h]??0;return d?n-o:o-n}return 0}),f.slice(0,c)},t.isNormalized=function(t,e=1e-6){let n=0;for(let e=0;e<t.length;e++){const o=t[e];n+=o*o}return Math.abs(n-1)<=e},t.meanVector=function(t){const e=t.length;if(0===e)return[];const n=t[0].length,o=new Array(n).fill(0);for(let i=0;i<e;i++){const e=t[i];for(let t=0;t<n;t++)o[t]+=e[t]}for(let t=0;t<n;t++)o[t]/=e;return o},t.normalizeVector=function(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];const n=Math.sqrt(e);if(0===n)return t.slice();const o=new Array(t.length);for(let e=0;e<t.length;e++)o[e]=t[e]/n;return o},t.rankBySimilarity=function(t,i,r={}){const{method:s="cosine"}=r;let l,a,c;switch(s){case"euclidean":l=n,a=!0,c="distance";break;case"manhattan":l=o,a=!0,c="distance";break;default:l=e,a=!1,c="similarityScore"}const f=new Array(i.length);for(let e=0;e<i.length;e++)f[e]={...i[e],[c]:l(t,i[e].embedding)};return f.sort((t,e)=>a?t[c]-e[c]:e[c]-t[c]),f}}); //# sourceMappingURL=index.umd.js.map