@alttiri/image-hash
Version:
Alt-Image-Hash. An alternative image hashing library.
65 lines (64 loc) • 1.91 kB
JavaScript
// calculateMedianByCountSorting
// calculateMedianBySorting
export const calculateMedian = calculateMedianByCountSorting;
export function calculateMedianBySorting(arr, copy = true) {
if (copy) {
arr = Uint8Array.from(arr);
}
const mid = Math.trunc(arr.length / 2);
arr.sort((a, b) => a - b);
if (arr.length % 2 === 0) {
return (arr[mid - 1] + arr[mid]) / 2;
}
else {
return arr[mid];
}
}
export function calculateMedianByCountSorting(ui8ca) {
let counts /* | number[] */;
if (ui8ca.length > 256) {
// counts = Array.from({length: 256}, () => 0);
if (ui8ca.length > 65536) {
counts = new Uint32Array(256);
}
else {
counts = new Uint16Array(256);
}
}
else {
counts = new Uint8Array(256);
}
const to = ui8ca.length;
for (let i = 0; i < to; i++) { // do not use slow `for of` loop
counts[ui8ca[i]]++;
}
const middle = ui8ca.length / 2;
let passedCount = 0;
for (let i = 0; i < 256; i++) {
const count = counts[i];
passedCount += count;
if (passedCount >= middle) {
if (middle % 1 === 0 && passedCount - middle === 0) {
let nextI = i;
for (let j = i + 1; j < 256; j++) {
if (counts[j]) {
nextI = j;
break;
}
}
return (i + nextI) / 2;
}
return i;
}
}
// If all values in the input array are the same and the input array length is 256 (or 65536).
// (256 incrementing of the same key of Uint8Array results in `0`.)
return ui8ca[0];
}
export function calculateAverage(ui8ca) {
let sum = 0;
for (let i = 0; i < ui8ca.length; i++) {
sum += ui8ca[i];
}
return sum / ui8ca.length;
}