Shreyansh Pandey
copy() {
return Object.assign(new Counter(), this);
}
Should be "close enough for government work" so long as ECMAScript 6 is present -- which I'd assume since we you care about legacy browsers we wouldn't be using JSON, Class, arrow functions, or Object.foreach.
The sad part being that again, the use of (the pointless) let, const alongside the foreach/arrow function dragging performance down for no good reason if you do need to brute force it.
The language of this is just ... I dunno... wrong. What you're calling a "shallow copy" isn't a copy! You do eventually get around to using the correct word, a reference as the only thing being copied internally is the pointer. There are many terms for this -- pointer, reference, alias -- but copy isn't one of them! a = b where b is an object is not a copy!
You don't have a "shallow" copy there. Nothing other than the pointer is duplicated.
A shallow copy is the term for when a element on a linked list doesn't copy the structural pointers. For example if you had:
<div id="test"> <h2>Test heading</h2> <p>A sample paragraph</p> </div>if you:
var test = document.getElementById('test'), shallow = test.cloneNode(false), deep = test.cloneNode(true);The shallow copy will have the ID of test and all other properties of the original DIV, but will not have the pointer structures of firstChild, lastChild, and so forth included so the child H2 and P aren't copied.
The deep copy does make copies of the child elements and assigns their pointer structure as appropriate.
That's the difference between shallow and deep.
You almost get there with the 'bonus' but not really; but with the inefficient callback "foreach" approach and lack of Object.assign... well...