WEIL은 WeekEnd I Learnedd...
JavaScript로 코테를 준비하면서 자주사용한 메서드들을 정리하려고 한다.
python의 enumerate 와 같은 기능을 한다
a = [1, 3, 45, 2, 10];
a.forEach((elem , idx)) => {
console.log(elem, idx); // 1 0 ....
}
const str = "Hello World";
const ret = str.split(" ")
console.log(ret); // [ 'Hello', 'World' ]
const a = ret.join(' ');
console.log(a); // Hello World
const b = ret.join("bar")
console.log(b); // HellobarWorld
const nums = [1, 2, 3, 4]
const even = nums.find((e) => e % 2 == 0);
console.log(even); // 2
const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
const nums = [1, 2, 3, 4]
const even = nums.findIndex((e) => e % 2 == 0);
console.log(even); // 1
파이썬의 in 연산자와 동일한 역할
const nums = [1, 2, 3, 4]
console.log(nums.includes(3)) // true
console.log(nums.includes(5)) // false
const str = "ABCDE";
console.log(str.substring(1, 3)); //BC
const str1 = "Saturday night plans";
console.log(str1.startsWith("Sat"));
// Expected output: true
복사기에 원본은 그대로 유지가 된다
const list = [1, 2, 3, 4, 5];
console.log(list.slice(1, 3)) //[ 2, 3 ]
삭제, 추가 둘다 가능한 만능 메서드인데 단 원본 바꿈.
let fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 1); // idx 1 부터 1개 삭제
console.log(fruits); // ['apple', 'cherry']
let fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 0, 'kiwi');
console.log(fruits); // ['apple', 'kiwi', 'banana', 'cherry']
배열도 객체라서 사용가능한데 , Object.keys()에 인자로 배열을 넘기면 인덱스가 나옴.
const myObject = {
name: '싹쓰리',
enName: 'SSAK3',
members: ['유두래곤', '린다G', '비룡'],
genre: 'Dance & pop',
agency: 'MBC',
making: '놀면뭐하니?'
}
const myKeys = Object.keys(myObject);
const myVals = Object.values(myObject);
console.log(myVals);
// ['싹쓰리','SSAK3',[ '유두래곤', '린다G', '비룡' ],'Dance & pop','MBC','놀면뭐하니?']
console.log(myKeys);
// ["name", "enName", "members", "genre", "agency", "making"]
{Key : value} ⇒ [key, value]
이렇게 바꾸어주어서, Array 메서드들(filter, find, forEach)을 사용할 수 있다.
const myObject = {
name: '싹쓰리',
enName: 'SSAK3',
members: ['유두래곤', '린다G', '비룡'],
genre: 'Dance & pop',
agency: 'MBC',
making: '놀면뭐하니?'
}
const maArrs = Object.entries(myObject);
console.log(maArrs);
/*
[
[ 'name', '싹쓰리' ],
[ 'enName', 'SSAK3' ],
[ 'members', [ '유두래곤', '린다G', '비룡' ] ],
[ 'genre', 'Dance & pop' ],
[ 'agency', 'MBC' ],
[ 'making', '놀면뭐하니?' ]
]
*/
console.log(maArrs.filter((elem) => elem[0] === 'name')); // [ [ 'name', '싹쓰리' ] ]
console.log(maArrs.find((elem) => elem[0] === 'name')); // [ 'name', '싹쓰리' ]
sort에 아무 인자도 안넘겨주면 js는 문자열의 UniCode 순이기에 의도한 순서가 아닐 수 있다.
반드시 인자를 넘겨줍시다.
let numbers = [2, 5, 21, 1, 4, 7, 8, 9];
numbers = numbers.sort((a, b) => a - b); // 오름 차순 정렬
console.log(numbers); // [1, 2, 4, 5, 7, 8, 9, 21 ]
let numbers = [2, 5, 21, 1, 4, 7, 8, 9];
numbers = numbers.sort((a, b) => a - b);
console.log(numbers.filter((elem) => elem % 2 == 0)) // 짝수만 찾기 2 4 8
let numbers = [2, 5, 21, 1, 4, 7, 8, 9];
const ret = numbers.map(e => e * 2) // 새로운 배열 생성
console.log(ret); // [4, 10, 42, 2,8, 14, 16, 18]
const number = [1, 2, 3, 4, 5]
const ret = number.reduce((total, e) => total + e); // total 변수에 배열 요소 모두 더하기
const ret_100 = number.reduce((total, e) => total + e + 100); // total 변수에 배열 요소 모두 더하기 + 100
console.log(ret); // 15
const graph = {
1: [2, 3],
2: [4],
3: [4, 5],
4: [],
5: []
};
let visited = [];
function dfs(start) {
if (visited.includes(start)) {
return;
}
visited.push(start);
console.log(start)
graph[start].forEach(e => dfs(e));
/* for(let i = 0; i < graph[start].length; i++){
dfs(graph[start][i]);
} */
/*
for(let neighbor of graph[start]){
dfs(neighbor);
}
*/
}
dfs(1);
function BFS(graph, start, visited) {
const queue = [];
queue.push(start);
visited[start] = true;
while (queue.length != 0) {
const v = queue.shift();
console.log(v);
for (const node of graph[v]) {
if (!visited[node]) {
queue.push(node);
visited[node] = true;
}
}
}
}
let visited = new Array(5).fill(false)
BFS(graph, graph[0], visited)
const a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let start = 0
let end = a.length - 1;
let mid
function binary_search(target) {
while (start <= end) {
mid = Math.floor((start + end) / 2);
if (a[mid] == target) {
console.log(target);
return;
} else if (a[mid] > target) {
end = mid - 1
} else {
start = mid + 1
}
}
}
binary_search(4);
let a = Array(50).fill(0); // 0이 50개 들어간 1차원 배열
let apt = Array.from({length : 5}, ()=> Array(4).fill(0))// 5(row) * 4(col) 짜리 2차원 배열
console.log(apt)
/*
[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]
]
*/
function fibo(N, memo = []) {
if (N <= 2) {
return 1;
}
if (N in memo) {
return memo[N]
}
memo[N] = fibo(N - 1, memo) + fibo(N - 2, memo);
return memo[N]
}
console.log(fibo(10));
function solution(n) {
var answer = [];
function move(start, end){
answer.push([start, end])
}
function hanoi(n, start, end, mid){
if(n == 1){
move(start, end)
} else {
hanoi(n - 1, start, mid, end);
move(start, end);
hanoi(n - 1 , mid, end, start);
}
}
hanoi(n, 1, 3, 2)
return answer;
}
const arr = [1, 2, 3, 4, 5];
[arr[1], arr[3]] = [arr[3], arr[1]]
console.log(arr); //[ 1, 4, 3, 2, 5 ]
초기화 없이 값부터 냅다 집어넣으려면 에러가 발생해서 if문으로 null 체크 후 value값을 더하는데
이를 or 연산자를 활용해서 좀 더 쌈뽕하게 코딩 가능.
보통 초기화가 안된채로 선언하면 undefined를 반환하는데,
undefined는 falsy한 값이라 0 이 되고,
초기화가 안된 상태라면 0 || 0 이라서 0을 반환하게되고
이미 값이 집어넣어진 상태라면 xCounts[point[0]] || 0 라서 xCounts[point[0]] 를 반환하게 된다.
for(let elem of nums){
if(map[elem] == null){
map[elem] = 0
}
map[elem]++;
}
for (const point of v) {
xCounts[point[0]] = (xCounts[point[0]] || 0) + 1;
yCounts[point[1]] = (yCounts[point[1]] || 0) + 1;
}
class Node{
constructor(val, priority){
this.val = val // 노드 값
this.priority = priority // 우선순위
}
}
class PriorityQueue{
constructor(){
this.values = []; // 우선순위 큐
}
enqueue(val, priority){
let newNode = new Node(val, priority);
this.values.push(newNode); // 삽입
this.bubbleUp(); // 우선순위에 따른 재조정
}
dequeue(){
let min = this.values[0] // 가장 앞에 있는 원소
let end = this.values.pop();
if(this.values.length > 0){
this.values[0] = end; // pop 후 제일 앞에 있던 원소
this.bubbleDown(); // 재조정
}
return min;
}
bubbleUp(){
let idx = this.values.length - 1;
const element = this.values[idx]; // 마지막 원소
while(idx > 0){
let parentIdx = Math.floor((idx - 1) / 2) // 부모노드
let parent = this.values[parentIdx];
if(element.priority >= parent.priority) break; // 최소힙이니 부모가 자기보다 값이 작으면 조건 만족
this.values[parentIdx] = element; // 부모, 자식 교환
this.values[idx] = parent;
idx = parentIdx;
}
}
bubbleDown(){
let idx = 0;
const length = this.values.length;
const element = this.values[0];
while(true){
let leftChildIdx = 2 * idx + 1; //0 Idx 기반, 1 더해주기
let rightChildIdx = 2 * idx + 2;
let leftChild, rightChild;
let swap = null;
if(leftChildIdx < length){
leftChild = this.values[leftChildIdx];
if(leftChild.priority < element.priority){
// 왼쪽 자식의 우선순위가 더 작으면 현재 요소보다 앞으로 와야함.
// 교체 대상으로 지정
swap = leftChildIdx;
}
}
if(rightChildIdx < length){
rightChild = this.values[rightChildIdx];
if ((swap === null && rightChild.priority < element.priority) ||(swap !== null && rightChild.priority < leftChild.priority)){
//1. 오른쪽 자식의 우선순위가 더 낮은 경우
//2. 오른쪽 자식의 우선순위가 왼쪽 자식보다 더 낮은 경우
swap = rightChildIdx;
}
}
if(swap == null) break;
this.values[idx] = this.values[swap];
this.values[swap] = element;
idx = swap;
}
}
}