Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 JSON parse / stringify #51

Open
fedono opened this issue Sep 24, 2023 · 2 comments
Open

实现 JSON parse / stringify #51

fedono opened this issue Sep 24, 2023 · 2 comments

Comments

@fedono
Copy link
Owner

fedono commented Sep 24, 2023

/**
 * @param {string} str
 * @return {object | Array | string | number | boolean | null}
 */
function parse(str) {
  if(str === '') {
    throw Error();
  }
  if(str[0] === "'") {
    throw Error();
  }
  if(str === 'null') {
    return null;
  }
  if(str === '{}') {
    return {};
  }
  if(str === '[]') {
    return [];
  }
  if(str === 'true') {
    return true;
  }
  if(str === 'false') {
    return false;
  }
  if(str[0] === '"') {
    return str.slice(1, -1);
  }
  if(+str === +str) {
    return Number(str);
  }
  if(str[0] === '{') {
    return str.slice(1, -1).split(',').reduce((acc, item) => {
      const index = item.indexOf(':');
      const key = item.slice(0, index)
      const value = item.slice(index + 1);
      acc[parse(key)] = parse(value);
      return acc;
    }, {});
  }
  if(str[0] === '[') {
    return str.slice(1, -1).split(',').map((value) => parse(value));
  }
}

来源 - implement-JSON-parse

@fedono
Copy link
Owner Author

fedono commented Sep 24, 2023

取巧的方案

/**
 * @param {string} str
 * @return {object | Array | string | number | boolean | null}
 */
function parse(str) {
    let result = (new Function(`return ${str.replace(/\"/g,"'")}`))();

    if(str !== JSON.stringify(result)) {
      throw new Error("Nope");
    }

    return result;
}

@fedono fedono changed the title 实现 JSON parse 实现 JSON parse / stringify Sep 24, 2023
@fedono
Copy link
Owner Author

fedono commented Sep 24, 2023

实现 stringify

/**
 * @param {any} data
 * @return {string}
 */
function stringify(data) {
  if(typeof data === 'bigint') {
    throw new Error('Do not know how to serialize a BigInt at JSON.stringify');
  } 
  if(typeof data === 'string') {
    return `"${data}"`;
  } 
  if(typeof data === 'function') {
    return undefined;
  }
  if(data !== data) {
    return 'null';
  }
  if(data === Infinity) {
    return 'null';
  }
  if(data === -Infinity) {
    return 'null';
  }
  if(typeof data === 'number') {
   return `${data}`;
  }
  if(typeof data === 'boolean') {
    return `${data}`;
  }
  if(data === null) {
    return 'null';
  }
  if(data === undefined) {
    return 'null';
  }
  if(typeof data === 'symbol') {
    return 'null';
  }
  if(data instanceof Date) {
    return `"${data.toISOString()}"`;
  }
  if(Array.isArray(data)) {
    const arr = data.map((el) => stringify(el));
    return `[${arr.join(',')}]`;
  }
  if(typeof data === 'object') {
    const arr = Object.entries(data).reduce((acc, [key, value]) => {
      if(value === undefined) {
        return acc;
      }
      acc.push(`"${key}":${stringify(value)}`);
      return acc;
    }, [])
    return `{${arr.join(',')}}`;
  }
}

来源 - implement-JSON-stringify

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant