If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.
If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.
Kata #15
DESCRIPTION:
Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
Examples:
Input: 42145 Output: 54421
Input: 145263 Output: 654321
Input: 123456789 Output: 987654321
Starting code:
function descendingOrder(n){
//...
}
My attempt that worked:
function descendingOrder(n){
let nToStr = n.toString().split('').sort((a,b)=>a-b).reverse().join('')
return Number(nToStr)
}
Realized I could still shorten it to this:
function descendingOrder(n){
return Number(n.toString().split('').sort((a,b)=>a-b).reverse().join(''))
}
Or even to this (Hello one-liner club!):
const descendingOrder = n => Number(n.toString().split('').sort((a,b)=>a-b).reverse().join(''))
Let's see what rank #1 in 'Best Practice' has in store for us:
function descendingOrder(n){
return parseInt(String(n).split('').sort().reverse().join(''))
}
I knew parseInt() could've been used for this challenge but I wasn't confident how it's supposed to be used yet so I stuck to what I know.
Rank #2:
function descendingOrder(n){
return +(n + '').split('').sort(function(a,b){ return b - a }).join('');
}
Kinda understand what's going on here but not fully sure as it's the first time I'm seeing this style. Not even sure what to type in a search engine to further my understanding of this. Hopefully I come across this again as I progress through the assigned readings.
Gotta admit, it took a few tries before I arrived at the solution as it's the first time I had to use the .sort() method. Sometimes, it doesn't click even if I'm reading the resources and applying what I've read to the problem. The tactic to finally reach the solution was to realize I was tired after doing about a dozen challenges in one go, leave the problem and take a rest, go back to the classes then come back at it after I'm refreshed.
That's it for Kata #15, stay tuned for more katas to be solved!
Link to Kata #1: Square(n) Sum
Link to Kata #2: Convert a Number to a String
Link to Kata #3: DNA to RNA Conversion
Link to Kata #4: Remove First and Last Character
Link to Kata #5: MakeUpperCase
Link to Kata #6: Total amount of points
Link to Kata #7: A Needle in the Haystack
Link to Kata #8: Sum of positive
Link to Kata #9: Basic Mathematical Operations
Link to Kata #10: Beginner - Reduce but Grow
Link to Kata #11: Square Every Digit
Link to Kata #12: Friend or Foe?