Day 19 — Alphabet Sequence — Scrimba JavaScriptmas
So this is my solution for the day 19 of #Scrimba #JavaScriptmas challenge. This is not easy for me, because i still a junior developer. But me have a principal
If not start right now, you will never start anything.
So for this write-up, i will try to explain how the code work for this challenge. This is the source code
function alphabetSubsequence(str) { const isSequence = new Set(str); if(isSequence.size < str.length) { return false; }else{ for(let i = 0; str.length + 1; i++){ if(str.charCodeAt(i+1) <= str.charCodeAt(i)){ return false; }else{ return true; } }
}}
In the second line of the code is
const isSequence = new Set(str);
This mean i declare new variable the name is ‘isSequence’ and inside of it is an object properties of Set that has value taken from str. The ‘Set’ object has many properties inside it, but i use ‘size’ for this challenge (The same as the hint). I use ‘size’ for represent an integer value inside the object that declared using object Set.
What i mean is, if i have an array [‘a’, ’b’, ’c’, ‘d’, ‘d’] , using the str method, will give the value of 4, because inside the array there are 4 main string (a, b, c, and d). The duplication of ‘d’ is not counted. For this challenge this is useful to pass the condition that string mustn’t be duplicated.
In the third and four line of the code is
if(isSequence.size < str.length) { return false;
}
What it’s mean, is to check the value of the object.size and str.length, if the object size is bigger than the str length, we can conclude that the parameter one of this challenged doesn’t pass. So it will return false.
In the five until the rest of code is
else{ for(let i = 0; str.length+1; i++){ if(str.charCodeAt(i+1) <= str.charCodeAt(i)){ return false; }else{ return true; } }
}
The first line of it, is else statement, it was taken from the code before. After that, i use for loop, to looping around the string (str). Please pay attention with the ‘i+1’. I use it because it will be usefull later to make code more clean and readable.
Using the charCodeAt method, to determine what is the unicode from the string and make a comparison with one of string before. I mean like this, try in the console
const text = 'gcea'
text.charCodeAt(0) // 103
text.charCodeAt(1) // 99
text.charCodeAt(2) // 101
text.charCodeAt(3) // 97
text.charCodeAt(4) // NaN
What comparison mean, if the second string is bigger than first string (103 > 99) so it will return false, because it doesn’t fill the second requirements of the question. It means the string not write in a sequence. If second checked string is bigger than one string before it (99 < 101), it will return true, because the string number is placed correctly.
And so on, if we run the program, the output will be like this.
If u want to check my progression, here is the link.
Thanks, hope it can give you a bit of understanding.