Created
September 10, 2019 14:58
-
-
Save jm90m/fa113129ff60e90f170afd6f6f4ba93a to your computer and use it in GitHub Desktop.
incomplete implementation of deck decoder
This file contains hidden or 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
const GOD_NAMES = { | |
nature: 1, | |
war: 2, | |
death: 3, | |
light: 4, | |
magic: 5, | |
deception: 6, | |
}; | |
function collectCards(cards) { | |
// count the number of times each card appears in the list | |
if (!Array.isArray(cards)) return []; | |
const counts = {}; | |
for (let i = 0; i < cards.length; i = i + 1) { | |
const cardId = cards[i]; | |
const currentCardCount = counts[cardId]; | |
if (currentCardCount === undefined) { | |
counts[cardId] = 1; | |
} else { | |
counts[cardId] = currentCardCount + 1; | |
} | |
} | |
const cardFrequencies = {}; | |
Object.keys(counts).forEach(cardId => { | |
const frequency = counts[cardId]; | |
const currentCardFrequency = cardFrequencies[frequency]; | |
if (currentCardFrequency === undefined) { | |
cardFrequencies[frequency] = [parseInt(cardId, 10)]; | |
} else { | |
cardFrequencies[frequency] = currentCardFrequency.concat(parseInt(cardId, 10)); | |
} | |
}); | |
const cardCollection = []; | |
Object.keys(cardFrequencies).forEach(frequency => { | |
const protos = cardFrequencies[frequency]; | |
cardCollection.push({ | |
frequency: parseInt(frequency, 10), | |
protos, | |
}); | |
}); | |
cardCollection.sort((cardFrequencyA, cardFrequencyB) => { | |
if (cardFrequencyA.frequency < cardFrequencyB.frequency) { | |
return -1; | |
} | |
if (cardFrequencyA.frequency > cardFrequencyB.frequency) { | |
return 1; | |
} | |
return 0; | |
}); | |
return cardCollection; | |
} | |
function encodeDeck(deck) { | |
console.log(deck.protos.length); | |
const versionBuffer = Buffer.from(deck.version.toString()); | |
if (!GOD_NAMES[deck.god]) { | |
return 'Unsupported god'; | |
} | |
const godBuffer = Buffer.from(deck.god); | |
let buffer = Buffer.concat([versionBuffer, godBuffer]); | |
const cardCollection = collectCards(deck.protos); | |
cardCollection.forEach(cards => { | |
buffer = Buffer.concat([buffer, Buffer.from(cards.frequency.toString())]); | |
buffer = Buffer.concat([buffer, Buffer.from(cards.protos.length.toString())]); | |
cards.protos.forEach(proto => { | |
buffer = Buffer.concat([buffer, Buffer.from(proto.toString())]); | |
}); | |
}); | |
return buffer.toString('base64'); | |
} | |
function decodeDeck(data) { | |
const decodedString = Buffer.from(data, 'base64'); | |
for (let i = 0; i < decodedString.length; i = i + 1) { | |
console.log(decodedString[i]); | |
} | |
return decodedString; | |
} | |
module.exports = { | |
decodeDeck, | |
encodeDeck, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment