728x90

✨ array의 마지막 값을 제거하고, 제거된 값을 반환한다.
(기존 array가 제거된 상태로 갱신된다)

💻Example Code

const arr = [ 'apple', 'juice', 'flower' ];

console.log( arr.pop() );
console.log( arr );

실행 결과(마지막 값인 flower 반환, 새로운 array 갱신)

😋 큐(Queue) 자료구조(Data Structure)의 remove()에서 사용할 수 있으며, 그 외에도 pop()은 정말 많은 곳에 쓰인다.
array에서 아예 제거된다는 것을 명심하자.
(큐 자료구조는 JavaScript - Data Structures에서 확인 가능하다)

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

 

Array.prototype.pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

developer.mozilla.org

 

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

Array.prototype.map()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
728x90

✨ 배열(array)의 가장 앞에 값을 넣어주고, 새로운 array의 길이를 반환하는 helper method
(Queue와 같이 First In이 필요한 상황에서 사용할 수 있다)

💻Example Code

const arr = [ 3, 4 ];
arr.unshift(1, 2);

console.log( arr );

실행 결과(기존 3, 4 앞에 1, 2가 삽입된 것을 볼 수 있다)

😋 큐(Queue) 자료구조(Data Structure)처럼 항상 값이 가장 앞에 들어가야하는 경우 사용할 수 있다.
큐 자료구조는 JavaScript - Data Structures에서 확인할 수 있다.

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

 

Array.prototype.unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

developer.mozilla.org

 

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

Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
728x90

Q. 값을 다르게 가지고 있는 2개의 큐(Queue)를 1개의 큐(Queue)로 만드는 weave 함수(function)을 만들어라.
(단, 값을 번갈아 넣어야하며, undefined는 없어야 한다.
또한, 어떠한 array도 만들어서는 안 되며, Queue의 add, remove, peek method만 이용하여 작성해야한다)

정답 예시

🎈 먼저, 값이 많이 있기 때문에 반복 작업이 필요하다. 그러니 '반복문'을 먼저 떠올려야할 것이다.
그리고 undefined가 들어가면 안 되니, 값이 있는지를 확인하는 '조건문'이 있어야한다.

값이 있는지 확인하는 peek()반복문의 조건으로 넣을 수 있을 것이다. 값이 있다면 '반복'해야하니까.
그리고 또한 한쪽의 값이 먼저 다 소진될 수 있으니, 반복문 안에서도 값이 있는지 또 확인하는 조건문도 필요하다.

조건이 맞는다면 해당 큐에서 값을 제거한다. remove()
그리고 새로운 큐에 값을 넣어준다. add()

위처럼 간단하게 생각하고 시작하면 된다.

🔮 가장 먼저, 새로운 큐를 만들어줘야한다. const q = new Queue();
반복문의 조건while( srcOne.peek() || srcTwo.peek() )을 넣어 둘 중 하나의 큐에 값이 있다면 반복한다.
조건문 if ( srcOne.peek() )if ( srcTwo.peek() )을 넣어줘서, 둘 중 하나의 큐라도 값이 있다면 실행시킨다.
if의 내부에서는 q.add( srcOne.remove() )를 통해 기존 값을 새로운 큐(q)에 넣어준다.

이렇게 반복해주면 번갈아 값을 넣는 weave algorithm이 완성된다.

Weave Algorithm 정답

Full Code

function weave(sourceOne, sourceTwo) {
const q = new Queue();
 
while (sourceOne.peek() || sourceTwo.peek()) {
if (sourceOne.peek()) {
q.add(sourceOne.remove());
}
if (sourceTwo.peek()) {
q.add(sourceTwo.remove());
}
}
 
return q;
}
728x90

큐의 정의(Definition of Queue)

🎈 위 그림에서 볼 수 있듯, Queue의 실행 순서는 FIFO로 진행된다.
FIFO란 First In First Out의 약자로서, 처음 들어간 값이 가장 먼저 나올 수 있다. 선입선출이라고 생각하면 쉽다.

Queue는 기본적으로 추가( add() ), 삭제( remove() ) 기능을 사용하여 다루며,
마지막 값 보기( peek() ) 기능처럼 본인이 필요한 기능을 만들어 사용하면 된다.

JavaScript의 class를 이용하여 Queue를 만들어 보겠다.

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/d869a976ec23478534e899b54d7e2b9160698639/exercises/weave/queue.js

😐 위에서 볼 수 있듯, Queue의 전체 뼈대는 생성자(constructor)를 이용하여 array를 선언해준다.

Array의 helper method

add()에서는 Array.prototype.unshift()를 이용하여, 값이 항상 Queue의 앞으로 들어가게 구성해준다.

remove()에서는 Array.prototype.pop()를 이용하여, 항상 (먼저 들어간)마지막 값이 나올 수 있게 구성한다.

peek()에서는 index에 [this.data.length-1]을 넣어줘서 값이 있다면 마지막 값을, 없다면 undefined를 return하게 해준다.

🎉이렇게 class를 작성해주면, FIFO(First In First Out)기능을 하는 기본 Queue를 만들어낼 수 있다.

다음 글에서는 값이 다른 2개의 큐(Queue)를 1개의 큐(Queue)로 만들어보는 자료구조를 이용한 알고리즘에 대해 작성해보겠다.

Full Code

class Queue {
constructor() {
this.data = [];
}
 
add(record) {
this.data.unshift(record);
}
 
remove() {
return this.data.pop();
}
 
peek() {
return this.data[this.data.length - 1];
}
}
728x90

