728x90

✨ Array에 내가 입력한 값(String or Number etc.)이 포함되어 있는지 확인할 때 사용하는 helper method

(e.g., strArr.includes('a')) 왼쪽처럼 strArr이라는 Array에 'a'가 있다면 true, 없다면 false를 return.
Vowels(모음 찾기) Algorithm에서 유용하게 사용하였다.

 

💻Example Code

const strArr = [ 'a', 'b', 'c' ];

console.log( strArr.includes('a') );

실행 결과( 'a'가 포함되어있기 때문에 true 출력 )

😋 Vowels(모음 찾기) Algorithm을 풀 때, 주어진 String에서 모음(a, e, i, o, u)이 몇 개인지 찾을 때 매우 유용하다.
더 활용된 내용은 Algorithm 카테고리의 Vowels(모음 찾기) Algorithm을 참고하시면 됩니다. 

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

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

Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24
728x90

✨ 직접 작성한 function을 주입하여, 각 elements를 test 할 수 있는 helper function

(e.g., arr.every(char => char === 'a')) 왼쪽처럼 test할 function을 주입하고, arr의 값이 1개 있다고 가정할 때, 그 arr의 값이 'a'와 동일하다면 true가 반환될 것이고, 아니라면 false가 반환될 것이다.
Palindrome(회문 구조) Algorithm에서 유용하게 사용하였다.

💻Example Code

const arr = [ 'a' ];

console.log( arr.every((char, index) => char === arr[index]));

실행 결과(값이 같기 때문에 true)

😋 Palindrome과 같이 전체 array를 처음부터 또는 마지막부터 하나씩 검사하기에 좋다.
더 활용된 내용은 palindrome algorithm을 참고하면 됩니다.

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

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

String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.reduce()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24
Array.prototype.reverse()  (0) 2019.12.24
728x90

✨직접 작성한 reducer function을 주입하여, 배열(array)의 여러 값을 하나씩 다루고, 최종적으로 single value를 도출해낸다.

(e.g., arr.reduce((acc, val) => acc += val)) 왼쪽처럼 기본적으로 첫 번째 argument는 accumulator, 두 번째 argument는 Current Value이며, 그 외에 세 번째 argument는 Current Index이며, reduce()의 두 번째 arugument에 initialValue(초기값)을 작성하여 acc에 초기값을 지정하는 것도 가능하다.
Reverse Int(or String)와 palindrome(회문 구조) 등 다양한 로직에서 유용하다.

💻Example Code

const numArr = [ 1, 2, 3, 4 ];
const strArr = [ 'b', 'c', 'd', 'e' ];

console.log(numArr.reduce((acc, num) => (acc = num + acc), 10));
console.log(strArr.reduce((rev, char) => (rev = char + rev), 'a'));

실행 결과(10+10=20, a+bcde를 거꾸로하면 edcba)

😋 배열의 모든 값을 간단하게 더하고 싶을 때, 배열의 문자를 거꾸로 정렬하고 싶을 때 등 다양한 기능에서 활용이 가능하다.

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

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

Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24
Array.prototype.reverse()  (0) 2019.12.24
Number.prototype.toString()  (0) 2019.12.24
728x90

✨ 배열(array)을 하나의 string으로 합쳐줄 때 사용하는 helper method

(e.g., arr.join('')) 왼쪽처럼 배열 arr 변수가 있을 때, join() 괄호 안에 원하는 separator를 넣어 배열을 하나의 string으로 합칠 수 있다.
Anagram(철자 순서를 바꾼 말), Capitalize(단어의 첫번째 문자 대문자화 하기), palindrome(회문 구조) 그리고 Reverse Int(or String)숫자나 문자 순서 뒤바꾸기 Algorithm에서 유용하게 사용했다.

💻Example Code

const arr = [ 'l', 'o', 'v', 'e' ];

console.log( arr.join('') );

실행 결과(문자 중간에 separator 없이 모두 합침)

