Good afternoon! Here's our prompt for today.
In Javascript there is a method called JSON.stringify()
that can convert an object or a variable into a JSON string. The method handles different data types differently, ending up with its correct JSON "translation". Some examples of how this method handles different types include:
Boolean
,Number
, andString
objects are converted to the corresponding primitive valuesundefined
,Function
, andSymbol
are not valid JSON values and are changed tonull
- The instances of
Date
are returned asdate.toISOString()
and are treated as strings Infinity
as well as the valuenull
are considered asnull
Can you implement a simplified version of this JSON stringifier, covering the most important constraints when it comes to the data type and value handling?
Here is an example of how your solution should work:
JAVASCRIPT
1stringify({}); // '{}'
2stringify(true); // 'true'
3stringify('foo'); // '"foo"'
4stringify([1, 'false', false]); // '[1,"false",false]'
5stringify([null, Infinity]); // '[null,null]'
6stringify({ x: 5 }); // '{"x":5}'

Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
34
function stringify(data) {
if (typeof data === "string") {
return `"${data}"`;
}
if (typeof data === "function") {
return undefined;
}
if (data === Infinity || data === -Infinity || data === null
|| data === undefined || typeof data === "symbol") {
return "null";
}
if (typeof data === "number" || typeof data === "boolean") {
return `${data}`;
}
if (data instanceof Date) {
return `"${data.toISOString()}"`;
}
if (Array.isArray(data)) {
const arr = data.map((el) => stringify(el));
return `[${arr.join(",")}]`;
}
if (typeof data === "object") {
const arr = Object.entries(data).reduce((acc, [key, value]) => {
if (value === undefined) {
return acc;
}
acc.push(`"${key}":${stringify(value)}`);
return acc;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?