Been doing research on this but I'd be interested in hearing more here. I saw in a Leetcode problem with Python that objects functioned more like a JavaScript Map, new Map() and all.
That proved instrumental to solving the problem which required inserting objects as keys within another object that you can't do without Maps in JS.
What I want to know is why does JavaScript have its original object {}, the way it is and if its a better practice now to use Maps instead?
This is the code for reference.
Python code
class Solution:
def copyRandomList(self, head: "Node") -> "Node":
oldToCopy = {None: None}
cur = head
while cur:
copy = Node(cur.val)
oldToCopy[cur] = copy
cur = cur.next
cur = head
while cur:
copy = oldToCopy[cur]
copy.next = oldToCopy[cur.next]
copy.random = oldToCopy[cur.random]
cur = cur.next
return oldToCopy[head]
JS version
var copyRandomList = function(head, map = new Map()) {
if(!head)return null;
if(map.has(head)) return map.get(head)
const node= new Node(head.val);
map.set(head, node)
console.log(map);
node.next=copyRandomList(head.next, map);
node.random=copyRandomList(head.random, map);
return map.get(head);
}