✨ASCII Code를 string으로 반환해주는 helper method

💻Example Code

console.log( String.fromCharCode(97) );
console.log( String.fromCharCode(113) );
console.log( String.fromCharCode(65) );

실행 결과(ASCII Code 97은 'a', 113은 'q', 65는 'A'라는 것을 알 수 있다)

😋 ASCII Code를 활용하는 문제를 풀 때 간혹 필요할 수 있다. ASCII Code를 string으로 바꿔준다.
백준 알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

ASCII Code

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

 

String.fromCharCode()

The static String.fromCharCode() method returns a string created from the specified sequence of UTF-16 code units.

developer.mozilla.org

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

Array.prototype.pop()  (0) 2020.01.04
Array.prototype.unshift()  (0) 2020.01.04
Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
728x90

✨ 주어진 array에서 찾고자하는 element의 index를 반환, 없다면 -1을 반환하는 helper method
(index는 가장 먼저 발견된 element 기준으로 반환된다)

💻Example Code

const arr = 'gamgongsa';

console.log( arr.indexOf('a') );
console.log( arr.indexOf('g') );
console.log( arr.indexOf('z') );

실행 결과('a'의 index는 1, 'g'의 index는 0, 'z'는 없기 때문에 -1)

😋 긴 문자열이 주어지고, 여기서 내가 원하는 알파벳이 있는지 없는지를 확인하고자 할 때 쓰기 좋은 helper method
알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

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

 

Array.prototype.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

developer.mozilla.org

 

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

Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
728x90

✨ 내가 찾고자하는 Pattern(character or string etc)을 찾기에 유용한 helper method
(Pattern은 사실 Regular Expression(정규표현식)이지만 쉽게 표현하기 위해 사용하였다)

💻Example Code

const str = 'Hi There!!';
const matches = str.match(/[aeiou]/gi);

console.log( matches );
console.log( matches ? matches.length : 0 )

실행 결과(match된 내용과 배열의 길이)

😋 특히, 특정 문자열을 검색하는 알고리즘 문제를 풀거나, 개발을 할때 매우 유용하다. (단, RegExp를 잘 안다는 전제하에)
Vowels Algorithm(모음 찾기) 문제를 풀 때 잘 사용했다.

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

 

String.prototype.match()

The match() method retrieves the result of matching a string against a regular expression.

developer.mozilla.org

 

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

String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
728x90

✨ 말 그대로 '기본 값 설정' + '나머지' + '펼치기(?)'를 사용하는 방법이다.

💻Example Code

Default
function f1(x, y = 0) {
  return x + y; }

console.log(f1(3) === 3);

Rest
function f2(x, ...y) {
  return x * y.length; }

console.log(f2(2, 'hi', true) === 4);

Spread
function f3(x, y, z) {
  return x + y + z; }

console.log(f3(...[1, 2, 3]) === 6);

실행 결과(모두 true로 출력)

😋 먼저, parameter default는 재귀함수를 사용할 때 유용하다. 굳이 선언을 따로 하지 않고, parameter에서 해결이 가능하기 때문이다. Rest는 아직 사용해본 적은 없지만, 종종 쓰일 것 같고, Spread는 알고리즘 문제를 풀 때와 개발을 할 때 꽤 많이 썼다. 특히, fibonacci, sort 그리고 levelWidth 등 다양한 곳에서 사용했다. 몇 줄이나 나와야할 코드를 단 한 줄로 해결하기에 굉장히 좋다.

👉 자세한 내용은 https://babeljs.io/docs/en/learn/#default-rest-spread

 

Babel · The compiler for next generation JavaScript

The compiler for next generation JavaScript

babeljs.io

 

'JavaScript > ES5, ES6+' 카테고리의 다른 글

Template Strings  (0) 2020.01.25
728x90

✨ 원하는 알파벳이나 숫자(0-9)의 아스키 코드(ASCII Code)를 알고 싶을 때, 사용하는 helper method
(e.g., str.charCodeAt(0)) 왼쪽처럼 알고 싶은 string의 index를 넣어서 사용한다. ()안에 아무것도 넣지 않으면 default 0
백준 11654번: 아스키 코드,  10809번: 알파벳 찾기 문제를 풀 때 사용하였다.

💻Example Code

const str = 'a';
const numStr = '1';

console.log( str.charCodeAt(0) );
console.log( numStr.charCodeAt(0) );
console.log( 'a'.charCodeAt(0) );

실행 결과('a'는 97, '1'은 49, 'A'는 65)

😋 JavaScript에서 string의 ASCII Code를 알고 싶을 때 사용하면 된다.

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

 

String.prototype.charCodeAt()

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

developer.mozilla.org

 

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

Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
728x90

✨ if else 문법을 간단하게 쓰고 싶을 때 사용하는 ternary operator(삼항 조건 연산자)

💻Example Code

const a = 11;
const b = 77;

a < b ? console.log('true') : console.log('false');

실행 결과(a는 b보다 작기 때문에 true를 출력)

😋 if else는 많은 줄을 차지하는 반면에, ternary operator(삼항 연산자)를 사용하면 최소 한 줄로 줄일 수 있다.
간결한 코드 작성을 원할 때, 매우 유용하다.

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

 

Conditional (ternary) operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execu

developer.mozilla.org

 

'JavaScript > Grammar' 카테고리의 다른 글

for...in  (0) 2019.12.27
for...of  (0) 2019.12.27

+ Recent posts