문자열을 받아 정렬 여부를 확인하는 JavaScript 함수를 작성해야 합니다.
예를 들어 -
isSorted('adefgjmxz') // true
isSorted('zxmfdba') // true
isSorted('dsfdsfva') // false 예시
다음은 코드입니다 -
const str = 'abdfhlmxz';
const findDiff = (a, b) => a.charCodeAt(0) - b.charCodeAt(0);
const isStringSorted = (str = '') => {
if(str.length < 2){
return true;
};
let res = ''
for(let i = 0; i < str.length-1; i++){
if(findDiff(str[i+1], str[i]) > 0){
res += 'u';
}else if(findDiff(str[i+1], str[i]) < 0){
res += 'd';
};
if(res.indexOf('u') && res.includes('d')){
return false;
};
};
return true;
};
console.log(isStringSorted(str)); 출력
이것은 콘솔에 다음과 같은 출력을 생성합니다 -
true