JSFiddle - React, Tailwind, and code Playground
by tonytlwu
HTML
<h1>Test Results</h1>
<ul>
</ul>
CSS
* { font-family: sans-serif; line-height: 150%; font-size: 10px; }
li { margin-bottom: 20px }
li.success { color: green }
li.error { color: red }
li code { font-family: monospace; font-weight: bold; }
JavaScript
function addOne(arr, base) {
if (base && base > 36) {
return 'Base cannot be bigger than 36'
}
if (!arr.length) {
arr = [0];
}
const sign = arr[0] < 0 ? -1 : 1
const positive = arr.map((el)=>{
const result = el< 0 ? -el : el;
return result
})
const int = parseInt(positive.join(""), base)
const total = int + sign
const numbers = total.toString(base).split("");
const result = numbers.map((el)=>{
let intVersion = Number.parseInt(el, base)
if (intVersion < 10) {
return intVersion * sign
}
if (sign) {
return el.toUpperCase();
}
return `-${el.toUpperCase()}`;
})
return result;
}
// --------------------------------------------
// TESTS BELOW - PLEASE ADD YOUR OWN TEST CASES
// --------------------------------------------
expect('addOne([5, 1, 2])', addOne([5, 1, 2]), [5, 1, 3]);
expect('addOne([0])', addOne([0]), [1]);
expect('addOne([9, 9])', addOne([9, 9]), [1, 0, 0]);
expect('addOne([1, 9, 9])', addOne([1, 9, 9]), [2, 0, 0]);
expect('addOne([-3, -7])', addOne([-3, -7]), [-3, -6]);
expect('addOne([-1, 0, 0])', addOne([-1, 0, 0]), [-9, -9]);
expect('addOne([1, 0, 1], 2)', addOne([1, 0, 1], 2), [1, 1, 0]);
expect('addOne([\'B\', 3, 9], 16], 2)', addOne(['B', 3, 9], 16), ['B', 3, 'A']);
expect('addOne([\'B\', 3, \'F\'], 16)', addOne(['B', 3, 'F'], 16), ['B', 4, 0]);
expect('addOne([-3, \'-F\'], 16)', addOne([-3, '-F'], 16), [-3, '-E']);
expect('addOne([\'-F\', 0], 16)', addOne(['-F', 0], 16), ['-E', '-F']);
// ------------------------------------------
function compareArrays(arr1, arr2) {
return $(arr1).not(arr2).length == 0 && $(arr2).not(arr1).length == 0;
}
function expect(name, a, b) {
if (a !== b && !(a instanceof Array && b instanceof Array && compareArrays(a, b))) {
$('ul').append('<li class="error">Testing <code>' + name + '</code> ...<br />Error: <code>' + a + '</code> is the wrong answer</li>');
} else {
$('ul').append('<li class="success">Testing <code>' + name + '</code>...