题目

假设一个object对象中有且仅有以下4种数据类型:string,number,array,object
其中:

  • string转化为:string.length + : + string
    • “abc” - “3:abc”
  • number转化为:i + number + e
    • 2 - “i2e”
  • array转为:l + 数组内容 + e
    • 空数组[] - “le”
    • 带string和number的数组:[1,”abc”] - “l i1e 3:abc e” (无空格)
    • 嵌套数组和对象:[[],[]] - “le le le le” (无空格)
  • object转为:d + key+value + e

    • 空对象{} - “de”
    • {x:”abc”,y:2} - “d 1:x 3:abc 1:y i2e e” (无空格)
    • 嵌套数组和对象:{x:{y:[]}} - “d 1:x d 1:y le e e “ (无空格)

      分析

      ``typescript function jsonStr(json: object): string { // 类型判定 function isString(x: unknown): x is string { return typeof x === "string"; } function isNumber(x: unknown): x is number { return typeof x === "number"; } function isArray(x: unknown): x is Array<any> { return Array.isArray(x); } // 序列化 function getString(x: string) { return${x.length}:${x}; } function getNumber(x: number) { returni${x}e; } function getArray(x: Array<any>) { let result = x.map(v => getAll(v)); returnl${result.join(“”)}e; } function getObject(x: object) { let result = Object.entries(x).map( ([key, value]) =>${getAll(key)}${getAll(value)}); returnd${result.join(“”)}e`; } // 统一序列化 function getAll(x: unknown): string { return isString(x) ? getString(x) : isNumber(x) ? getNumber(x) : isArray(x) ? getArray(x) : getObject(x as object); }

    // test console.log( getAll(“abc”) === “3:abc”, getAll(123) === “i123e”, getAll([]) === “le”, getAll([“abc”, 123, []]) === “l3:abci123elee”, getAll({}) === “de”, getAll({ a: “abc”, b: 123, c: [], d: {} }) ===

    1. "d1:a3:abc1:bi123e1:cle1:ddee"

    );

    // 执行运行函数 return getAll(json); }

// test let input = { a: “abc”, b: 123, c: [“abc”, 123, []], d: { x: “abc”, y: 123, z: {} }, }; let output = “d1:a3:abc1:bi123e1:cl3:abci123elee1:dd1:x3:abc1:yi123e1:zdeee”; console.log(jsonStr(input) === output); ```