Skip to content

Commit a9e9e6c

Browse files
committed
convert hex to decimal with native bigint
1 parent 96e8846 commit a9e9e6c

File tree

1 file changed

+3
-28
lines changed

1 file changed

+3
-28
lines changed

flagsmith-engine/utils/hashing/index.ts

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,31 +6,6 @@ const makeRepeated = (arr: Array<any>, repeats: number) =>
66
Array.from({ length: repeats }, () => arr).flat();
77

88
// https://stackoverflow.com/questions/12532871/how-to-convert-a-very-large-hex-number-to-decimal-in-javascript
9-
function h2d(s: string): string {
10-
function add(x: string, y: string) {
11-
var c = 0,
12-
r: number[] = [];
13-
const a = x.split('').map(Number);
14-
const b = y.split('').map(Number);
15-
while (x.length || y.length) {
16-
var s = (a.pop() || 0) + (b.pop() || 0) + c;
17-
r.unshift(s < 10 ? s : s - 10);
18-
c = s < 10 ? 0 : 1;
19-
}
20-
if (c) r.unshift(c);
21-
return r.join('');
22-
}
23-
24-
var dec = '0';
25-
s.split('').forEach(function (chr: any) {
26-
var n = parseInt(chr, 16);
27-
for (var t = 8; t; t >>= 1) {
28-
dec = add(dec, dec);
29-
if (n & t) dec = add(dec, '1');
30-
}
31-
});
32-
return dec;
33-
}
349
/**
3510
* Given a list of object ids, get a floating point number between 0 and 1 based on
3611
* the hash of those ids. This should give the same value every time for any list of ids.
@@ -42,12 +17,12 @@ function h2d(s: string): string {
4217
export function getHashedPercentateForObjIds(objectIds: Array<any>, iterations = 1): number {
4318
let toHash = makeRepeated(objectIds, iterations).join(',');
4419
const hashedValue = md5(toHash);
45-
const hashedInt = BigInt(h2d(hashedValue));
46-
const value = (((hashedInt) % 9999n) / 9998n) * 100n;
20+
const hashedInt = BigInt('0x' + hashedValue);
21+
const value = (Number((hashedInt % 9999n)) / 9998.0) * 100;
4722

4823
// we ignore this for it's nearly impossible use case to catch
4924
/* istanbul ignore next */
50-
if (value === 100n) {
25+
if (value === 100) {
5126
/* istanbul ignore next */
5227
return getHashedPercentateForObjIds(objectIds, iterations + 1);
5328
}

0 commit comments

Comments
 (0)