identify-media
Version:
Analyse file path and content to make search criteria for media APIs
49 lines (41 loc) • 1.56 kB
text/typescript
const initBlock = (size: number): number[] => {
let temp = size;
const longs: number[] = [];
for (let i = 0; i < 8; i++) {
longs[i] = temp & 255;
temp = temp >> 8;
}
return longs;
}
const processChunk = (chunk: string, init: number[]): number[] => {
return chunk.split('').reduce((result, current, index): number[] => {
const idx = (index + 8) % 8;
return result.slice(0, idx).concat(result[idx] + current.charCodeAt(0)).concat(result.slice(idx+1));
}, init);
}
interface Normalized {
normalized: number[];
overflow: number;
}
const longsToBin = (longs: number[]): number[] => {
return longs.reduce((result, current): Normalized => {
const sum = current + result.overflow;
const overflow = sum >> 8;
return {
normalized: result.normalized.concat(sum & 255),
overflow
}
}, {normalized: [], overflow: 0} as Normalized).normalized;
}
const bin2hex = (longs: number[]): string => {
const hexString = '0123456789abcdef';
return longsToBin(longs).reverse().reduce((result, current): string => {
return result + hexString.charAt(current >> 4 & 15) + hexString.charAt(current & 15);
}, '');
}
export const makeHash = (size: number, firstChunk: Promise<string>, secondChunk: Promise<string>): Promise<string> => {
return firstChunk
.then((chunk) => processChunk(chunk, initBlock(size)))
.then((longs) => secondChunk.then((chunk) => processChunk(chunk, longs)))
.then(bin2hex);
}