LoginSignup
2

More than 5 years have passed since last update.

JSON.stringifyを自分で作ってみた

Last updated at Posted at 2017-12-21

そういえば自分で実装したことがあったので、せっかくなので公開してみる。
ちなみに結構しんどかった。

  const _ = require('underscore'); // ライブラリunderscoreを使う。

  const addDoubleQuatationToString = function (str) {
    if (typeof str === 'string') {
      return '\"' + str + '\"';
    } else {
      return str;
    }
  };

  const arrWithNoElement = function (arr) {
    return Array.isArray(arr) && arr.length === 0;
  };

  const objWithNoPropety = function (obj) {
    return typeof obj === 'object' && !Array.isArray(obj) && Object.keys(obj).length === 0;
  };

  const isNotObject = function (obj) {
    return typeof obj !== 'object';
  };

  const isBaseCase = function (obj) {
    return obj === null || isNotObject(obj) || arrWithNoElement(obj) || objWithNoPropety(obj);
  };

  const stringify = function(obj) {
    let resultString = '';
    let count = 0;

    if (isBaseCase(obj)) {
      if (obj === null) {
        resultString += obj;
      } else if (arrWithNoElement(obj)) {
        resultString += '[]';
      } else if (objWithNoPropety(obj)) {
        resultString += '{}';
      } else {
        resultString += addDoubleQuatationToString(obj);
      }
      return resultString; 
    } else {
      _.each(obj, function (value, indexOrKey, iteratedObj) {
        if (Array.isArray(iteratedObj)) {
          if (count === 0) {
            let addedString = stringify(value);
            resultString += '[' + addedString;
          } else {
            let addedString = stringify(value);
            resultString += ',' + addedString;
          } 
          count ++;
          if (arrWithNoElement(iteratedObj) || count === iteratedObj.length) {
            resultString += ']';
          }
        } else {
          if (count === 0) {
            let addedString = stringify(value);
            resultString += '{' + addDoubleQuatationToString(indexOrKey) + ':' + addedString;
          } else {
            let addedString = stringify(value);
            resultString += ',' + addDoubleQuatationToString(indexOrKey) + ':' + addedString;
          } 
          count ++;
          if (count === Object.keys(iteratedObj).length) {
            resultString += '}';
          }
        }
      });
      return resultString;
    }

  };

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2