From fd79fc7b91bbab89c06e886a65cd3c062027f6a5 Mon Sep 17 00:00:00 2001 From: Richard Walker Date: Thu, 8 Mar 2018 13:09:27 +0100 Subject: [PATCH] feat: add hashArray method --- lib/common.js | 30 ++++++++++++++++++++++++++++++ test/common.test.js | 9 +++++++++ 2 files changed, 39 insertions(+) diff --git a/lib/common.js b/lib/common.js index c84440f..49b7eac 100644 --- a/lib/common.js +++ b/lib/common.js @@ -115,3 +115,33 @@ module.exports.createTemporaryFilename = fileType => { const rand = Math.floor(Math.random() * 1000).toString(); return `tmp-${Date.now().toString()}-${rand}.${fileType}`; }; + +/** + * Hashes an array of hashes into a single hash + * + * @param {string[]} arr array of hash strings + * + * @returns {string} a single hash + */ + +function hashArray(arr) { + const source = new stream.Readable({ objectMode: true, read() {} }); + const hasher = new IdHasher(); + + source.pipe(hasher); + + return new Promise((resolve, reject) => { + hasher.on('finish', () => { + resolve(hasher.hash); + }); + + hasher.on('error', reject); + + for (const hash of arr) { + source.push({ id: hash }); + } + source.push(null); + }); +} + +module.exports.hashArray = hashArray; diff --git a/test/common.test.js b/test/common.test.js index 0db5026..4889e11 100644 --- a/test/common.test.js +++ b/test/common.test.js @@ -8,6 +8,7 @@ const { FileHasher, SourceHasher, createTemporaryFilename, + hashArray, } = require('../'); test('SourceHasher() - feed stream source hash', done => { @@ -102,3 +103,11 @@ test('createTemporaryFilename()', () => { const regex = new RegExp(`^tmp-[0-9a-f-]{5,40}.${type}$`); expect(createTemporaryFilename(type)).toMatch(regex); }); + +test('hashArray() - takes array of hashes, resolves as a hash', async () => { + expect.hasAssertions(); + const hash = await hashArray(['abc1acb2', 'abc1acb2', 'abc1acb2']); + expect(hash).toBe( + '31675a591c1f2963a9ee2d48af5e23b352885db705210818d203e2ba2fc752b4' + ); +});