計算機科学のブログ

複雑なデータの扱いを学ぶ バイナリデータ、Unicode文字列、UTF-16、ArrayBuffer、Uint16Array、JSON(JavaScript Object Notation)、ディープコピー、メソッド(stringfy、parse)

ハンズオンJavaScript (あんどうやすし(著)、オライリー・ジャパン)の8章(複雑なデータの扱いを学ぶ)、8.4(練習問題)の8-1、8-2の解答を求めてみる。

コード

console.log('8-1')

let binary = new Int32Array([-570238871, -1738642577]).buffer,
    i16 = new Uint16Array(binary),
    s = String.fromCharCode(...i16);

console.log(binary);
console.log(i16);
console.log(...i16);
console.log(s);

console.log('8-2');
let deepCopy = (obj) => JSON.parse(JSON.stringify(obj)),
    ko1 = {
        id: 1,
        name: 'Echoes',
        parameters: [
            {
                power: 'E',
                speed: 'E',
                range: 'B',
            },
            {
                power: 'C',
                speed: 'D',
                range: 'B',
            },
            {
                power: 'B',
                speed: 'B',
                range: 'C',
            },
        ],
    },
    ko2 = deepCopy(ko1);
console.log(ko1);
console.log(deepCopy(ko2));

console.log('変更後');
ko1.id = '';
console.log(ko1);
console.log(ko2);
ko1.parameters[0].power = 'Z';
console.log(ko1);
console.log(ko2);

入出力結果(Terminal, Zsh)

% node main.js
8-1
ArrayBuffer {
  [Uint8Contents]: <69 d8 02 de 6f 6b 5e 98>,
  byteLength: 8
}
Uint16Array(4) [ 55401, 56834, 27503, 39006 ]
55401 56834 27503 39006
𪘂歯類
8-2
{
  id: 1,
  name: 'Echoes',
  parameters: [
    { power: 'E', speed: 'E', range: 'B' },
    { power: 'C', speed: 'D', range: 'B' },
    { power: 'B', speed: 'B', range: 'C' }
  ]
}
{
  id: 1,
  name: 'Echoes',
  parameters: [
    { power: 'E', speed: 'E', range: 'B' },
    { power: 'C', speed: 'D', range: 'B' },
    { power: 'B', speed: 'B', range: 'C' }
  ]
}
変更後
{
  id: '',
  name: 'Echoes',
  parameters: [
    { power: 'E', speed: 'E', range: 'B' },
    { power: 'C', speed: 'D', range: 'B' },
    { power: 'B', speed: 'B', range: 'C' }
  ]
}
{
  id: 1,
  name: 'Echoes',
  parameters: [
    { power: 'E', speed: 'E', range: 'B' },
    { power: 'C', speed: 'D', range: 'B' },
    { power: 'B', speed: 'B', range: 'C' }
  ]
}
{
  id: '',
  name: 'Echoes',
  parameters: [
    { power: 'Z', speed: 'E', range: 'B' },
    { power: 'C', speed: 'D', range: 'B' },
    { power: 'B', speed: 'B', range: 'C' }
  ]
}
{
  id: 1,
  name: 'Echoes',
  parameters: [
    { power: 'E', speed: 'E', range: 'B' },
    { power: 'C', speed: 'D', range: 'B' },
    { power: 'B', speed: 'B', range: 'C' }
  ]
}
%