All files / crypto/src hashString.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 3/3
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22                                1x 1x 1x 1x    
/**
 * Hashes a String using the given `algorithm`
 *
 * @example
 * Hash a String using `SHA-256`
 * ```ts
 * const sha256hasher = hashString("SHA-256");
 * const arrayBuffer = sha256hasher("test");
 *
 * const hexString = arrayBufferToHexString(arrayBuffer);
 * console.log(hexString); // "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
 * ```
 *
 * @param algorithm
 * @returns the ArrayBuffer containing the hash in binary form
 */
export const hashString =
  (algorithm: AlgorithmIdentifier) =>
  async (str: string): Promise<ArrayBuffer> => {
    return await crypto.subtle.digest(algorithm, new TextEncoder().encode(str));
  };