JSFiddle - React, Tailwind, and code Playground
by kkdaily
JavaScript
/* determine if a string has all unique chars */
// turn string into an array
// iterate over the array of chars
// for each char, look up whether that char has been seen already
// if not, store the char as a key value in a hash table and continue iterating
// otherwise, exit the loop and return false
// SPECIAL CASES
// if the array is length 1, return true
// if the array length > 1, put the first char into the hash table first before comparison logic
//ex: 'dog'
const uniqueStringCheck = (str) => {
if (str.length <= 1) {
return false;
}
const chars = str.split('');
let charsSeen = {};
let strIsUnique = true;
for (let i = 0; i < chars.length; i++) {
let char = chars[i];
if (charsSeen[char]) {
strIsUnique = false;
break;
}
charsSeen[char] = char;
}
return strIsUnique;
};
let a = uniqueStringCheck('dog');
alert(a);