The best kittens, technology, and video games blog in the world.

Saturday, March 30, 2019

stringify-any

a185975 jewel-2 by The.Rohit from flickr (CC-NC)

So here's my second interesting Javascript npm package - stringify-any.

Javascript is a basically very low quality language where everything only kinda sorta mostly works. In this case I ran into problems of inspecting objects.

Problem this package is targeting

If you want to inspect obj in a browser, you'd usually just do:

console.log(obj)

And the browser will generate appropriate interactive widget you can click around to look around.

That's of course not possible outside the browser. So what if you want to print the object?

console.log(`${obj}`)

The most obvious way will fail with [object Object].

JSON sort of helps, and we can do this:

console.log(JSON.stringify(obj))

It's hard to read due to bad indentation, but copy and pasting JSON into pretty printer is a basic web development skill, so it's kinda tolerable.

And then you try some modern Javascript, and somewhere in that obj there's a nested new Set([1, 2, 3]), which quietly turns into {}, making you want to drop Javascript and just code Ruby in browser or Clojurescript or something.

What you can do now

Just get the package, import stringify function, and call it:

import "stringify-any" as stringify
console.log(stringify(obj))

It will do the right thing.

It handles all cases I could think of, like undefined, -0, infinities, NaN, DateMapSet.

It also sort of handles WeakMapWeakSetFunction - we can't show what's inside, but we can at least show the type.

Because Javascript is Javascript I'm sure I missed something. Please report, github issues are the best place.

I couldn't find any other package that does this correctly (found a lot which tried but failed), but then it's totally possible something like this already exists.

No comments: