https://programmers.co.kr/learn/courses/30/lessons/12926/solution_groups?language=javascript
체감 난이도 : ☆☆☆
function solution(str, num) {
const alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',];
let result = '';
for (let i = 0; i < str.length; i += 1) {
// 1.공백이면 그냥 공백으로 리턴
if (str[i] === ' ') {
result += ' ';
continue;
}
let idx = alpha.findIndex((el) => el === str[i]);
if (idx >= 0) {
// 2.소문자인 경우
let position = idx + num; // 26
if (position > alpha.length - 1) {
// 26 > 25
position -= alpha.length;
}
result += alpha[position];
continue;
} else {
// 3.대문자인 경우
idx = alpha.findIndex((el) => el === str[i].toLowerCase());
let position = idx + num;
if (position > alpha.length - 1) {
position -= alpha.length;
}
result += alpha[position].toUpperCase();
}
}
return result;
}
// 실행코드
console.log(solution('Ab', 1)); /// BC
console.log(solution('z', 1)); // a
console.log(solution('a B', 1)); // b C
console.log(solution('a B z', 4)); // e F d
function solution(str, num) {
const lower = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',];
const upper = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',];
let result = '';
for (let i = 0; i < str.length; i += 1) {
// 1. 공백이면 공백을 더함
if (str[i] === ' ') {
result += ' ';
continue;
}
// 2.대문자인지 소문자인지 구별
const arr = lower.includes(str[i]) ? lower : upper;
// 3.인덱스 값을 찾아 num을 더한 인덱스 값을 찾음
let index = arr.indexOf(str[i]) + num;
if (index > arr.length - 1) {
index -= arr.length;
}
result += arr[index];
}
return result;
}
// 1.split으로 str을 배열로 만든 후
// 2.map을 돌면서 해당 인덱스+num 인 요소를 찾아 반환함.
// 3.map의 결과를 join하여 문자열로 반환.
function solution(str, n) {
const alpha = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXY ';
return str
.split('')
.map((el) => alpha[alpha.indexOf(el) + n])
.join('');
}
indexOf()는 매개변수에 "찾으려는 값"이 들어감,
findIndex()는 매개변수에 "콜백함수"가 들어감
const str = 'abcdefg hijk lmnop';
console.log(str.indexOf('cde')); // 2
console.log(str.indexOf('a', 3)); // -1 // 3번째 인덱스인 d부터 찾기 시작하라는 뜻
const array1 = [5, 12, 8, 130, 44];
console.log(array1.findIndex((el) => el > 13)); // 3 (요소 130의 인덱스값이 나옴)