Created
July 7, 2018 22:28
-
-
Save jredville/08349f5df2cb3ddbe7167dc801d82d8b to your computer and use it in GitHub Desktop.
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
class Letter { | |
constructor(letter) { | |
this._letter = letter; | |
this._before = []; | |
this._after = []; | |
} | |
get letter() { | |
return this._letter; | |
} | |
get before() { | |
return this._before; | |
} | |
get after() { | |
return this._after; | |
} | |
isBefore(other) { | |
if (this.before.indexOf(other) === -1) { | |
this.before.push(other); | |
} | |
} | |
isAfter(other) { | |
if (this.after.indexOf(other) === -1) { | |
this.after.push(other); | |
} | |
} | |
toString() { | |
return this.letter; | |
} | |
} | |
class Triplets { | |
constructor() { | |
this._letters = []; | |
} | |
get letters() { | |
return this._letters; | |
} | |
add(first, sec, last) { | |
this.addOne(first, sec); | |
this.addOne(sec, last, first); | |
this.addOne(last, null, sec); | |
return this; | |
} | |
addLetter(letter) { | |
const l = new Letter(letter); | |
this.letters.push(l); | |
return l; | |
} | |
findLetter(letter) { | |
if (!letter) { | |
return | |
} | |
return this.letters.find(l => l.letter === letter) || this.addLetter(letter); | |
} | |
addOne(letter, before, after) { | |
letter = this.findLetter(letter); | |
before = this.findLetter(before); | |
after = this.findLetter(after); | |
if (before) { | |
letter.isBefore(before) | |
} | |
if (after) { | |
letter.isAfter(after) | |
} | |
} | |
deleteFromArray(arr, target) { | |
const item = arr.find(l => l.letter === target.letter); | |
const index = arr.indexOf(item); | |
arr.splice(index, 1); | |
} | |
findNextLetter(from) { | |
const res = from.before.find(l => l.after.length === 1 && l.after[0].letter == from.letter); | |
from.before.forEach(bef => this.deleteFromArray(bef.after, from)); | |
this.deleteFromArray(this.letters, from); | |
return res; | |
} | |
toString() { | |
const res = this.letters.filter(l => l.after.length === 0); | |
while(this.letters.length > 1) { | |
res.push(this.findNextLetter(res[res.length-1])); | |
} | |
return res.map(l => l.toString()).join(''); | |
} | |
} | |
var recoverSecret = function(triplets) { | |
return triplets.reduce((t, l) => t.add(...l), new Triplets()).toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment