nonNumericOnlyHash.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. /** @import Hash from "./Hash" */
  7. const A_CODE = "a".charCodeAt(0);
  8. /**
  9. * Returns hash that has at least one non numeric char.
  10. * @param {string} hash hash
  11. * @param {number} hashLength hash length
  12. * @returns {string} returns hash that has at least one non numeric char
  13. */
  14. const nonNumericOnlyHash = (hash, hashLength) => {
  15. if (hashLength < 1) return "";
  16. const slice = hash.slice(0, hashLength);
  17. if (/[^\d]/.test(slice)) return slice;
  18. return `${String.fromCharCode(
  19. A_CODE + (Number.parseInt(hash[0], 10) % 6)
  20. )}${slice.slice(1)}`;
  21. };
  22. /**
  23. * Digests a hash and truncates it to a content-hash string (non-numeric first char).
  24. * @param {Hash} hash hash
  25. * @param {string} hashDigest digest encoding
  26. * @param {number} hashDigestLength hash length
  27. * @returns {string} content hash string
  28. */
  29. const digestNonNumericOnly = (hash, hashDigest, hashDigestLength) =>
  30. nonNumericOnlyHash(hash.digest(hashDigest), hashDigestLength);
  31. /**
  32. * Digests a hash, returning both the truncated content-hash string and the full
  33. * (untruncated) digest, so `[contenthash:<digest>]` can re-encode from full entropy.
  34. * @param {Hash} hash hash
  35. * @param {string} hashDigest digest encoding
  36. * @param {number} hashDigestLength hash length
  37. * @returns {[string, string]} content hash string and full digest
  38. */
  39. const digestNonNumericOnlyWithFull = (hash, hashDigest, hashDigestLength) => {
  40. const full = /** @type {string} */ (hash.digest(hashDigest));
  41. return [nonNumericOnlyHash(full, hashDigestLength), full];
  42. };
  43. nonNumericOnlyHash.digestNonNumericOnly = digestNonNumericOnly;
  44. nonNumericOnlyHash.digestNonNumericOnlyWithFull = digestNonNumericOnlyWithFull;
  45. module.exports = nonNumericOnlyHash;