main
Jason Staten 1 year ago
parent a773f29eb9
commit f041fcb775

@ -1,23 +1,35 @@
const iter = (obj, stack) => { const iter = (obj, key, lines) => {
const key = stack.join('.');
if (obj === null) { 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") { 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") { if (typeof obj === "string") {
return `${key}=${JSON.stringify(obj)}` lines.push(`${key}=${JSON.stringify(obj)};`);
return
} }
lines.push(`${key}=${obj};`)
return `${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", () => { test("number", () => {
const result = gronify(3) const result = gronify(3)
assert.strictEqual(result, `json=3`) assert.strictEqual(result, `json=3;`)
}); });
test("string", () => { test("string", () => {
const result = gronify("hello") const result = gronify("hello")
assert.strictEqual(result, `json="hello"`) assert.strictEqual(result, `json="hello";`)
}); });
test("empty obj", () => { test("empty obj", () => {
const result = gronify({}) const result = gronify({})
assert.strictEqual(result, `json={}`) assert.strictEqual(result, `json={};`)
}); });
test("null", () => { test("null", () => {
const result = gronify(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