find-closest
Version:
Like Array.prototype.find, but for finding the closest match.
3 lines (2 loc) • 722 B
JavaScript
const e=(e,t,n)=>{let r={index:-1,distance:Number.POSITIVE_INFINITY,value:0};for(let o=0;o<e.length;o++){const a=e[o];let i;if(n){const r=n(a,{index:o,target:t,collection:e});switch(r){case!1:continue;case!0:if("number"!=typeof a)throw new TypeError(`\`filterMapFn\` returned \`true\` for non-number value \`${a}\`.`);i=a;break;default:i=r}}else{if("number"!=typeof a)throw new TypeError(`Array contains non-number value \`${a}\` without a \`filterMapFn\` to map it to a number.`);i=a}const u=Math.abs(i-t);if(0===u)return o;u<r.distance&&(r={index:o,distance:u,value:i})}return r.index},t=e,n=(...t)=>t[0][e(...t)];export default n;export{n as findClosest,t as findClosestIndex};
//# sourceMappingURL=index.modern.js.map