😋 Algorithm에서 test case로 문자 또는 숫자가 입력되었을 때, 배열로 전환하고 다시 문자 또는 숫자로 합칠 때 사용할 수 있다.

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

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

Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24
Array.prototype.reverse()  (0) 2019.12.24
Number.prototype.toString()  (0) 2019.12.24
Global.parseInt()  (0) 2019.12.24
728x90

✨ 배열(array)의 순서를 정반대로 뒤바꾸고 싶을 때 사용하는 helper method

(e.g., arr.reverse()) 왼쪽처럼 배열 arr 변수가 있을 때, reverse() 를 이용하여 배열 순서를 정반대로 뒤바꿀 수 있다.
Reverse Int(숫자 거꾸로 바꾸기), Reverse String(문자열 거꾸로 바꾸기) 그리고 Palindrome(회문 구조) Algorithm에서 유용하게 사용했다.

💻Example Code

const arr = [ 'a', 'b', 'c' ];

console.log( arr.reverse() );

실행 결과(순서가 정반대로 뒤바뀜)

😋 Reverse Int(or String)은 말 그대로 순서를 뒤바꿔 줘야하기 때문에 reverse()는 매우 유용하며,
palindrome(회문 구조)는 순서가 뒤바뀌어도 같아야하기 때문에 역시 reverse()는 매우 유용하다.

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

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

Array.prototype.reduce()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24
Number.prototype.toString()  (0) 2019.12.24
Global.parseInt()  (0) 2019.12.24
Math.sign()  (0) 2019.12.24
728x90

✨ 숫자(number)를 문자열(string)로 바꿔주는 helper method

(e.g., num.toString()) 왼쪽처럼 num 변수에 숫자가 선언되어 있을 때, 문자열로 변환하여 다른 변수에 저장할 수 있다.
Rever Int(숫자 거꾸로 바꾸기) Algorithm에서 유용하게 사용했다.

💻Example Code
✅ String와 Number를 비교하는 코드로 작성한다.

const num = 31;
const numToString = num.toString();

console.log( num );
console.log( numToString );
console.log( typeof num );
console.log( typeof numToString );

실행 결과(Number, String 순서) - VS Code Node.js 기준

😋 Reverse Int(숫자 거꾸로 바꾸기) Algorithm을 다룰 때, 처음에 받은 case test를 toString()으로 변환 후 문자를 다룬다.
즉, 해당 number를 string으로 바꾼 후 index를 직접 특정하여 다루고 싶을 때 유용하게 사용할 수 있다.

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

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

Array.prototype.join()  (0) 2019.12.24
Array.prototype.reverse()  (0) 2019.12.24
Global.parseInt()  (0) 2019.12.24
Math.sign()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
728x90

✨ string을 integer(number)로 바꿔주는 helper method

Reverse Int(숫자 거꾸로 바꾸기) Algorithm에서 유용하게 사용했다.
(string 변환 후 다시 integer로 되돌려야하기 때문이다)

💻Example Code
✅ String와 Number를 비교하는 코드로 작성한다.

const str = '24';

console.log( parseInt(str) );
console.log( str );
console.log( typeof parseInt(str) );
console.log( typeof str );

실행 결과(Number, String) - VS Code Node.js 기준

😋 Reverse Int (숫자 거꾸로 바꾸기) Algorithm을 다룰 때, string 변환 후 최종값을 number로 되돌리기 위해 사용한다.

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

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

Array.prototype.reverse()  (0) 2019.12.24
Number.prototype.toString()  (0) 2019.12.24
Math.sign()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
728x90

✨number 의 부호를 알아내기 위한 helper method

기본적으로 양수(positive) 또는 음수(negative) 1을 반환하며(+/- 1), 괄호 안에 0을 넣는다면 +/- 0을 반환한다.
(양수는 +로 표기하지 않고 생략한다)
Reverse Int(숫자 거꾸로 바꾸기) Algorithm에서 유용하게 사용했다.
(number를 string으로 바꿔 다루는 경우, 최종값은 number로 반환해야 하기 때문에 부호를 되찾을 때 사용한다)

💻Example Code

