728x90

Q. 주어진 String(문장)에서 각 단어의 첫 알파벳을 대문자로 바꿔라.

--- Examples
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/08ffc38c2f7b32b8baa35a6ecfc6c1d367559b1c/exercises/capitalize/index.js

😢 배열(Array)의 index을 이용해서 원초적 해결하려 했더니 조금 힘들었다.

😊 Solution 1)
입력받은 str을 split(' ')을 이용해 각 단어별로 나눠진 Array를 만들어주고,
for ... of loop 안에서 각 단어를 하나씩 가져와, 첫 번째 알파벳은 대문자로, 나머지 값은 slice(1)로 붙여주었다.
그리고 join(' ')을 이용해 다시 String(문장)으로 만들어 반환해주었다.

Solution 2)
classic for loop을 이용해 각 index의 앞(i-1)이 ' '(space)라면 해당 index(i)를 대문자로 변환하여 저장한다.
그게 아니라면, 해당 index(i)를 단순 저장해준다.

✔ toUpperCase()

소문자를 대문자로 변환해준다.

✔ split(' ')

String을 ' '(space)기준으로 나눠서 array에 저장해준다

✔ slice(1)

index 1부터 끝까지 모두 slice해준다

✔ for ... of

Array의 안에 있는 값을 index 순서대로 하나씩 가져온다

✔ join(' ')

' '(space)기준으로 Array를 String(문장)으로 합쳐준다

Full Code

function capitalize(str) {
let result = str[0].toUpperCase();
 
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === ' ') {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
 
return result;
}
 
// function capitalize(str) {
// const words = [];
 
// for (let word of str.split(' ')) {
// words.push(word[0].toUpperCase() + word.slice(1));
// }
 
// return words.join(' ');
// }
728x90

Q. 주어진 array를 주어진 size만큼 잘라서 sub array로 넣어라.

--- Examples
chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/master/completed_exercises/chunk/index.js

😢 undefined 개념, 배열의 마지막 index를 지정하는 방법 그리고 slice를 활용하는 방법을 몰라서 많이 고민했다.

😊 Solution 1)
주어진 array 값을 for ... of를 통해 element로 하나씩 가져오고, 새로운 chunk array가 비어(undefined)있거나 size만큼 꽉차면 새로운 sub array를 push하고, 그게 아니라면 chunk array의 마지막 index sub array에 element를 push하여 해결한다.

Solution 2)
index를 size만큼 쌓아올리는 index 변수를 선언하여, slice(index, index + size); index += size; 를 while loop안에서 반복해준다. 그렇게하면 주어진 길이만큼 slice하여 sub array로 push할 수 있다.

✔ undefined 이용

!undefined는 true

✔ slice(begin, end)

시작부터 끝 전 index까지 array를 잘라준다.
(자세한 내용은 helper method 카테고리에서 확인 가능하다)

Full Code

function chunk(array, size) {
const chunked = [];
let index = 0;
 
while (index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
}
 
return chunked;
}
 
// function chunk(array, size) {
// const chunked = [];
//
// for (let element of array) {
// const last = chunked[chunked.length - 1];
//
// if (!last || last.length === size) {
// chunked.push([element]);
// } else {
// last.push(element);
// }
// }
//
// return chunked;
// }
728x90

✨ 배열(array)을 원하는 크기 만큼 자르고 싶을 때 사용하는 helper method(원래 값은 유지되며, copy개념이다)
(e.g., arr.slice(0,2)) 왼쪽처럼 시작(0), 끝(2) index를 지정해주면, array의 0부터 1 index까지 값을 얻어낼 수 있다.
slice( '시작', '여기 바로 앞까지' )으로 기억해주면 편하다.
Capitalize, Chunk and Merge Sort Algorithm 에서 유용하게 사용하였다.

💻Example Code

const arr = [ 1, 2, 3, 4, 5 ];

console.log( arr.slice(0,2) );

실행 결과(0부터 1 index까지 출력)

😋 자주 사용하지 않다가 사용하면, 어디까지 array가 잘리는지 헷갈리기 쉬운 helper method이다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Global.parseInt()  (0) 2019.12.24
Math.sign()  (0) 2019.12.24
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
Function.prototype.apply()  (0) 2019.12.22

+ Recent posts