1- import md5 from 'md5' ;
2- import bigInt from 'big-integer' ;
1+ import { BinaryLike , createHash } from "node:crypto" ;
2+
3+ const md5 = ( data : BinaryLike ) => createHash ( 'md5' ) . update ( data ) . digest ( 'hex' )
34
45const makeRepeated = ( arr : Array < any > , repeats : number ) =>
56 Array . from ( { length : repeats } , ( ) => arr ) . flat ( ) ;
67
78// https://stackoverflow.com/questions/12532871/how-to-convert-a-very-large-hex-number-to-decimal-in-javascript
8- function h2d ( s : any ) : string {
9- function add ( x : any , y : any ) {
10- var c = 0 ,
11- r = [ ] ;
12- var x = x . split ( '' ) . map ( Number ) ;
13- var y = y . split ( '' ) . map ( Number ) ;
14- while ( x . length || y . length ) {
15- var s = ( x . pop ( ) || 0 ) + ( y . pop ( ) || 0 ) + c ;
16- r . unshift ( s < 10 ? s : s - 10 ) ;
17- c = s < 10 ? 0 : 1 ;
18- }
19- if ( c ) r . unshift ( c ) ;
20- return r . join ( '' ) ;
21- }
22-
23- var dec = '0' ;
24- s . split ( '' ) . forEach ( function ( chr : any ) {
25- var n = parseInt ( chr , 16 ) ;
26- for ( var t = 8 ; t ; t >>= 1 ) {
27- dec = add ( dec , dec ) ;
28- if ( n & t ) dec = add ( dec , '1' ) ;
29- }
30- } ) ;
31- return dec ;
32- }
339/**
3410 * Given a list of object ids, get a floating point number between 0 and 1 based on
3511 * the hash of those ids. This should give the same value every time for any list of ids.
@@ -41,8 +17,8 @@ function h2d(s: any): string {
4117export function getHashedPercentateForObjIds ( objectIds : Array < any > , iterations = 1 ) : number {
4218 let toHash = makeRepeated ( objectIds , iterations ) . join ( ',' ) ;
4319 const hashedValue = md5 ( toHash ) ;
44- const hashedInt = bigInt ( h2d ( hashedValue ) ) ;
45- const value = ( hashedInt . mod ( 9999 ) . toJSNumber ( ) / 9998 ) * 100 ;
20+ const hashedInt = BigInt ( '0x' + hashedValue ) ;
21+ const value = ( Number ( ( hashedInt % 9999n ) ) / 9998.0 ) * 100 ;
4622
4723 // we ignore this for it's nearly impossible use case to catch
4824 /* istanbul ignore next */
0 commit comments