Re:Copying objects in JavaScript
by simlevesque on Tuesday November 13, 2018 @01:00PM
(#18443110)
That article is wrong. A date can definitely be serialized in JS. It is in fact converted to a ISO string when it is transformed into JSON, but the article says it does not. The author needs to learn about JSON.stringify and the toJSON method of built-ins.
[ Parent
| on HN ]
Re:Copying objects in JavaScript
by wheresvic1 on Tuesday November 13, 2018 @01:12PM
(#18443213)
Aha yes you are correct - it outputs an ISO string at the very least but does not parse it back to a date. I will update the article to reflect this!
Re:Copying objects in JavaScript
by simlevesque on Tuesday November 13, 2018 @01:15PM
(#18443251)
Ok but please read carefuly because JSON.parse can in fact recover dates. The JSON.parse function accepts a 'reviver' function as an argument to do just that. 99% of the time it's not useful so there is no reason for JSON.parse to do it by default but JSON.parse definitely can parse dates back if you use all it's features.
I like that it does not do it by default but I can make it parse the dates if I want.
Saying that JSON.parse can do something when it's really just you implementing the transformation from string to date object is a little misleading.
You can make JSON parse arbitrary sublanguages if you're willing to put in the work.
And what do you pass as the reviver argument? Your own function to check a string to see if it's valid IS8601 and parse it? That's just using parse()'s recursive walking of the object: it does no date reviving itself, right?
That way you can get different result, as you could actually have date object and date as string stored somewhere. You will need custom strigify callback to differentiate which should be converted back to date on parse and which should be a string.
Still, this is not pure json this way, it's your own transformations
Indeed it can, but I believe the point is that it's not round-tripable, meaning you can't parse the resulting serialized JSON back into its original form, the one that contained the Date objects.
If you could do so, JSON.stringify/parse would be a convenient way to do a deep clone.
Re:Copying objects in JavaScript
by simlevesque on Tuesday November 13, 2018 @01:12PM
(#18443210)
Yeah that's right. All I'm saying is that no matter what, the following sentence is false:
> An example of a non-serializable value type is the Date object - it is printed in a non ISO-standard format and cannot be parsed back to its original value :(.
It would be cool if there was a webpage for “Is your function ______?” with a list of things that functions can be:
- Roundtrip-able (reversible?)
- Pure
- Effectful
- Mutation-doing
- Idempotent/Nullipotent
- Algebraically closed over the set of its inputs
- Et c.
Every time I hear about a new one I wish I had such a list
> - Roundtrip-able (reversible?)
You mean injective