Skip to content

Instantly share code, notes, and snippets.

@lindsaycarbonell
Created February 14, 2019 21:03
Show Gist options
  • Save lindsaycarbonell/d992dedef9f7fd3ddca79fd53e265eb0 to your computer and use it in GitHub Desktop.
Save lindsaycarbonell/d992dedef9f7fd3ddca79fd53e265eb0 to your computer and use it in GitHub Desktop.
kata: make the deadfish swim

Write a simple parser that will parse and run Deadfish.

Deadfish has 4 commands, each 1 character long:

i increments the value (initially 0) d decrements the value s squares the value o outputs the value into the return array Invalid characters should be ignored.

parse("iiisdoso") => [ 8, 64 ]

function parse( data )
{
var response = [];
var num = 0;
data.split("").forEach(function(val) {
if (val == "d") {
num--;
} else if (val == "i") {
num ++;
} else if (val == "s") {
num = num*num;
} else if (val == "o") {
response.push(num);
}
});
return response;
}
//SOLUTION ONE
function parse(data) {
let res = [];
data.split('').reduce((cur, s) => {
if (s === 'i') cur++;
if (s === 'd') cur--;
if (s === 's') cur = Math.pow(cur, 2); //I would've done cur *= cur;
if (s === 'o') res.push(cur);
return cur;
}, 0);
return res;
}
//SOLUTION TWO
function parse( data ) {
var v = 0, ret = []
for (var c of data) {
switch (c) {
case 'i' : v++; break;
case 'd' : v--; break;
case 's' : v=v*v; break;
case 'o' : ret.push(v); break;
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment