Okay so I am trying to replicate JSON.stringify. Currently I am getting this error. Unfortunately this error is not very helpful because the message is cut short before it actually gets to what the problem is so I am quite stuck. Can anyone tell me what is wrong with my object code? I am currently commenting out the recusive code for nested arrays/objects as the tests for that are separate.
Here is the code (only the code relevant to arrays and objects):
if (Array.isArray(input)) {
var toJSON = '[';
var key = 0;
function toString() {
if (input.length === 0) {
return '[]';
}
if (key < input.length) {
// if (Array.isArray(input[key]) || typeof input[key] === 'object') {
// toJSON += stringifier(input[key]);
// }
if (input[key] === null || typeof input[key] === 'function' || input[key] === undefined) {
toJSON += 'null';
}
if (typeof input[key] === 'number' || typeof input[key] === 'boolean') {
toJSON += `${input[key]}`;
}
if (typeof input[key] === 'string') {
toJSON += `"${input[key]}"`;
}
key++;
if (key < input.length) {
toJSON += ',';
}
toString();
}
}
toString();
return toJSON + ']';
}
if (typeof input === 'object') {
if (Object.keys(input).length === 0) {
return '{}';
}
var toJSON = '{';
for (var key in input) {
toJSON += `"${key}":`;
// if (Array.isArray(input[key]) || typeof input[key] === 'object') {
// toJSON += stringifier(input[key]);
// }
if (input[key] === null || input[key] === undefined || typeof input[key] === 'function') {
toJSON += `null`;
} else if (typeof input[key] === 'number') {
toJSON += `${input[key]}`;
} else if (typeof input[key] === 'string') {
toJSON += `"${input[key]}"`;
}
if (key != Object.keys(input)[Object.keys(input).length - 1]) {
toJSON += ',';
}
}
return toJSON + '}';
}
Now if I uncomment the recursive code, it breaks the array code that is currently working and I get this: