r/dailyprogrammer - 2018-01-24 - Bowling

by Douglas_Meyer

CSS

pre {
  background-color: #DDD;
}

JavaScript

const inputs = [
  '6 4 5 3 10 10 8 1 8 0 10 6 3 7 3 5 3',
  '9  0  9  0  9  0  9  0  9  0  9  0  9  0  9  0  9  0  9  0',
  '10 10 10 10 10 10 10 10 10 10 10 10',
  '5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5',
  '10 3  7  6  1  10 10 10 2  8  9  0  7  3  10 10 10',
  '9  0  3  7  6  1  3  7  8  1  5  5  0  10 8  0  7  3  8  2  8',
];
const outputs = [
  '6/ 53 X  X  81 8- X  63 7/ 53',
  '9- 9- 9- 9- 9- 9- 9- 9- 9- 9-',
  'X  X  X  X  X  X  X  X  X  XXX',
  '5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/5',
  'X  3/ 61 X  X  X  2/ 9- 7/ XXX',
  '9- 3/ 61 3/ 81 5/ -/ 8- 7/ 8/8',
];

function displayFrame(frame){
	return frame
  .replace(/\b(?:(10)|(\d)\s+(\d+))\b\s*/g, function(_, strike, n1, n2){
  	if (strike) return "X  ";
  	if (n1*1+n2*1 === 10) return `${n1}/ `;
    return `${n1}${n2} `;
  })
  .replace(/0/g, '-')
  .replace(/(?:(X)  (X)  (X) |(\S\/) (\S)|(\S{2})) ?$/, (...a) => a.slice(1,-2).join(''));
}

inputs.forEach((input, index) => {
	const output = outputs[index];
	const pre = document.createElement('pre');
	document.body.appendChild(pre);
  out = displayFrame(input);
	pre.textContent = `${input}
${JSON.stringify(output)}
${JSON.stringify(out)}
${output === out}`});