tc39 stage4 proposal 중 배열에 관련된 것들을 뽑아 정리했습니다.
Array.prototype와 TypedArray.prototype에 값에 의한 복사를 지원하는 새 메서드를 제공합니다.
또한 Tuple.prototype(stage 2)은 불변성을 보장하지만 array.prototype의 메서드들은 선척전으로 그렇지 못합니다. 이 메서드들을 통해 두 자료구조의 연계성이 강화될 것입니다.
Array.prototype.toReversed() -> Array
Array.prototype.toSorted(compareFn) -> Array
Array.prototype.toSpliced(start, deleteCount, ...items) -> Array
Array.prototype.with(index, value) -> Array
/* 출처: https://github.com/tc39/proposal-change-array-by-copy */
const sequence = [1, 2, 3];
sequence.toReversed(); // => [3, 2, 1]
sequence; // => [1, 2, 3]
const outOfOrder = new Uint8Array([3, 1, 2]);
outOfOrder.toSorted(); // => Uint8Array [1, 2, 3]
outOfOrder; // => Uint8Array [3, 1, 2]
const correctionNeeded = [1, 1, 3];
correctionNeeded.with(1, 2); // => [1, 2, 3]
correctionNeeded; // => [1, 1, 3]
또한 react의 배열을 다룰 때 spread syntax를 사용하지 않고 편하게 update를 수행 할 수 있습니다.
/* https://youtube.com/shorts/7xHtGNVQktI?feature=share */
// before
const onChange = (id, text) => {
const newTodos = [...todos];
newTodos[
newTodos.findIndex(t => t.id === id);
].text = text;
setTodos(newTodos);
}
// after
const onChange = (id, text) => {
setTodos(
todos.with(
todos.findIndex(t => t.id === id),
{ id, text }
)
)
};
// onDelete의 경우
const onDelete = (id) => {
setTodos(
todos.toSpliced(
todos.findIndex(t => t.id === id),
1
)
)
};
Array.prototype.findLast()
Array.prototype.findLastIndex()
자바스크립트에는 제공된 조건에 따라 배열의 값을 반환하는 indexOf(), lastIndexOf(), find(), findIndex() 등의 메서드가 있지만 뒤에서부터 역순으로(from last to first) 요소를 제공하는 메서드가 없습니다.
[...array].reverse().find()
위와 같은식으로 코드를 사용할 수는 있지만
findLast(), findLastIndex()는 find(), findIndex()와 같지만 배열의 마지막 요소에서부터 역순으로 계산합니다.