Skip to content
This repository has been archived by the owner on Jun 24, 2024. It is now read-only.

Commit

Permalink
feat: add hashArray method
Browse files Browse the repository at this point in the history
  • Loading branch information
digitalsadhu committed Mar 8, 2018
1 parent 90bf27d commit fd79fc7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
9 changes: 9 additions & 0 deletions test/common.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const {
FileHasher,
SourceHasher,
createTemporaryFilename,
hashArray,
} = require('../');

test('SourceHasher() - feed stream source hash', done => {
Expand Down Expand Up @@ -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'
);
});

0 comments on commit fd79fc7

Please sign in to comment.