Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8c3c2f7

Browse files
committed
Add solution #2633
1 parent 6f25e24 commit 8c3c2f7

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1976,6 +1976,7 @@
19761976
2630|[Memoize II](./solutions/2630-memoize-ii.js)|Hard|
19771977
2631|[Group By](./solutions/2631-group-by.js)|Medium|
19781978
2632|[Curry](./solutions/2632-curry.js)|Medium|
1979+
2633|[Convert Object to JSON String](./solutions/2633-convert-object-to-json-string.js)|Medium|
19791980
2634|[Filter Elements from Array](./solutions/2634-filter-elements-from-array.js)|Easy|
19801981
2635|[Apply Transform Over Each Element in Array](./solutions/2635-apply-transform-over-each-element-in-array.js)|Easy|
19811982
2636|[Promise Pool](./solutions/2636-promise-pool.js)|Medium|
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* 2633. Convert Object to JSON String
3+
* https://leetcode.com/problems/convert-object-to-json-string/
4+
* Difficulty: Medium
5+
*
6+
* Given a value, return a valid JSON string of that value. The value can be a string, number,
7+
* array, object, boolean, or null. The returned string should not include extra spaces. The
8+
* order of keys should be the same as the order returned by Object.keys().
9+
*
10+
* Please solve it without using the built-in JSON.stringify method.
11+
*/
12+
13+
/**
14+
* @param {null|boolean|number|string|Array|Object} object
15+
* @return {string}
16+
*/
17+
var jsonStringify = function(object) {
18+
if (object === null) return 'null';
19+
if (typeof object === 'boolean' || typeof object === 'number') return String(object);
20+
if (typeof object === 'string') return `"${object}"`;
21+
22+
if (Array.isArray(object)) {
23+
const elements = object.map(item => jsonStringify(item));
24+
return `[${elements.join(',')}]`;
25+
}
26+
27+
const pairs = Object.keys(object).map(key => `"${key}":${jsonStringify(object[key])}`);
28+
return `{${pairs.join(',')}}`;
29+
};

0 commit comments

Comments
 (0)