I am trying to redo some of the examples in Request, to familiarize with request and also JS in general, and was stuck with below code. The original code is written in ‘Switch,case’ conditional statement, I am trying to use ‘If else’ statement.
//Original:
const formatJson = (resJson) => {
resJson = JSON.stringify(resJson);
let counter = 0;
return resJson.split(’’)
.map(char => {
switch (char) {
case ‘,’:
return ,\n${' '.repeat(counter * 2)}
;
case ‘{’:
counter += 1;
return {\n${' '.repeat(counter * 2)}
;
case ‘}’:
counter -= 1;
return \n${' '.repeat(counter * 2)}}
;
default:
return char;
}
})
.join(’’);
};
//My version:
const formatJson = (resJson) => {
resJson = JSON.stringify(resJson);
let counter = 0;
return resJson.split(’’).map(char => {
if (char == ‘,’) {
return ,\n${' '.repeat(counter * 2)}
;
} else if (char == ‘{’) {
return counter +=
{\n${' '.repeat(counter * 2)}
;
} else if (char == ‘}’) {
return counter -=
\n${' '.repeat(counter * 2)}}
;
} else {
return char;
}
}).join(’’)
};
The problem, I narrowed down, it’s the ‘counter’. In switch statement, after comparing case with the switch, if truthy, we can add the counter, but I can’t seems to do it in if else statement.
Please help, thanks in advanced.