randPosition.ts 494 B

12345678910111213
  1. /**
  2. * Generate a uniform number in the range [0 ... `num_positions` - 1] by hashing
  3. `seed` (bytes) and `counter` (int). Note that proper uniformity requires that
  4. num_positions should be much less than 2**64.
  5. (see https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/)
  6. """
  7. */
  8. export default (seed, num_positions, counter) => {
  9. int64 = int.from_bytes(sha256(seed + counter.to_bytes(4, 'big'))[:8], 'big')
  10. return (int64 * num_positions) >> 64
  11. }