Skip to content

structuredClone.js

https://developer.mozilla.org/ko/docs/Web/API/structuredClone

js
// 객체 복제
const obj = {
  arr: [0, 1],
};

const clonedObj = structuredClone(obj);

clonedObj.arr.push(2);

console.log(obj.arr); // [0, 1]
console.log(clonedObj.arr); // [0, 1, 2]

// 순환 참조 지원
const original = { name: "MDN" };
original.itSelf = original;

const cloned = structuredClone(original);

console.assert(cloned !== original);
console.assert(cloned.name === original.name);
console.assert(cloned.itSelf === cloned);

// 전송가능한 객체(Transferable objects): 전송 후 기존 데이터 사용 불가
const uInt8Arr = Uint8Array.from({ length: 1024 }, (_, i) => i);
console.log(uInt8Arr.byteLength); // 1024

const transferred = structuredClone(uInt8Arr, {
  transfer: [uInt8Arr.buffer],
});
console.log(uInt8Arr.byteLength); // 0

collection.js

js
const clone = value => {
  switch (true) {
    case isPrimitive(value):
      return value
    case isArray(value):
      return value.map(clone)
    case isMap(value):
      return new Map(value)
    case isSet(value):
      return new Set(value)
    default:
      return cloneObject(value)
  }
}

const isPrimitive = value => {
  switch (true) {
    case value === undefined:
    case value === null:
      return true
    case typeof value === 'object':
    case typeof value === 'function':
    case Number.isNaN(value):
      return false
    default:
      return true
  }
}
const isArray = target => Array.isArray(target)
const isMap = target => target instanceof Map
const isSet = target => target instanceof Set

const cloneObject = obj => {
  const cloned = Object.create(Object.getPrototypeOf(obj))
  for (const key in obj) {
    cloned[key] = clone(obj[key])
  }
  return cloned
}

module.exports = {clone}

json.js

js
const clone = json => JSON.parse(JSON.stringify(json))

module.exports = {clone}

object-array.js

js
const clone = objOrArr => {
  switch (true) {
    case isPrimitive(objOrArr):
      return objOrArr
    case Array.isArray(objOrArr):
      return objOrArr.map(clone)
    default:
      return cloneObject(objOrArr)
  }
}

const isPrimitive = value => {
  switch (true) {
    case value === undefined:
    case value === null:
      return true
    case typeof value === 'object':
    case typeof value === 'function':
    case Number.isNaN(value):
      return false
    default:
      return true
  }
}

const cloneObject = obj => {
  const cloned = Object.create(Object.getPrototypeOf(obj))
  for (const key in obj) {
    cloned[key] = clone(obj[key])
  }
  return cloned
}

module.exports = {clone}