StatsManager.js 960 B

123456789101112131415161718192021222324
  1. const crypto = require('node:crypto')
  2. /**
  3. * Consistently sample a keyspace with a given sample percentage.
  4. * The same key will always produce a consistent percentile value that
  5. * can be compared against the sample percentage.
  6. * Example: if key is the userId and the samplePercentage is 10, then
  7. * we see all the activity for the 10% of users who are selected.
  8. *
  9. * @param {string} key - The unique identifier to be hashed and checked.
  10. * @param {number} samplePercentage - The percentage (0-100) of keys that should return true.
  11. * @returns {boolean} - True if the key is within the sample, false otherwise.
  12. */
  13. function sampleByHash(key, samplePercentage) {
  14. if (samplePercentage <= 0) {
  15. return false
  16. }
  17. const hash = crypto.createHash('md5').update(key).digest()
  18. const hashValue = hash.readUInt32BE(0)
  19. const percentile = Math.floor((hashValue / 0xffffffff) * 100)
  20. return percentile < samplePercentage
  21. }
  22. module.exports = { sampleByHash }