Skip to content

Instantly share code, notes, and snippets.

@nikasulo
Created June 3, 2020 16:42
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 nikasulo/373d740bc47c6fad15287e16ff9a4400 to your computer and use it in GitHub Desktop.
Save nikasulo/373d740bc47c6fad15287e16ff9a4400 to your computer and use it in GitHub Desktop.
The solution to my test
function assertEquals(result, expected) {
if (result !== expected) {
throw new Error(`result: ${result} expected: ${expected}`);
}
}
// No validations needed
// Assume that the string is composed only by (positive) numbers
// NOTE: cannot use parseInt and Number constructor
function parseCoolInteger(value) {
const numbers = {
"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
}
let finalNumber = 0;
const valueLength = value.length;
for (let i=0; i < valueLength; i++) {
let number = numbers[value[i]]
// Calculate the exponent of 10, whether 10, 100, 1000 etc.
let exponent = valueLength - ( i + 1 );
// Multiply the number by the exponent and add it to the result for instance
// In 1234, when i === 0, the line below will be 0 += (1 * (10^1000)) which gives 1000
finalNumber += (number * (10**exponent))
};
return finalNumber;
}
assertEquals(parseCoolInteger("1234"), 1234);
assertEquals(parseCoolInteger("11"), 11);
assertEquals(parseCoolInteger("123456789"), 11);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment