문자열을 받아들이고 그 알파벳을 미러링하는 함수를 작성해야 합니다. 예를 들어 -
If the input is ‘abcd’ The output should be ‘zyxw’
이 함수는 단순히 모든 문자를 가져와서 (26 - N) 알파벳만큼 멀리 매핑합니다. 여기서 는 e의 경우 5, j의 경우 10과 같이 해당 알파벳의 1 기반 인덱스입니다.
여기서는 String.prototype.replace() 메서드를 사용하여 대소문자에 관계없이 모든 영어 알파벳을 일치시킵니다. 이 함수의 전체 코드는 -
입니다.예
const str = 'ABCD';
const mirrorString = str => {
const regex = /[A-Za-z]/g;
return str.replace(regex, char => {
const ascii = char.charCodeAt();
let start, end;
if(ascii > 96){
start = 97;
end = 122;
} else {
start = 65;
end = 90;
}
return String.fromCharCode(end - (ascii-start));
});
}
console.log(mirrorString(str));
console.log(mirrorString('Can we flip this as well'));
console.log(mirrorString('SOME UPPERCASE STUFF')); 출력
콘솔의 출력은 -
ZYXW Xzm dv uork gsrh zh dvoo HLNV FKKVIXZHV HGFUU