Skip to content

Instantly share code, notes, and snippets.

@artalar
Created June 15, 2018 06:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artalar/6d42cae96ce08f6da772af3e087e0a29 to your computer and use it in GitHub Desktop.
Save artalar/6d42cae96ce08f6da772af3e087e0a29 to your computer and use it in GitHub Desktop.

Реализуйте ф-ю shallowCopy, которая будет осуществлять [не глубокое] копирование объекта сохраняя его hidden class \ structure \ shape.

Если последние определения вам не ясны, вот статья для введения https://medium.com/@bmeurer/surprising-polymorphism-in-react-applications-63015b50abc

Или видео https://youtu.be/5nmpokoRaZI

// shallowCopyWithSaveMap.js
const a = {x:1, y:2, z:3};

const b = shallowCopyWithSaveMap(a);

console.log("a and b is different objects:", a !== b);

console.log("a and b have same map:", %HaveSameMap(a, b));
# shell
node --allow-natives-syntax ./shallowCopyWithSaveMap.js
> a and b is differend objects: true
> a and b have same map: true

Ответ в комментарии

@artalar
Copy link
Author

artalar commented Jun 15, 2018

Answer

``` function shallowCopyWithSaveMap(obj) { const keys = Object.keys(obj); const code = 'new Object({' + keys.join(': undefined,') + ': undefined})'; const newObject = eval(code); for (let i = 0; i < keys.length; i++) { const key = keys[i]; newObject[key] = obj[key]; } return newObject; } ``` tests awful https://jsperf.com/object-creating-eval-vs-enumeration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment