Reputation: 3
So I'm new to Javascript, just finished a small free online crash course that covers the bare bones basics but I'm still pretty clueless. Found TwilioQuest that takes problems and gets the player to solve them in a game format. One issue has me at the mercy of the same 11 lines of code. The task is write a script that will take two command line arguments - a pair of strings that should be compared to see which one comes first alphabetically (letter casing is not important). The script should determine if the first string is before, after, or in the same position (equal) to the second string, alphabetically. For each case, you should print out a number with console.log. When the first argument is earlier in the alphabet than the second, your script should print -1. When the first argument is the same as the second, your script should print 0. When the first argument is later in the alphabet than the second, your function should print 1.
This is what I have right now and I'm being told that its false or that it doesn't work
const firstValue = process.argv[2];
const secondValue = process.argv[3];
if ((firstValue.toLowerCase() < secondValue.toLowerCase())) {
console.log(-1)
};
if ((firstValue > secondValue)) {
console.log(1);
};
if ((firstValue.ignoreCase == secondValue.ignoreCase)) {
console.log(0);
};
I have tried nesting the conditional operator and I'm still told its wrong
Upvotes: 0
Views: 33
Reputation: 781300
You're only doing the case-insensitive comparison in the first condition. toLowerCase()
doesn't modify the string, so you need to do it in all the comparisons.
But it's easier if you do it once when assigning the variables.
const firstValue = process.argv[2].toLowerCase();
const secondValue = process.argv[3].toLowerCase();
if (firstValue < secondValue) {
console.log(-1);
} else if (firstValue == secondValue) {
console.log(0);
} else {
console.log(1);
}
When you have a series of mutually exclusive tests, you should use else if
and else
so it doesn't perform unnecessary tests.
Upvotes: 1
Reputation: 407
you can use charCodeAt() it provides the ascii value of a string character
const firstValue = process.argv[2];
const secondValue = process.argv[3];
firstValue.toLowerCase()
secondValue.toLowerCase()
if ((firstValue.charCodeAt(0) < secondValue.charCodeAt(0))) {
console.log(-1)
};
if ((firstValue.charCodeAt(0) > secondValue.charCodeAt(0))) {
console.log(1);
};
if ((firstValue.charCodeAt(0) == secondValue.charCodeAt(0))) {
console.log(0);
};
hope this solves your problem
Upvotes: 0