Skip to content

Instantly share code, notes, and snippets.

@kamilogorek
Created June 14, 2017 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamilogorek/da567b3cf80af0fde6c5a4bc11904374 to your computer and use it in GitHub Desktop.
Save kamilogorek/da567b3cf80af0fde6c5a4bc11904374 to your computer and use it in GitHub Desktop.
Calculate spell damage code kata
const { damage } = require("./spell");
console.assert(2 === damage("feeai")); // == 2
console.assert(7 === damage("feaineain")); // == 1 + 2 + 2 + 2 = 7 (fe-ai-ne-ai) - not (fe-ain-ai) because 1+3+2 = 6 and 7 > 6
console.assert(0 === damage("jee")); // == 0
console.assert(0 === damage("fefefefefeaiaiaiaiai")); // == 0 (more than one 'fe')
console.assert(1 === damage("fdafafeajain")); // == 1 (fe-ai) 3 - 2 (because 'aj')
console.assert(0 === damage("fexxxxxxxxxxai")); // == 0 (3-10 = -7 < 0)
const DEV = true;
const spellsDamage = {
fe: 1,
je: 2,
jee: 3,
ain: 3,
dai: 5,
ne: 2,
ai: 2
};
const availableSpells = Object.keys(spellsDamage);
const longestSpellLength = Math.max(...availableSpells.map(x => x.length));
function shorterToLonger(spell) {
let totalDamage = 0;
mainLoop: for (let i = 0; i < spell.length; i++) {
for (let j = 1; j <= longestSpellLength; j++) {
const spellPart = spell.slice(i, i + j);
if (availableSpells.includes(spellPart)) {
totalDamage += spellsDamage[spellPart];
i += j - 1;
continue mainLoop;
}
}
totalDamage -= 1;
}
return totalDamage;
}
function longerToShorter(spell) {
let totalDamage = 0;
mainLoop: for (let i = 0; i < spell.length; i++) {
const spellPart = spell.slice(i, longestSpellLength);
if (availableSpells.includes(spellPart)) {
totalDamage += spellsDamage[spellPart];
i += spellPart.length;
continue;
}
for (let j = 1; j < spellPart.length; j++) {
if (availableSpells.includes(spellPart.slice(0, -j))) {
totalDamage += spellsDamage[spellPart.slice(0, -j)];
i += spellPart.length - j;
continue mainLoop;
}
}
totalDamage -= 1;
}
return totalDamage;
}
exports.damage = function(spellString) {
const match = /fe(.*)ai/.exec(spellString);
if (!match || spellString.match(/fe/g).length > 1) {
if (DEV) console.log(`Spell: '${spellString}' | Invalid spell`);
return 0;
}
const extractedSpell = match[1];
let totalDamage = spellsDamage["fe"] + spellsDamage["ai"];
const shorterToLongerDamage = shorterToLonger(extractedSpell);
const longerToShorterDamage = longerToShorter(extractedSpell);
if (shorterToLongerDamage > longerToShorterDamage) {
totalDamage += shorterToLongerDamage;
} else {
totalDamage += longerToShorterDamage;
}
if (DEV) console.log(`Spell: '${spellString}' | Damage: ${totalDamage}`);
return totalDamage > 0 ? totalDamage : 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment