ethers.js/packages/tests/lib/utils.js

68 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2020-07-13 08:03:56 -04:00
/* istanbul ignore file */
2019-05-14 18:48:48 -04:00
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
2021-03-07 18:24:04 -05:00
exports.equals = exports.randomNumber = exports.randomHexString = exports.randomBytes = void 0;
2019-05-14 18:48:48 -04:00
var ethers_1 = require("ethers");
function randomBytes(seed, lower, upper) {
if (!upper) {
upper = lower;
}
if (upper === 0 && upper === lower) {
return new Uint8Array(0);
}
var result = ethers_1.ethers.utils.arrayify(ethers_1.ethers.utils.keccak256(ethers_1.ethers.utils.toUtf8Bytes(seed)));
while (result.length < upper) {
result = ethers_1.ethers.utils.concat([result, ethers_1.ethers.utils.keccak256(ethers_1.ethers.utils.concat([seed, result]))]);
}
var top = ethers_1.ethers.utils.arrayify(ethers_1.ethers.utils.keccak256(result));
var percent = ((top[0] << 16) | (top[1] << 8) | top[2]) / 0x01000000;
return result.slice(0, lower + Math.floor((upper - lower) * percent));
}
exports.randomBytes = randomBytes;
function randomHexString(seed, lower, upper) {
return ethers_1.ethers.utils.hexlify(randomBytes(seed, lower, upper));
}
exports.randomHexString = randomHexString;
function randomNumber(seed, lower, upper) {
var top = randomBytes(seed, 3);
var percent = ((top[0] << 16) | (top[1] << 8) | top[2]) / 0x01000000;
return lower + Math.floor((upper - lower) * percent);
}
exports.randomNumber = randomNumber;
function equals(a, b) {
// Array (treat recursively)
if (Array.isArray(a)) {
if (!Array.isArray(b) || a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i++) {
if (!equals(a[i], b[i])) {
return false;
}
}
return true;
}
// BigNumber
if (a.eq) {
if (!b.eq || !a.eq(b)) {
return false;
}
return true;
}
// Uint8Array
if (a.buffer) {
if (!b.buffer || a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
// Something else
return a === b;
}
exports.equals = equals;
2020-07-13 08:03:56 -04:00
//# sourceMappingURL=utils.js.map