Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created July 24, 2018 12:56
Show Gist options
  • Save prof3ssorSt3v3/3d99c75b12b0b5df9549d83f11a7f228 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/3d99c75b12b0b5df9549d83f11a7f228 to your computer and use it in GitHub Desktop.

Revisions

  1. prof3ssorSt3v3 created this gist Jul 24, 2018.
    82 changes: 82 additions & 0 deletions deep-shallow.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,82 @@
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Shallow vs Deep Copy</title>
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="../video-pages/main.css">
    </head>
    <body>
    <header>
    <h1>Shallow vs Deep Copy</h1>
    </header>
    <main>
    <div id="output"></div>
    </main>
    <script>
    /***********************
    In NodeJS we only have the JSON methods.
    Beyond that you will have to bring in
    an NPM module or write your own
    custom method.
    ***********************/
    /***********************
    Deep Copy methods
    1. JSON.parse(JSON.stringify())
    2. Service Workers postMessage() onmessage
    3. History API history.pushState(obj, title) history.state
    4. Notification API new Notification("title", {data: obj} ).data
    5. Build a custom recursive function
    ***********************/

    let shallowArr = [123,
    'bob',
    true,
    null,
    undefined];

    let deepArr = [123,
    'bob',
    true,
    ['Hank', 'Brent', 'Lacy'],
    {'Rouleau':'Dog River',
    'Wilcox': 'Woolerton'}
    ];

    let deepObj = {
    'characters': ['Wanda','Davis','Emma','Karen'],
    'places': ['Corner Gas','Ruby','Foo Mart'],
    'grad68': false,
    'seasons': 5
    }

    let newObj = {...deepObj};
    //newObj.places[0] = 'Ottawa'; //changed inside ref.
    //newObj.places = ['Ottawa', 'Calcutta']; //new ref
    console.log(newObj, deepObj);
    let otherObj = JSON.parse(JSON.stringify(deepObj));
    otherObj.places[0] = 'Ottawa';
    console.log(otherObj, deepObj);

    /*********************
    Shallow Copy Method examples
    1. arr1.slice(0)
    2. [].concat(arr1)
    3. Spread Operator
    4. Object.create({}, obj)
    5. Object.assign({}, obj)
    6. Array.from(arr1)
    *********************/
    let s = 'steve';
    let g = s;
    s = 'new value';
    //console.log(s, g);

    let arr = Array.from(shallowArr);
    //let arr1 = [...shallowArr];
    shallowArr[0] = 456;
    //console.log(arr, shallowArr);

    </script>
    </body>
    </html>