Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shallow-clone a Map or Set

People also ask

How will you create a shallow copy of a map?

To create a shallow copy of a Map , pass the existing Map as a parameter to the Map() constructor, e.g. const newMap = new Map(oldMap) . The Map() constructor takes an iterable, such as another Map , and adds the key-value pairs to the new Map .

What is shallow cloning?

A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.


Use the constructor to clone Maps and Sets:

var clonedMap = new Map(originalMap)

var clonedSet = new Set(originalSet)

Creating a new Set via a for loop is faster than the Set constructor. The same is true for Maps, although to a lesser degree.

const timeInLoop = (desc, loopCount, fn) => {
  const d = `${desc}: ${loopCount.toExponential()}`
  console.time(d)
  for (let i = 0; i < loopCount; i++) {
    fn()
  }
  console.timeEnd(d)
}

const set = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

const setFromForLoop = x => {
  const y = new Set()
  for (const item of x) y.add(item)
  return y
}

const map = new Map([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]])

const mapFromForLoop = x => {
  const y = new Map()
  for (const entry of x) y.set(...entry)
  return y
}

timeInLoop('new Set(set)', 1e5, () => new Set(set))

timeInLoop('setFromForLoop(set)', 1e5, () => setFromForLoop(set))

timeInLoop('new Map(map)', 1e5, () => new Map(map))

timeInLoop('mapFromForLoop(map)', 1e5, () => mapFromForLoop(map))

Shallow clone:

var clonedMap = new Map(originalMap)

var clonedSet = new Set(originalSet)

Deep clone:

var deepClonedMap = new Map(JSON.parse(JSON.stringify([...originalMap])))
var deepClonedSet = new Set(JSON.parse(JSON.stringify([...originalSet])))

let originalMap = new Map()
let data = {a:'a',b:'b'}
originalMap.set(1,data)

let shallowCloned = new Map(originalMap)
let deepCloned = new Map(JSON.parse(JSON.stringify([...originalMap])))
data.a = 'p'
console.log('originalMap:',[...originalMap])
console.log('shallowCloned:',[...shallowCloned])
console.log('deepCloned:',[...deepCloned])