[Daily Coding 9]Optional Chaining(?.)/!!/정규표현식/every/some/Map

hameee·2023년 1월 25일
1

Daily Coding

목록 보기
9/10

1.Optional Chaining(?.)

. 체이닝 연산자와 유사하게 작동하지만, 만약 참조가 nullish(null/undefined)이라면, 에러가 발생하는 것 대신에 undefined 리턴

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

console.log(adventurer.dog.name); // Error
console.log(adventurer.dog?.name); // undefined

2.!! 활용

활용1. 매트릭스의 값 유무를 확인하고 싶은 경우

값이 없으면(0이면) false, 있으면 true 반환

활용2. 매트릭스의 가장자리 부분도 값이 없는 것으로 취급하고 싶은 경우

undefined 또는 0이면 false, 아니면 true 반환

// 프로그래머스 안전지대 문제
// 1(폭탄) -> false
// 폭탄 주변 -> false
// 안전지대 -> safezone++

function solution(board) {
  let outside = [[-1,0], [-1,-1], [-1,1], [0,-1],[0,1],[1,0], [1,-1], [1,1]];
  let safezone = 0;

  board.forEach((row, y, self) => row.forEach((it, x) => {
    // 폭탄이면 -> false
    if (it === 1) return false;
    // 폭탄 아니면 -> 주변에 하나라도 폭탄(1)이 있으면 false, 아니면 safezone++
    return outside.some(([oy, ox]) => !!self[oy + y]?.[ox + x])
           ? false : safezone++;
  }));

  return safezone;
}

3.정규표현식

1) 형식

/정규표현식/flag

2) flag

i : 대·소문자 구분 없이 검색
g : 패턴과 일치하는 모든 것 검색. g 플래그가 없으면 패턴과 일치하는 첫 번째 결과만 반환.
m : 다중 행 모드(multiline mode)를 활성화. ^$ 사용 시 여러 줄에 걸쳐 검사. m 플래그가 없으면 ^$ 사용 시 전체의 처음과 마지막만 검사.

3) 정규표현식

정리 깃허브: https://github.com/dream-ellie/regex
참고 영상: https://youtu.be/t3M6toIflyQ
연습 사이트: https://regexr.com/5ml92

4) RegExp.prototype.test()

주어진 문자열이 정규 표현식을 만족하는지 판별

const regex = new RegExp('foo*'); // new RegExp의 두번째 인자로 flag를 넣을 수 있음(문자열)
console.log(regex.test('table football')); // true

4.every, some

1) Array.prototype.every()

배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트
모든 요소가 통과해야 true 반환

const array = [1, 30, 39, 29, 10, 13];
const isBelowThreshold = (value) => value < 40;

console.log(array.every(isBelowThreshold));// true

2) Array.prototype.some()

배열 안에 주어진 판별 함수를 통과하는 요소가 있는지 테스트
하나의 요소만 통화해도 true 반환

const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0;

console.log(array.some(even));// true

5.Map

키-값 쌍을 저장, 키의 삽입 순서 기억

1) Method

new Map() Creates a new Map object
set() Sets the value for a key in a Map
get() Gets the value for a key in a Map
clear() Removes all the elements from a Map
delete() Removes a Map element specified by a key
has() Returns true if a key exists in a Map
forEach() Invokes a callback for each key/value pair in a Map
entries() Returns an iterator object with the [key, value] pairs in a Map
keys() Returns an iterator object with the keys in a Map
values() Returns an iterator object of the values in a Map

2) Property

size Returns the number of Map elements

3) Example

const map1 = new Map();

// map1에 key-value 추가
map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);

console.log(map1) // Map {'a' => 1, 'b' => 2, 'c' => 3}

// <How to use>
// 1.Use the first value as a key
console.log(map1.get('a')) // 1 (key로 value를 불러오기 위해 get 메서드 사용해야 함)
console.log(map1['a']) // undefined

// 2.Use the first value as a value
// 1)
for(let el of map1) {
  console.log(el) 
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
// 주의: for...in이랑은 못 씀

// 2) 
let arr = [...map1]
console.log(arr) // [['a', 1], ['b', 2], ['c', 3]]

// 3.2D Array -> Map object
const array = [['key1', 'value1'], ['key2', 'value2']];
const myMap = new Map(array);

console.log(myMap) // Map {'key1' => 'value1', 'key2' => 'value2'}

0개의 댓글