Last active
July 26, 2017 20:19
-
-
Save earlonrails/052eda9091f96c0b90e80adc6abbd960 to your computer and use it in GitHub Desktop.
Merkle tree written in es6 javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
"use strict" | |
const expect = require('expect.js') | |
class Merkle { | |
constructor(array) { | |
this.key = array.join('') | |
this.left = null | |
this.right = null | |
this.load(array) | |
} | |
load(array) { | |
if (array.length == 1) return | |
var left, | |
right, | |
mid = Math.floor(array.length / 2) | |
if (mid != 1 && mid % 2 != 0) { | |
mid += 1 | |
} | |
left = array.slice(0, mid) | |
right = array.slice(mid) | |
if (left.length) { | |
this.left = new Merkle(left) | |
} | |
if (right.length) { | |
this.right = new Merkle(right) | |
} | |
} | |
} | |
// works with 2 | |
var m = new Merkle(['a', 'b']) | |
expect(m.left.key).to.eql('a') | |
expect(m.right.key).to.eql('b') | |
// works with 6 | |
var m = new Merkle(['a', 'b', 'c', 'd', 'e', 'f']) | |
expect(m.left.key).to.eql('abcd') | |
expect(m.right.key).to.eql('ef') | |
// works with 11 | |
var m = new Merkle(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']) | |
expect(m.left.key).to.eql('abcdef') | |
expect(m.right.key).to.eql('ghijk') | |
// works with 12 | |
var m = new Merkle(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']) | |
expect(m.left.key).to.eql('abcdef') | |
expect(m.right.key).to.eql('ghijkl') | |
console.log("All tests pass") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment