@bitblit/ratchet-common
Version:
Common tools for general use
67 lines • 2.74 kB
JavaScript
import { Logger } from '../logger/logger.js';
export class TransformRatchet {
static transform(toTransform, rules = []) {
return TransformRatchet.transformGeneric(toTransform, rules, false, null);
}
static transformGeneric(toTransform, rules = [], isKey, context) {
let rval = null;
const type = typeof toTransform;
switch (type) {
case 'undefined':
case 'symbol':
case 'function':
rval = toTransform;
break;
case 'number':
case 'string':
case 'boolean':
rval = TransformRatchet.applyTransformToPrimitive(toTransform, rules, isKey, context);
break;
case 'object':
rval = TransformRatchet.applyTransformToObject(toTransform, rules, isKey, context);
break;
default:
throw new Error('Unrecognized type ' + type);
}
return rval;
}
static applyTransformToObject(toTransform, rules = [], isKey, context = null) {
Logger.silly('Tranform: %j, %s, %j', toTransform, isKey, context);
let rval = null;
if (toTransform != null) {
if (Array.isArray(toTransform)) {
rval = [];
toTransform.forEach((val) => {
const newVal = TransformRatchet.transformGeneric(val, rules, isKey, toTransform);
if (newVal != null) {
rval.push(newVal);
}
});
}
else {
rval = {};
Object.keys(toTransform).forEach((k) => {
const oldValue = toTransform[k];
const newKey = TransformRatchet.applyTransformToPrimitive(k, rules, true, toTransform);
if (newKey != null) {
let newValue = TransformRatchet.transformGeneric(oldValue, rules, false, toTransform);
newValue = TransformRatchet.applyTransformToPrimitive(newValue, rules, false, toTransform);
if (newValue != null) {
rval[newKey] = newValue;
}
}
});
rval = TransformRatchet.applyTransformToPrimitive(rval, rules, false, toTransform);
}
}
return rval;
}
static applyTransformToPrimitive(toTransform, rules = [], isKey, context) {
let rval = toTransform;
rules.forEach((r) => {
rval = rval == null ? null : r.transform(rval, isKey, context);
});
return rval;
}
}
//# sourceMappingURL=transform-ratchet.js.map