UNPKG

diffusion

Version:

Diffusion JavaScript client

125 lines (102 loc) 2.82 kB
var Type = { DECIMAL : "DECIMAL", INTEGER : "INTEGER", STRING : "STRING" }; module.exports = function FieldImpl(name, type, min, max, index, scale) { this.name = name; this.type = type; this.min = min; this.max = max; if (scale !== undefined) { this.scale = scale; } this.index = index; this.isVariable = min !== max; this.getAbsoluteIndex = function(_index) { if (_index < 0 || max !== -1 && _index > max - 1) { throw new Error("Invalid index '" + _index + "' for field '" + name + "'"); } return index + _index; }; this.toString = function() { var ret = "Field [Name=" + name + ", Type=" + type; if (min === max) { ret += ", Occurs=" + min; } else { ret += ", Min=" + min + ", Max="; if (max === -1) { ret += "Unlimited"; } else { ret += max; } } if (type === Type.DECIMAL) { ret += ", Scale=" + scale; } return ret + "]"; }; }; // Returns a validated value in the format indicated by the field module.exports.normalise = function(field, value) { switch (field.type) { case Type.DECIMAL : var f = parseFloat(value); if (Number.isNaN(f)) { throw new Error("Invalid decimal value: '" + value + "'"); } return f.toFixed(field.scale); case Type.INTEGER : var i = parseInt(value); var s = i.toString(); if (Number.isNaN(i) || s.indexOf(".") > -1) { throw new Error("Invalid integer value: '" + value + ''); } return s; case Type.STRING : return value; default : return ""; } }; module.exports.toJSON = function(field) { var o = { name : field.name, type : field.type, min : field.min, max : field.max }; if (field.type === Type.DECIMAL) { o.scale = field.scale; } return o; }; module.exports.modelValue = function(field) { switch (field.type) { case Type.DECIMAL : return decimalModelValue(field); case Type.INTEGER : return "0"; case Type.STRING : return ""; default: return ""; } }; function decimalModelValue(field) { switch (field.scale) { case 1 : return "0.0"; case 2 : return "0.000"; case 3 : return "0.000"; default : var ret = "0."; for (var i = 0; i < field.scale; ++i) { ret += "0"; } return ret; } } module.exports.Type = Type;