fixedstr
Version:
Transforms fixed string to object and vice versa
71 lines • 2.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
function parseText(str) {
return str.trim();
}
function textToString(field, value) {
value = value || '';
const endLength = Math.max(0, field.size + 1 - value.length);
const end = new Array(endLength).join(' ');
return value + end;
}
class FixedStr {
static str(name, size) {
return {
name: name,
size: size
};
}
static strTrunc(name, size) {
return {
name: name,
size: size,
toFixedString: (field, value) => {
const str = (value || '').substring(0, size);
return textToString(field, str);
}
};
}
static number(name, size) {
return {
name: name,
size: size,
parse: Number,
toFixedString: (field, value) => {
const strVal = value && value.toString ? value.toString() : '0';
const pad = new Array(Math.max(0, field.size + 1 - strVal.length)).join('0');
return pad + strVal;
}
};
}
constructor(ObjectDefinitions) {
this.objDef = ObjectDefinitions;
}
objectify(str) {
let from = 0;
str = str || '';
return this.objDef.reduce((obj, field) => {
const parse = field.parse || parseText;
obj[field.name] = parse(str.substring(from, from + field.size));
from += field.size;
return obj;
}, {});
}
stringify(obj) {
return this.objDef.reduce((str, field) => {
const toStr = field.toFixedString || textToString;
const strValue = toStr(field, obj[field.name]);
if (strValue && strValue.length > field.size) {
throw new Error('truncation error on field: ' +
field.name +
', size: ' +
field.size +
', value: ' +
obj[field.name]);
}
return str + strValue;
}, '');
}
}
exports.FixedStr = FixedStr;
//# sourceMappingURL=index.js.map