I know whatever program codewars uses does not care about readability (most computer programs don't), but in the real world readability is important.
The first step to refactoring should be creating tests. This way you can easily figure out if you've broken something:
let test1 = getNextNumberOfGreaterSize(12);
let test2 = getNextNumberOfGreaterSize(513);
let test3 = getNextNumberOfGreaterSize(2017);
assertEquals(21, test1);
assertEquals(531, test2);
assertEquals(2071, test3);
function assertEquals(expected, actual) {
if (expected !== actual) {
throw new Error("expected: " + expected + " but was: " + actual);
}
}
While designing tests, you may discover other edge cases such as:
- What if the number given is already the highest?
- What if the number doesn't have any other combinations (such as 11)?
- What if a single digit number is given (1)?
You didn't provide a function name, but assuming it wasn't descriptive, I suggest you change it. It's tricky coming up with a name for such a function (Functions like these probably wouldn't exist in the 'real world'), but this will suffice:something like getNextNumberOfGreaterSize(originalNumber)
Maybe addwith a comment describing what it does.
Set otherNumber
(Note I changed the name to be more readable. Cutting off 3 letters isn't saving you, or the interpreter any time) outside of the while loop and get rid of your if statement:
let otherNum = originalNumber;
while (originalNumber > newNum) {
if (....
Whatever you are doing inside the if statement deserves a comment. YouBetter yet, you should also put it inside a function (especially when you know you'll refactor it later!):
function numbersContainSameDigits(number1, number2) {
return String(number1)
.split("")
.sort()
.join("") ===
String(number2)
.split("")
.sort()
.join("");
}
Now that we got the important stuff (readability) out of the way, let's move onto what you're actually asking for, how. How can we shave a few milliseconds off each run? / Why is coderank telling us the methods too slow?
Computers suck at computing Strings. However they rock at computing numbers. Lets change our code to use numbers and never Strings: