わたしもみている| Immutable Javascript using ES6 and beyond(Array)

前回ここのObjectまで読みました。

今回はArray
immutableなArray。
非破壊メソッドを使おう

pushの代わりに、
Spread Operator
[code language="javascript"]
let characters = ['a', 'b'];
let newCharactors = [...characters, 'c'];
console.log(newCharactors === characters)
//false
console.log(characters)
//["a", "b"]
newCharactors
//["a", "b", "c"]
[/code]

[code language="javascript"]
//要素b以外の新しい配列を返す
const whithout = characters.filter(char => char !== 'b');
whithout
//["a"]

//要素bとcを入れ替えた新しい配列を返す
const backInTime = characters.map(char => char === 'b' ? 'c' :char);
backInTime
//["a", "c"]

//大文字にした新しい配列を返す
const shoutOut = characters.map( char => char.toUpperCase())
shoutOut
//["A", "B"]

//2つの配列を足した新しい配列を返す
let characters = ['a', 'b'];
const otherCharacters = ['d','e'];
const moreCharacters = [...characters, ...otherCharacters]
moreCharacters
//["a", "b", "d", "e"]
[/code]

sort()の返り値とオリジナルの参照先は変わらない。要素順だけ入れ替える

[code language="javascript"]
const characters2 = ["b", "d", "a", "c"];
const sortedCharacters = characters2.sort()
sortedCharacters
//["a", "b", "c", "d"]
sortedCharacters === characters2
//true
[/code]

順序を入れ替えた上で新しい配列を返すにはsliceを使う
[code language="javascript"]
const sortedCharacters2 = characters2.slice().sort();
sortedCharacters2 === characters2
//false
characters2
//["a", "b", "c", "d"]
sortedCharacters2
//["a", "b", "c", "d"]
[/code]

なぜ新しいオブジェクトを生成する方がいいのか??
そんなに新しいオブジェクトを生成してメモリは大丈夫なの??

But that disadvantage is very small compared to the advantages.
欠点は利点に比べて非常に小さいです

One of the more complicated operations in Javascript is tracking if an object changed
JSでより複雑な操作の一つはオブジェクトが変更された場合の追跡です

Object.observe(object, callback) are pretty heavy
Object.observeは相当重たいです。
※記事が古いのか、Object.observeは今では廃止されています

if you keep your state immutable you can just rely on oldObject === newObject to check if state changed or not, this is way less CPU demanding.

もしオブジェクトの状態を不変に保てば古いオブジェクトか新しいオブジェクトかどうかのチェックは
oldObjet === newObject だけで可能だし、これはCPUへのダメージが少ない方法です

Second big advantage is code quality. Making sure your state is immutable forces you to think better of your application structure. It encourages programming in a more functional way, makes your code easy to follow and reduces the possibility of nasty bugs. Win, win, right?
第二の大きなアドバンテージはコードの品質です。
状態を確認することは不変オブジェクトがなせることです。
これはアプリケーションの構築への良い考えなのです
It encourages programming in a more functional way, makes your code easy to follow and reduces the possibility of nasty bugs.
より関数型なプログラミングを奨励します。バグを除き、コードを追いやすくするのです

Reference
Immutable Javascript using ES6 and beyond