작년에 JS 세계엔 무슨 일이 있었을까

dante Yoon·2024년 2월 17일
6

js/ts

목록 보기
14/14
post-thumbnail

유튜브로 보기 https://www.youtube.com/watch?v=RFjaDcVb9a8

안녕하세요, 단테입니다.
ECMAScript 버전 출시는 많은 자바스크립트 개발자들의 관심을 받는 주제죠, 구글에 검색했을 때 나오는 수많은 자료들이 JS에 대한 인기와 관심을 증명합니다. 그러나 깃허브공식 문서에 나와있는 내용과 다르게 2024의 피쳐의 내용들이 ECMAScript 2023로 소개되는등 버전이 잘못 명시되어 소개되는 콘텐츠들도 많은 것 같습니다.

이제 곧 여러 플랫폼에서 ECMAScript 2024에 대한 소식들을 받아보실텐데요, 그전에 작년의 주요한 기능들을 먼저 알아보겠습니다.

Array find from last

{Array, TypedArray}.prototype.findLast

Array는 알겠는데 TypedArray가 뭐야?

TypedArray는 배열과 비슷한 바이너리 데이터를 저장하는 자료구조를 이야기합니다. 아래와 같은 TypedArray들이 있습니다.

출처: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects

중요한 건 새로 추가된 findLast 메소드인데요, 배열 안에 있는 단어 중 'A'로 시작하는 마지막 단어를 선택하고 싶으면 다음과 같이 코드를 작성할 수 있습니다. 배열을 순회하는 코드를 작성해야 하는데 findLast메소드를 사용하면 보다 간단히 작성할 수 있습니다.

before

const strings = ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry'];

let lastStringStartingWithA;
for (let i = strings.length - 1; i >= 0; i--) {
    if (strings[i][0] === 'A') {
        lastStringStartingWithA = strings[i];
        break;
    }
}
console.log(lastStringStartingWithA); // => 'Apricot' // 살구

after

strings.findLast(s => s.startsWith('A'))

{Array, %TypedArray%}.prototype.findLastIndex

값이 아닌 인덱스를 찾을 때 사용할 수 있습니다.

strings.findLastIndex(s => s.startsWith('A')) // 3

ramda, lodash

기존에 이렇게 편하게 작업하기 위해서는 라이브러리를 사용해야 했습니다.

Hashbang Grammar

쉘 스크립트를 리눅스에서 실행시키기 위해 다음처럼 코드를 작성합니다.

sh

#! /bin/bash

echo "Shell Script"

첫줄에 작성한 #!을 hashbang이라고 합니다.

nodejs로 작성한 스크립트를 CLI로 실행시키기 위해서 hashbang을 사용할 수 있습니다.

node.sh

#!/usr/bin/env node

console.log("Shebang Supported in Javascript");

shebang은 다음의 포맷팅을 가집니다.
#! interpreter [optional-arg]

따라서 nodejs를 사용하여 쉘 스크립트를 실행시키라는 의미이며 이렇게 작성된 스크립트는 node 명령어를 사용해서도 실행시킬 수 있습니다.

$ node node.sh
> Shebang Supported in Javascript

Symbols as WeakMap keys

WeakMap은 자바스크립트 자료구조중 원시타입이 아닌 객첵를 키로 가질 수 있는 맵 구조입니다.
Symbol 타입을 이제 키로 사용할 수 있게 되었습니다.

node.js 20버전을 설치해야 하며 예제코드를 작성하면 다음과 같이 심볼 타입을 키로 가질 수 있는 WeakMap을 사용할 수 있습니다 .

프로그램 전체에서 특정 객체의 레퍼런스를 가르키는 unique id를 만들 수 있습니다.

const weak = new WeakMap();

const secretKey = Symbol('secret');
const user = {
  id: 1,
  name: 'Dante'
};


weak.set(secretKey, { password: 'secretpassword1234' });

const secret = weak.get(secretKey);
console.log(secret); 
// { password: 'secretpassword1234' }
const weak = new WeakMap();

function generateUUID(obj) {
  const idKey = Symbol('uuid');
  weak.set(idKey, obj);
  return idKey;
}

const userObject = {};
const uuid1 = generateUUID(userObject);
const uuid2 = generateUUID(userObject);
console.log(uuid1) // Symbol(uuid)
console.log(uuid2) // Symbol(uuid)
console.log(uuid1 === uuid2) // false

Change Array by Copy

문제점

Array.prototype에 이미 존재하던 reverse, sorted, splice 메소드는 원본배열을 변경하는 문제점이 있었습니다.

const strings = ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry'];

/**
strings.splice(1,3)
(3) ['Apple', 'Avocado', 'Apricot']
strings
(2) ['Banana', 'Blueberry']
*/

Array.prototype.toReversed() -> Array

원본배열은 그대로 유지하고 새로운 배열을 반환합니다.

const strings = ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry'];

const reversedStrings = strings.toReversed();
console.log(reversedStrings); // ['Blueberry', 'Apricot', 'Avocado', 'Apple', 'Banana']

Array.prototype.toSorted(compareFn) -> Array

const strings = ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry'];

const sortedStrings = strings.toSorted();
console.log(sortedStrings); // ['Apple', 'Apricot', 'Avocado', 'Banana', 'Blueberry']

Array.prototype.toSpliced(start, deleteCount, ...items) -> Array

const strings = ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry'];

const splicedStrings = strings.toSpliced(2, 1, 'Blackberry');
console.log(splicedStrings); // ['Banana', 'Apple', 'Blackberry', 'Apricot', 'Blueberry']

/**
strings ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry']
*/

Array.prototype.with(index, value) -> Array

with이 좀 생소하실 것 같은데 index에 있는 단일 엘리먼트를 변경한 새로운 배열을 반환합니다.

예를 들어

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]

3을 6으로 변경하고 제곱을 했기에 arr[2]는 36이 되었습니다.

const strings = ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry'];

// Hypothetical usage of Array.prototype.with
const newStrings = strings.with(1, 'Blackberry');
console.log(newStrings); // ['Banana', 'Blackberry', 'Avocado', 'Apricot', 'Blueberry']
console.log(strings); // ['Banana', 'Apple', 'Avocado', 'Apricot', 'Blueberry'], remains unchanged
profile
성장을 향한 작은 몸부림의 흔적들

1개의 댓글

comment-user-thumbnail
2024년 2월 25일

findlastindex 잘 읽었습니다 감사합니다!

답글 달기