Solution
Our solution would be the method stringify
, that will simply handle the cases we mentioned above, with many different if
conditions. For example, we return undefined
if the type of the data is a function, or we return null
if it is a synbol, undefined, infinity, or null.
1if (typeof data === "function") {
2 return undefined;
3}
4if (data === Infinity || data === -Infinity || data === null
5 || data === undefined || typeof data === "symbol") {
6 return "null";
7}
If the data is a string, number or a boolean, we return the data itself, bearing in mind the quotes needed for a string value.
1if (typeof data === "string") {
2 return `"${data}"`;
3}
4if (typeof data === "number" || typeof data === "boolean") {
5 return `${data}`;
6}
If our data type is a date, as stated above, we return it as a string, by using data.toISOString()
.
In case we are dealing with an array, or an object, then we need a bit more logic to parse our data. So, for an array, we will first map and stringify our data to make sure the elements are all in a string format, and then we are going to parse it in the needed JSON array format, using braces, and separate the data with commas:
1if (Array.isArray(data)) {
2 const arr = data.map((el) => stringify(el));
3 return `[${arr.join(",")}]`;
4}
For objects, we will handle them by looping the object properties one by one, and then using the reduce
method we will divide them into key-value pairs - key being the property name, and the value being its value. We will perserve the JSON objects notation, wrapping the object properties into brackets, and in the format "key": "value"
.
1if (typeof data === "object") {
2 const arr = Object.entries(data).reduce((acc, [key, value]) => {
3 if (value === undefined) {
4 return acc;
5 }
6 acc.push(`"${key}":${stringify(value)}`);
7 return acc;
8 }, []);
9 return `{${arr.join(",")}}`;
10}
Our final solution with all these conditions handled would look like this:
1function stringify(data) {
2 if (typeof data === "string") {
3 return `"${data}"`;
4 }
5 if (typeof data === "function") {
6 return undefined;
7 }
8 if (data === Infinity || data === -Infinity || data === null
9 || data === undefined || typeof data === "symbol") {
10 return "null";
11 }
12 if (typeof data === "number" || typeof data === "boolean") {
13 return `${data}`;
14 }
15
16 if (data instanceof Date) {
17 return `"${data.toISOString()}"`;
18 }
19 if (Array.isArray(data)) {
20 const arr = data.map((el) => stringify(el));
21 return `[${arr.join(",")}]`;
22 }
23 if (typeof data === "object") {
24 const arr = Object.entries(data).reduce((acc, [key, value]) => {
25 if (value === undefined) {
26 return acc;
27 }
28 acc.push(`"${key}":${stringify(value)}`);
29 return acc;
30 }, []);
31 return `{${arr.join(",")}}`;
32 }
33}