Skip to content

Instantly share code, notes, and snippets.

@sr105
Last active August 30, 2018 16:41
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 sr105/95ca10447578cfd71349c4a61e2efc4f to your computer and use it in GitHub Desktop.
Save sr105/95ca10447578cfd71349c4a61e2efc4f to your computer and use it in GitHub Desktop.
woodLength Javascript Kata
// https://www.codewars.com/kata/how-much-wood/train/javascript
//
// Written for node v8.1.3
//
// nvm install v8.1.3
// nvm use v8.1.3
// node woodLength.js
//
function woodLength(dimensions) {
function measurement(str) {
// https://regex101.com/r/Z8aHuk/1
const re = /^(?:(\d+)(['"]))? ?(?:(\d+)? ?(?:(\d+)\/(\d+))?(['"]))$/;
const m = str.match(re);
if (!m) throw str;
const value = defaultValue => v => parseInt(v) || defaultValue;
const units = {"'": 12, '"': 1};
const unit = v => units[v] || 1;
const defaults = [value(0), unit, value(0), value(0), value(1), unit];
const values = m.slice(1, 1 + defaults.length);
const [whole, wunit, fwhole, num, denom, funit] = values.map((v, i) => defaults[i](v));
return whole * wunit + (fwhole + (num / denom)) * funit;
}
function toFractionalInch(n) {
let b = 1;
while (!Number.isInteger(n)) {
b *= 2;
n *= 2;
}
return [n, b];
}
let height, length, width;
try {
[height, length, width] = dimensions.map(x => measurement(x));
} catch(e) {
console.log('bad input: ' + e);
return 'bad input: ' + e;
}
const need = 2 * (height + length + 4 * width);
const feet = Math.floor(need / 12);
let inches = need - feet * 12;
const fraction = toFractionalInch(inches - Math.floor(inches));
inches = Math.floor(inches);
let s = [];
if (feet) s.push(`${feet}'`);
if (inches) s.push(inches);
if (fraction[0]) s.push(fraction.join('/'));
return s.join(' ') + ((inches || fraction[0]) ? '"' : '');
}
const tests = [
[["1\'","1\'","1/2\""], "4\' 4\""],
[["2\'","1\' 5\"","1/16\""], "6\' 10 1/2\""],
[["2\'","1\' 5\"","1\""], "7\' 6\""],
[["4\'","2\' 6\"","5/32\""], "13\' 1 1/4\""],
[["7\"","9\"","2\""], "4\'"],
[["a7\"","9\"","2\""], "4\'"],
];
tests.forEach(([input, output]) =>
console.log("woodLength([" + input.join(', ') + "]) == " + output +
" => " + (woodLength(input) == output))
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment