Skip to content

Instantly share code, notes, and snippets.

@Jiert
Created February 2, 2017 21:12
Show Gist options
  • Select an option

  • Save Jiert/3d3f62e63f1597ebb0038f2f1c98b905 to your computer and use it in GitHub Desktop.

Select an option

Save Jiert/3d3f62e63f1597ebb0038f2f1c98b905 to your computer and use it in GitHub Desktop.

Revisions

  1. Jiert created this gist Feb 2, 2017.
    37 changes: 37 additions & 0 deletions stringify.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    // Implement JSON.stringify
    var example = {
    "array": [1, 2, 3],
    "number": 123,
    "object": {
    "a": "b",
    "c": "d",
    "e": "f"
    },
    "string": "Hello World"
    }


    var stringify = function(obj) {
    var output = "";

    if (typeof(obj) === 'number') {
    output = output.concat(obj)
    } else if (typeof(obj) === 'string') {
    output = output.concat('"', obj, '"')
    } else if (Array.isArray(obj)) {
    output = output.concat('[', obj.map(stringify), ']')
    } else if (typeof(obj) === 'object') {
    var entries = Object.entries(obj);

    output = output.concat('{', entries.map(function(entry) {
    return "".concat('"', entry[0], '":', stringify(entry[1]))
    }), '}')
    }

    return output;
    }

    var output = stringify(example);

    console.log(output)