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 inspectobj
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]
.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, importstringify
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
It also sort of handles
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.
It handles all cases I could think of, like
undefined
, -0
, infinities, NaN
, Date
, Map
, Set
.It also sort of handles
WeakMap
, WeakSet
, Function
- 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:
Post a Comment