Sigo recibiendo un error que indica que no puede leer el retorno en getLatestBlock. Literalmente seguí un video de YouTube paso a paso. Funcionó para él. No entiendo qué estoy haciendo mal.
El video se lanzó en 2017. ¿Ha habido cambios en JS que desconozco? Gracias a todos.
const SHA256 = require("crypto-js/sha256"); class Block { constructor(index, timestamp, data, previousHash = "") { this.index = index; this.timestamp = timestamp; this.data = data; this.previousHash = previousHash; this.hash = this.calculateHash(); } // Hash identifies the block calculateHash() { return SHA256( this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) ).toString(); } } class Blockchain { contstructor() { this.chain = [this.createGenesisBlock()]; } createGenesisBlock() { return new Block(0, "01/01/2017", "Genesis block", "0"); } getLatestBlock() { this.chain[this.chain.length - 1]; } addBlock(newBlock) { newBlock.previousHash = this.getLatestBlock().hash; newBlock.hash = newBlock.calculateHash(); this.chain.push(newBlock); } } let savejeeCoin = new Blockchain(); savejeeCoin.addBlock(new Block(1, "10/07/2017", { amount: 4 })); savejeeCoin.addBlock(new Block(2, "12/07/2017", { amount: 10 })); console.log(JSON.stringify(savejeeCoin, null, 4));En primer lugar, hay un error tipográfico en su clase Blockchain : contstructor debe ser constructor . Es por eso que no inicializas tus cosas y obtienes el error.
Refactorizaría un poco la cosa:
Espero que esto ayude... Me parece más OOP.
Salud
const SHA256 = require("crypto-js/sha256"); class Block { get amount() { return this._amount; } get hash() { return this._hash; } get index() { return this._index; } get timestamp() { return this._timestamp; } constructor(index, amount, prevHash = '') { // make all props private so they can be written only once this._index = index; this._timestamp = +new Date(); this._amount = amount; this._hash = SHA256( `${this.index}-${prevHash}-${this.timestamp}-${this.amount}` ).toString(); } } class BlockChain { get chain() { return this._chain; } constructor() { this._chain = []; this.addBlock(0, 'Genesis block'); } getCurrentHash() { this.chain[this.chain.length - 1].hash; } addBlock(amount, prevHash = this.getCurrentHash()) { this.chain.push(new Block(this.chain.length - 1, amount, prevHash)); } } let savejeeCoin = new Blockchain(); savejeeCoin.addBlock(4); savejeeCoin.addBlock(10); console.log(JSON.stringify(savejeeCoin, null, 4));Blitz aquí donde implementé miembros privados (#) y una compilación fn para imprimir bloques individuales y la cadena...