"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* Design by Contract module (c) OptimalBits 2011. Roadmap: - Optional parameters. ['(string)', 'array'] - Variable number of parameters.['number','...'] api?: contract(arguments) .params('string', 'array', '...') .params('number') .end() */ let noop = {}; const _ = require("lodash"); // import { IContract } from './interfaces'; noop.params = function () { return this; }; noop.end = function () { }; exports.contract = function (args) { if (exports.contract.debug === true) { exports.contract.fulfilled = false; exports.contract.args = _.toArray(args); exports.contract.checkedParams = []; return exports.contract; } else { return noop; } }; function checkParams(args, contract) { let fulfilled, types, type, i, j; if (args.length !== contract.length) { return false; } else { for (i = 0; i < args.length; i++) { try { types = contract[i].split('|'); } catch (e) { console.log(e, args); } type = typeOf(args[i]); fulfilled = false; for (j = 0; j < types.length; j++) { if (type === types[j]) { fulfilled = true; break; } } if (fulfilled === false) { return false; } } return true; } } exports.checkParams = checkParams; ; exports.contract.params = function () { this.fulfilled |= checkParams(this.args, _.toArray(arguments)); if (this.fulfilled) { return noop; } else { this.checkedParams.push(arguments); return this; } }; exports.contract.end = function () { if (!this.fulfilled) { printParamsError(this.args, this.checkedParams); throw new Error('Broke parameter contract'); } }; let typeOf = function (obj) { return Array.isArray(obj) ? 'array' : typeof obj; }; function printParamsError(args, checkedParams) { let msg = 'Parameter mismatch.\nInput:\n( ', type, input, i; _.each(args, function (input, key) { type = typeOf(input); if (key !== 0) { msg += ', '; } msg += input + ': ' + type; }); msg += ')\nAccepted:\n'; for (i = 0; i < checkedParams.length; i++) { msg += '(' + argsToString(checkedParams[i]) + ')\n'; } console.log(msg); } exports.printParamsError = printParamsError; ; function argsToString(args) { let res = ""; _.each(args, function (arg, key) { if (key !== 0) { res += ', '; } res += arg; }); return res; } exports.argsToString = argsToString; // exports = module.exports = contract; //# sourceMappingURL=contract.js.map