From f041fcb775d0f358db5b60d2f92a3d9c0d8398e8 Mon Sep 17 00:00:00 2001 From: Jason Staten Date: Sun, 10 Sep 2023 00:11:44 -0600 Subject: [PATCH] nesting --- ngron.mjs | 32 ++++++++++++++++++++++---------- ngron.test.mjs | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 67 insertions(+), 14 deletions(-) diff --git a/ngron.mjs b/ngron.mjs index 4970557..91dd302 100644 --- a/ngron.mjs +++ b/ngron.mjs @@ -1,23 +1,35 @@ -const iter = (obj, stack) => { - const key = stack.join('.'); +const iter = (obj, key, lines) => { if (obj === null) { - return `${key}=null` + lines.push(`${key}=null;`) + return + } + if (Array.isArray(obj)) { + lines.push(`${key}=[];`) + obj.forEach((v, idx) => { + iter(v, `${key}[${idx}]`, lines); + }); + return } if (typeof obj === "object") { - return `${key}={}` + lines.push(`${key}={};`) + for (const [k,v] of Object.entries(obj)) { + iter(v, `${key}.${k}`, lines); + } + return } if (typeof obj === "string") { - return `${key}=${JSON.stringify(obj)}` + lines.push(`${key}=${JSON.stringify(obj)};`); + return } - - return `${key}=${obj}` - + lines.push(`${key}=${obj};`) } -export const gronify = (obj) => { +export const gronify = (obj) => { + const lines = [] + iter(obj, ["json"], lines) - return iter(obj, ["json"]) + return lines.join('\n'); } diff --git a/ngron.test.mjs b/ngron.test.mjs index 3a673ab..c7fc8c3 100644 --- a/ngron.test.mjs +++ b/ngron.test.mjs @@ -5,24 +5,65 @@ import { gronify } from "./ngron.mjs"; test("number", () => { const result = gronify(3) - assert.strictEqual(result, `json=3`) + assert.strictEqual(result, `json=3;`) }); test("string", () => { const result = gronify("hello") - assert.strictEqual(result, `json="hello"`) + assert.strictEqual(result, `json="hello";`) }); test("empty obj", () => { const result = gronify({}) - assert.strictEqual(result, `json={}`) + assert.strictEqual(result, `json={};`) }); test("null", () => { const result = gronify(null) - assert.strictEqual(result, `json=null`) + assert.strictEqual(result, `json=null;`) +}); + +test("empty array", () => { + const result = gronify([]) + assert.strictEqual(result, `json=[];`) +}); + +test("nested obj", () => { + const result = gronify({one: 1}) + + assert.strictEqual(result, `json={}; +json.one=1;`) +}); + +test("nested array", () => { + const result = gronify(["hello", "world"]) + + assert.strictEqual(result, `json=[]; +json[0]="hello"; +json[1]="world";`) +}); + +test("complex", () => { + const result = gronify([ + {name: "Alice", startYear: 2001}, + {name: "Ralph", startYear: 2010}, + {name: "Jesse", startYear: 2007, tired: true}, +]) + + assert.strictEqual(result, `json=[]; +json[0]={}; +json[0].name="Alice"; +json[0].startYear=2001; +json[1]={}; +json[1].name="Ralph"; +json[1].startYear=2010; +json[2]={}; +json[2].name="Jesse"; +json[2].startYear=2007; +json[2].tired=true;`); + });