data-to-jsonschema-to-ts
Version:
Convert plain javascript objects to JSON Schema and TypeScript typings
79 lines • 2.44 kB
JavaScript
/**
* Recursively traverses an object and calls a callback for each primitive value encountered
* @param obj The object to traverse
* @param handlePrimitive Callback function called for each primitive value
* @param currentPath Current JSON path (used internally for recursion)
*/
export function traverseObject(obj, handlePrimitive, currentPath = "") {
// Handle null separately since typeof null === 'object'
if (obj === null) {
handlePrimitive(obj, currentPath, {
key: "",
parent: {
path: currentPath,
type: "object",
},
});
return;
}
// Handle arrays
if (Array.isArray(obj)) {
obj.forEach((item, index) => {
const newPath = currentPath ? `${currentPath}[${index}]` : `[${index}]`;
if (isPrimitive(item)) {
handlePrimitive(item, newPath, {
key: index,
parent: {
path: currentPath,
type: "array",
},
});
}
else {
traverseObject(item, handlePrimitive, newPath);
}
});
return;
}
// Handle objects
if (typeof obj === "object") {
Object.entries(obj).forEach(([key, value]) => {
const newPath = currentPath ? `${currentPath}.${key}` : key;
if (isPrimitive(value)) {
handlePrimitive(value, newPath, {
key,
parent: {
path: currentPath,
type: "object",
},
});
}
else {
traverseObject(value, handlePrimitive, newPath);
}
});
return;
}
// Handle primitive values at root level
if (currentPath) {
handlePrimitive(obj, currentPath, {
key: "",
parent: {
path: currentPath,
type: Array.isArray(obj) ? "array" : "object",
},
});
}
return;
}
/**
* Type guard to check if a value is a primitive
*/
function isPrimitive(value) {
return (value === null ||
value === undefined ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean");
}
//# sourceMappingURL=traverse-object.js.map