Skip to content

Commit 03f8b75

Browse files
committed
Remove duplicated code from hash functions
1 parent 8c669d6 commit 03f8b75

File tree

5 files changed

+23
-20
lines changed

5 files changed

+23
-20
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Hash } from "crypto";
2+
3+
export function createHashFunction(
4+
hashConstructor: () => Hash
5+
): (msg: Buffer) => Buffer {
6+
return msg => {
7+
const hash = hashConstructor();
8+
hash.update(msg);
9+
return Buffer.from(hash.digest());
10+
};
11+
}
Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
const { ripemd160: Ripemd160 } = require("hash.js/lib/hash/ripemd");
22

3-
export function ripemd160(msg: Buffer): Buffer {
4-
const hash = new Ripemd160();
5-
hash.update(msg);
3+
import { createHashFunction } from "../hash-utils";
64

7-
return Buffer.from(hash.digest());
8-
}
5+
export const ripemd160 = createHashFunction(() => new Ripemd160());
Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
const Sha256Hash = require("hash.js/lib/hash/sha/256");
22

3-
export function sha256(msg: Buffer): Buffer {
4-
const hash = new Sha256Hash();
5-
hash.update(msg);
3+
import { createHashFunction } from "../hash-utils";
64

7-
return Buffer.from(hash.digest());
8-
}
5+
export const sha256 = createHashFunction(() => new Sha256Hash());
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import crypto from "crypto";
22

3-
export function ripemd160(msg: Buffer): Buffer {
4-
const hash = crypto.createHash("ripemd160");
5-
hash.update(msg);
6-
return Buffer.from(hash.digest());
7-
}
3+
import { createHashFunction } from "./hash-utils";
4+
5+
export const ripemd160 = createHashFunction(() =>
6+
crypto.createHash("ripemd160")
7+
);
Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import crypto from "crypto";
22

3-
export function sha256(msg: Buffer): Buffer {
4-
const hash = crypto.createHash("sha256");
5-
hash.update(msg);
6-
return Buffer.from(hash.digest());
7-
}
3+
import { createHashFunction } from "./hash-utils";
4+
5+
export const sha256 = createHashFunction(() => crypto.createHash("sha256"));

0 commit comments

Comments
 (0)