Skip to content

Instantly share code, notes, and snippets.

@islishude
Last active May 30, 2019 05:35
Show Gist options
  • Save islishude/a932403a0e7bec4443db028085590394 to your computer and use it in GitHub Desktop.
Save islishude/a932403a0e7bec4443db028085590394 to your computer and use it in GitHub Desktop.
base26.js
const { deepStrictEqual } = require("assert");
const table = "ABCDEFGHIJKLMNOPQRSTUVWXWZ";
const tableLength = table.length;
// 13.1
{
const func1 = row => {
let result = 0;
const rowlength = row.length;
for (let i = 0; i < rowlength; i++) {
const index = table.indexOf(row[i]) + 1;
if (index === 0) {
throw new Error("Invalid row string at" + i);
}
result += index * tableLength ** i;
}
return result;
};
// tests
const testData = [
{
param: "A",
want: 1,
wantErr: false
},
{
param: "1",
want: null,
wantErr: true
},
{
param: "AA",
want: 27,
wantErr: false
}
];
for (const { param, want, wantErr } of testData) {
try {
const got = func1(param);
deepStrictEqual(got, want, `${param} tests failed`);
deepStrictEqual(wantErr, false, `${param} wants no error`);
} catch (e) {
deepStrictEqual(wantErr, true, `${param} wants error`);
}
}
console.log("13.1 Test successful!");
}
// 13.2
{
const func2 = x => {
if (x < 0 || x > 2 ** 32 - 1) {
return "";
}
let result = "";
let xbt = BigInt(x);
const base = BigInt(tableLength);
const one = BigInt(1);
const zero = BigInt(0);
while (xbt > zero) {
const index = xbt % base;
result = table[index - one] + result;
xbt /= base;
}
return result;
};
const testData = [
{
param: 1,
want: "A"
},
{
param: 2,
want: "B"
},
{
param: 27,
want: "AA"
},
{
param: -1,
want: ""
},
{
param: 2 ** 32,
want: ""
}
];
for (const { param, want } of testData) {
deepStrictEqual(func2(param), want, `${param} tests failed`);
}
console.log("13.2 Test successful");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment