liveBook · Manning

calculateHash

As explained in The Joy of JavaScript

calculateHash is a book-local method name for computing a hash value from selected properties.

calculateHash is a method that computes a deterministic hash from selected object properties. Its design separates property selection, data assembly, and digest computation so the hashing algorithm can change independently. section 4.3.2 section 4.4.2

A composable implementation divides the method into these responsibilities:

  • Selects the configured keys and extracts their values from the target object. section 4.4.2
  • Assembles selected values into a predictable string representation, using JSON.stringify when values may be non-primitive. section 4.3.2 section 4.4.2
  • Computes the digest through a replaceable cipher, first with a recursive implementation and later with Node.js crypto. section 4.3.2 section 4.4.2
  • Composes these pure functions while keeping object context at the mixin boundary. section 4.3.2 section 4.4.2

Hashing a transaction

A transaction can combine its sender, recipient, and funds into a SHA-256 hexadecimal digest by applying HasHash(['sender', 'recipient', 'funds']). Repeated calls with unchanged selected properties produce the same hash. section 4.4.2

Listing 4.12 Final implementation of HasHash
const HasHash = (
  keys,
  options = { 
       algorithm: 'SHA256', 
       encoding:  'hex' 
    }
) => ({
  calculateHash() {
     return compose(
      computeCipher(options),
      assemble,
      props(keys)
    )(this);           #1
  }
});

The final HasHash implementation shows configurable keys and hash options flowing through props, assemble, and computeCipher. section 4.4.2

How The Joy of JavaScript covers it

How deep it goes
Decomposes context-sensitive hashing into pure functions, composition, currying, serialization, and crypto-backed digest generation.
Examples
Uses transaction sender, recipient, and funds values to produce a SHA-256 hexadecimal digest.
What it assumes
Assumes JavaScript functions, objects, this binding, mixins, and composition while teaching their interaction through hashing.
What you can do after
Build it from scratch as a configurable hashing pipeline and apply it to multiple object shapes through a mixin.
How it connects
Connects hashing with pure functions, function composition, currying, mixins, dynamic binding, and object property selection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.