main
Jason Staten 8 months ago
parent a773f29eb9
commit f041fcb775

@ -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');
}

@ -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;`);
});

Loading…
Cancel
Save