UNPKG

ts-simple-mapper

Version:

A lightweight utility for mapping object properties between different shapes

51 lines (50 loc) 1.67 kB
// src/index.ts function simpleMap(source, options = {}) { const { exclude = [], transforms = {}, fieldMappings = {} } = options; const result = {}; for (const sourceKey in source) { if (Object.prototype.hasOwnProperty.call(source, sourceKey)) { if (exclude.includes(sourceKey)) continue; const targetKey = Object.entries(fieldMappings).find(([_, value2]) => value2 === sourceKey)?.[0] || sourceKey; const value = source[sourceKey]; if (transforms && targetKey in transforms) { const transform = transforms[targetKey]; if (typeof transform === "function") { result[targetKey] = transform(cloneValue(value)); } else if (typeof transform === "object" && transform !== null && typeof value === "object" && value !== null) { result[targetKey] = simpleMap(value, { transforms: transform }); } else { result[targetKey] = cloneValue(value); } } else { result[targetKey] = cloneValue(value); } } } return result; } function cloneValue(value, seen = /* @__PURE__ */ new WeakSet()) { if (value === null || typeof value !== "object") { return value; } if (seen.has(value)) { throw new Error("Circular reference detected during deep cloning"); } seen.add(value); if (Array.isArray(value)) { return value.map((item) => cloneValue(item, seen)); } if (value instanceof Date) { return new Date(value); } const result = {}; for (const key in value) { if (Object.prototype.hasOwnProperty.call(value, key)) { result[key] = cloneValue(value[key], seen); } } return result; } export { simpleMap };