自編自用筆試題:給JSON.stringify的簡化實現添加「環」檢查算法

### 題目javascript

JSON.stringify 的功能是,將一個 javascript 字面量對象轉化爲一個JSON格式的字符串。例如java

const obj = {a:1, b:2}

JSON.stringify(obj) // => '{"a":1,"b":2}'

當要轉化的對象有「環」存在時,爲了不死循環,JSON.stringify 會拋出異常,例如:json

const obj = {
  foo: {
    name: 'foo'
  },
  bar: {
    name: 'bar'
    baz: {
      name: 'baz',
      next: null // 將指向obj.bar
    }
  }
}

obj.bar.baz.next = obj.bar

JSON.stringify(obj) // => TypeError: Converting circular structure to JSON

假設入參是字面量對象,屬性名是字符串,屬性值要麼是數字字面量,要麼是字面量對象,不考慮json排版,JSON.stringify的簡化版實現以下:函數

/**
 * 「環」檢查器
 */
function detectorCircular(obj) {
  // 請實現
}

/**
 * JSON.stringify簡化實現
 * @param obj 要轉化爲字符串的對象
 * @param ignoreCircular 是否忽略「環」檢查
 */
function stringify(obj, ignoreCircular = false) {
  if (!ignoreCircular && detectorCircular(obj)) {
    throw new TypeError('Converting circular structure to JSON')
  }

  const keys = Object.keys(obj)
  
  if (!keys.length) {
    return '{}'
  }
  
  const content = keys.map(key => {
    const value = obj[key]
    
    if (typeof value === 'number') {
      return `"${key}":${value}`
    } else {
      return `"${key}":${stringify(value, true)}`
    }
  }).join(',')
  
  return `{${content}}`
}

請實現上述代碼中的 detectorCircular 函數。code

相關文章
相關標籤/搜索