const num = -24;

console.log( Math.sign(num) );

실행 결과 (-1)

😋 Reverse Int algorithm을 다룰 때, test case로 주어진 number값을 string으로 변환 후 순서를 뒤바꿔 줘야한다.
따라서, 마지막 결과값을 return 해줄 때, Math.sign(test case값)을 곱해주면 본래의 부호를 손쉽게 다시 되찾을 수 있다.

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

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

Number.prototype.toString()  (0) 2019.12.24
Global.parseInt()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
728x90

Q. 주어진 string의 회문 구조를 파악하고, 맞으면 true 틀리면 false를 return하라.

--- Examples
palindrome("abba") === true
palindrome("abcdefg") === false

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/efd69d6b976fab583958556518cf5b3162275d67
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/efd69d6b976fab583958556518cf5b3162275d67

😢 reverse int and string에서 배웠던 Skill로도 충분했지만, 다른 방법을 적용해보고 싶었다.

😊 every()를 이용하여 주어진 string argument를 검사하는 방식을 배울 수 있었다.

✔ Array.prototype.every()

every() 괄호 안에 test function을 작성하여, 해당 array값을 이용해 test할 수 있다.
위의 소스코드에서는 char === str[str.length - i - 1]을 이용하여 맨 앞과 맨 뒤의 값을 하나씩 이동하며 비교하였다.
자세한 every() 사용법은 helper methods category에서 다루도록 하겠다.

Full Code

function palindrome(str) {
return str.split('').every((char, i) => {
return char === str[str.length - i - 1];
});
}
 
// function palindrome(str) {
// let reversed = str
// .split('')
// .reverse()
// .join();
// return str === reversed;
// }
728x90

Q. 주어진 integer를 정반대로 뒤바꾸고 return하라.

--- Examples
reverseInt(15) === 51
reverseInt(981) === 189
reverseInt(500) === 5
reverseInt(-15) === -51
reverseInt(-90) === -9

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/ccd99f2e87c5836d5e0b22793caf882e652d9529
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/ccd99f2e87c5836d5e0b22793caf882e652d9529
https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/ccd99f2e87c5836d5e0b22793caf882e652d9529

😢 정반대로 바꾸는 것은 문제가 없었으나, 부호를 살리는 것과 다시 num type 으로 바꾸는 것에 대해서 어떻게 효율적으로 코드를 작성할 수 있을지 조금 고민을 했다.

😊 Math.sign()을 이용해 깔끔하게 부호를 살릴 수 있었고, Reverse String에서 쓰던 Skill들을 그대로 사용하였다.
그 외에 추가된 Skill은 toString(), parseInt()가 있다.

✔ Math.sign()

Math.sign()를 이용해 해당 변수의 부호를 알아내고 활용할 수 있다.
위의 소스코드에서 보면 알 수 있듯, arguments로 들어오는 n의 부호를 마지막에 곱해주어 해당 -(negative)를 다시 살려주었다.

✔ Number.prototype.toString()

처음에 들어오는 arguments가 number type이므로 reverse()를 이용할 것이라면 toString()으로 반드시 변환해줘야 한다.
그리고 reverse()를 사용하기 전에 split()사용하여 array로 반드시 변환해줘야 한다. Array.prototype.reverse()이기 때문이다.

✔ Global.parseInt()

string과 array를 이용해 number를 뒤바꾸어 주었으니, 최종값은 parseInt()를 이용해 number type으로 변환해야 한다.

Full Code

function reverseInt(n) {
let reversed = n
.toString()
.split('')
.reverse()
.join('');
return parseInt(reversed) * Math.sign(n);
}
 
// function reverseInt(n) {
// let rev = '';
 
// for (let num of n.toString()) {
// rev = num + rev;
// }
 
// return Math.sign(n) * parseInt(rev);
// }
 
// function reverseInt(n) {
// return (
// Math.sign(n) *
// parseInt(
// n
// .toString()
// .split('')
// .reduce((rev, num) => (rev = num + rev))
// )
// );
// }

+ Recent posts