I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.
Today I did: https://www.codewars.com/kata/consecutive-strings/javascript
Time: 20 minutes
What I’ve learnt: I was able to implement manipulating a for loop, by adjusting the value of i
, instead of just setting ` i = 0`. I always feel so in control of my loop when I’m able to implement this. 😉
Since there were certain conditions I can automatically know what it returns (if the second value is greater than the string arrays length, or if the second value is 0 or less), I avoided the iteration and set the return
right away. (This is what we learned from yesterday’s challenge!)
Here was my solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function longestConsec(strarr, k) { let greatestWordComboLength = 0 let finalString = "" if (k > strarr.length || k < 1) return "" for (let i = k-1; i < strarr.length; i++){ let currentComboLength = 0 let currentCombinedString = [] for (let w = 0; w < k; w++){ currentComboLength = currentComboLength + strarr[i - w].length currentCombinedString.unshift(strarr[i - w]) } if (currentComboLength > greatestWordComboLength){ greatestWordComboLength = currentComboLength finalString = currentCombinedString.join("") } } return finalString } |
What I learned from other people’s code:
Slice is something I see very often in other people’s code. It is something I have to get more comfortable with. It will help to manipulate the array on the spot, so I don’t have to make a new array the way I want it to return.
NOTE TO SELF: Start using slice!!
See you tomorrow!!