Write safeJsonParse(text) that returns [error, value] instead of throwing.
On success, return [null, value]. On invalid JSON, return [error, undefined], where error is the SyntaxError that JSON.parse threw. If text isn't a string, return a TypeError the same way instead of parsing it.
function safeJsonParse(text) {
// your code
}
// const [error, data] = safeJsonParse('{"a":1}'); // error is null, data is {a: 1}
// safeJsonParse("{a:1}"); // [SyntaxError, undefined]
// safeJsonParse(42); // [TypeError, undefined]
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…