I found a solution to this homework question, but I dont feel its the most efficient way to tackle the problem. Interested in other solutions I should explore.
Question: Write a function named allEqual that returns true if every character in the string is the same
Example:
If you pass "aaa" it should return true If you pass "aba" it should return false */
My Code
var stringAE = "aba";
function allEqual(string) {
var stringAENew = "";
for (var i = 0; i < string.length; i++) {
if (string[0] === string[i]) {
stringAENew += string[i];
console.log(stringAENew)
}
}
return stringAENew === string;
}
allEqual(stringAE)
Simple solution using .every()
.
function allEqual(input) { return input.split('').every(char => char === input[0]); } console.log(allEqual('aba')); // false console.log(allEqual('aaa')); // true console.log(allEqual('')); // true
You can return false
immediately once you find a character that doesn't match the first character. If you make it through the whole loop, return true
because all the characters must have matched.
function allEqual(string) {
for (var i = 1; i < string.length; i++) {
if (string[i] != string[0]) {
return false;
}
}
return true;
}
You can also start your loop at i = 1
, since the first character is obviously equal to itself, so there's no need to test it.
Can be done with regex too
function allEqual(str) {
return /^(.)\1*$/.test(str);
}
Although probably not so effective.
This ES6 solution also works for strings with Unicode code points in other than the first plane , ie with codes outside of the 16 bit range:
function allEqual(string) { return [...string].every( (x, _, a) => x === a[0]); } console.log(allEqual('aaaa')); // true console.log(allEqual('aaaba')); // false // Next one fails in solutions that don't support multi-plane unicode: console.log(allEqual('𝌆𝌆𝌆')); // true console.log(allEqual('')); // true
There's no reason to construct a result string. Just go over all the characters and compare them to the first one (as you've been doing). If you found a different character, the result is false
. If you've gone over all the characters and haven't found a different one, the answer is true
(note that this includes the edge cases of an empty string and a single character string):
function allEqual(string) {
for (var i = 1; i < string.length; i++) {
if (string[0] !== string[i]) {
return false;
}
}
return true;
}
I'm a little late for the party, but as I needed to do this on a project, I came up with another approach:
function allEqual(input) { return input === '' || new Set(input).size === 1; } console.log(['', 'aaa', '11', '####', 'aba', '12', '##@%', null, undefined].map(item => ({ item, allEqual: allEqual(item), })));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.