MISC MISC

Sang Young Ha·2022년 11월 25일
post-thumbnail

흥미(?)로울만한 것들

Javascript Language

proxies

  • Proxy 객체는 다른 객체를 위한 proxy 를 생성하게 해준다. 이 proxy 는 해당 객체의 주요 operation 을 intercept 및 redefine 을 할 수 있다.
  • Proxy 객체는 주로 property access, validate, fomat 을 log 하기 위해, 또는 input 을 sanitize 하기 위해 주로 쓰인다.
  • Proxy 는 두개의 파라미터로 만들 수 있다.
  1. target: the original object which you want to proxy
  2. handler: an object that defines which operations will be intercepted and how to redefine intercepted operations.
  • 아래의 코드는 target 객체를 위한 proxy 를 생성하는 코드이다.
const target = {
  message1: "hello",
  message2: "everyone",
};

const handler1 = {};

const proxy1 = new Proxy(target, handler1);
//hander1 이 비었기 때문에 original target 와 같이 작동한다.
console.log(proxy1.message1); // hello
console.log(proxy1.message2); // everyone
  • proxy 를 customize 하기 위해선 다음과 같이 handler object 에 function 을 정의 해준다.
const handler2 = {
  get(target, prop, receiver) {
    return "world";
  },
};
const proxy2 = new Proxy(target, handler2);
console.log(proxy2.message1); // world
console.log(proxy2.message2); // world

Promise.allSettled()

  • Promise.any() 와 비슷하게 iterable 한 promise 들을 인풋으로 받은 후, 하나의 Promise 를 리턴한다. 모든 promise 들이 settle 되면 fulfil 된다. fulfil 시에 각 promise 의 결과를 담은 어레이를 보여준다.
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result.status)));

// expected output:
// "fulfilled"
// "rejected"

Nullish Coalescing

const foo = null ?? "default string";
console.log(foo);
// expected output: "default string"

const fooTwo = 0 ?? 47;
console.log(fooTwo);
// expected output : 0

Numeric Separators (코드 가독성을 위한)

let budget = 1_000_000_000;
// same as writing 
let budget = 1000000000;

//다음과 같이도 사용 가능
let budget = 120_201_123.05; // 120201123.05
let budget = 123_450; // 123450
let budget = 12345_00; // 1234500

String.prototype.replaceAll()

  • syntax : replaceAll(pattern, replacement)
  • example:
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"


// global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

String.prototype.matchAll()

  • syntax: matchAll(regexp)
  • example:
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]

Logical Assignment

const a = { duration: 50, title: "" };
a.duration ||= 10;
console.log(a.duration);
// expected output: 50

a.title ||= "타이틀이 비었소.";
console.log(a.title);
// expected output: "타이틀이 비었소."

Promise.any()

  • iterable 한 promise 들을 입력받아 하나의 Promise 를 리턴한다. 이 리턴된 promise 는 여러개의 input promise 들 중 하나만 fulfil 이 되면 fulfil 된다. 입력된 모든 promise 들이 reject 될 시 reject 한다.
  • syntax: Promise.any(iterable)
  • example:
const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));

const promises = [promise1, promise2, promise3];

Promise.any(promises).then((value) => console.log(value));

// expected output: "quick"

Array.prototype.at()

  • integer 를 index 로 입력받아 해당 index 의 아이템을 리턴한다. 음수 integer 값은 어레이의 마지막 아이템으로부터 거꾸로 카운트 한다.
const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// expected output: "Using an index of -2 item returned is 130"

Temporal

  • Javascript 의 불편한 Date object 가 개선된 객체! Date 보다 훨씬 편하다.

Array.findLast()

const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found); 
// expected output: 130

Error.prototype.cause

try {
  connectToDatabase();
} catch (err) {
  throw new Error('Connecting to database failed.', { cause: err });
}

Object.hasOwn()

const object1 = {
  prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true

Regexp Match Indices

const str1 = "foo bar foo";
const regex1 = /foo/dg;
console.log(regex1.exec(str1).indices[0]);
// expected output: Array [0, 3]

Browser APIs

  • Service Workers
  • Intl
  • WebGL
  • Web Animations
  • WebRTC
  • Web Speech API
  • WebSocket
  • Custom Elements
  • Shadow DOM
  • Page Visibility API
  • Broadcast Channel API
  • Geolocation API
  • File System Access API
  • Web Share API
  • WebXR Device API

0개의 댓글