typhonjs-escomplex-commons
Advanced tools
Comparing version 0.0.8 to 0.0.9
@@ -30,3 +30,5 @@ 'use strict'; | ||
/** | ||
* Provides a class report. | ||
* Provides the class report object which stores data pertaining to a single ES6 class. | ||
* | ||
* Methods that are stored as MethodReports in the `methods` member variable. | ||
*/ | ||
@@ -99,4 +101,4 @@ | ||
this.methods.forEach(function (report) { | ||
report.finalize(); | ||
this.methods.forEach(function (methodReport) { | ||
methodReport.finalize(); | ||
}); | ||
@@ -120,17 +122,17 @@ | ||
if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') { | ||
throw new TypeError('parse error: `object` is not an `object`.'); | ||
throw new TypeError('parse error: \'object\' is not an \'object\'.'); | ||
} | ||
var report = Object.assign(new ClassReport(), object); | ||
var classReport = Object.assign(new ClassReport(), object); | ||
// Must explicitly assign `aggregate` to `report._methodReport` and re-assign data. | ||
report.aggregate = Object.assign(report._methodReport, object.aggregate); | ||
// Must explicitly assign `aggregate` to `classReport._methodReport` and re-assign data. | ||
classReport.aggregate = Object.assign(classReport._methodReport, object.aggregate); | ||
if (report.methods.length > 0) { | ||
report.methods = report.methods.map(function (report) { | ||
return _MethodReport2.default.parse(report); | ||
if (classReport.methods.length > 0) { | ||
classReport.methods = classReport.methods.map(function (methodReport) { | ||
return _MethodReport2.default.parse(methodReport); | ||
}); | ||
} | ||
return report; | ||
return classReport; | ||
} | ||
@@ -137,0 +139,0 @@ }]); |
@@ -30,3 +30,5 @@ 'use strict'; | ||
/** | ||
* Provides a method report. | ||
* Provides the method report object which stores data pertaining to a single method / function. | ||
* | ||
* | ||
*/ | ||
@@ -188,3 +190,3 @@ | ||
if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') { | ||
throw new TypeError('parse error: `object` is not an `object`.'); | ||
throw new TypeError('parse error: \'object\' is not an \'object\'.'); | ||
} | ||
@@ -191,0 +193,0 @@ |
@@ -25,2 +25,10 @@ 'use strict'; | ||
var _MathUtil = require('../../utils/MathUtil'); | ||
var _MathUtil2 = _interopRequireDefault(_MathUtil); | ||
var _TransformFormat = require('../../transform/TransformFormat'); | ||
var _TransformFormat2 = _interopRequireDefault(_TransformFormat); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -35,3 +43,8 @@ | ||
/** | ||
* Provides the default report object which stores data pertaining to a single file / module being processed. | ||
* Provides the module report object which stores data pertaining to a single file / module being processed. | ||
* | ||
* All ES Module classes are stored in the `classes` member variable as ClassReports. Methods that are not part of a | ||
* class are stored as MethodReports in the `methods` member variable. | ||
* | ||
* Various helper methods found in ModuleReport and AbstractReport help increment associated data during collection. | ||
*/ | ||
@@ -52,3 +65,5 @@ | ||
function ModuleReport(lineStart, lineEnd) { | ||
function ModuleReport() { | ||
var lineStart = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; | ||
var lineEnd = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; | ||
var settings = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; | ||
@@ -263,3 +278,3 @@ | ||
return this; | ||
return _MathUtil2.default.toFixedTraverse(this); | ||
} | ||
@@ -292,12 +307,31 @@ | ||
/** | ||
* Provides a default array and indices for summing maintainability metrics via `sumMetrics`. | ||
* Returns the supported format file extension types. | ||
* | ||
* @returns {{sums: number[], indices: {cyclomatic: number, effort: number, loc: number, maintainability: number, params: number}}} | ||
* @returns {string[]} | ||
*/ | ||
}, { | ||
key: 'halsteadItemEncountered', | ||
key: 'getSetting', | ||
/** | ||
* Returns the setting indexed by the given key. | ||
* | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} defaultValue - A default value to return if no setting for the given key is currently stored. | ||
* | ||
* @returns {*} | ||
*/ | ||
value: function getSetting(key) { | ||
var defaultValue = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1]; | ||
/* istanbul ignore if */ | ||
if (typeof key !== 'string' || key === '') { | ||
throw new TypeError('getSetting error: \'key\' is not a \'string\' or is empty.'); | ||
} | ||
return _typeof(this.settings) === 'object' && typeof this.settings[key] !== 'undefined' ? this.settings[key] : defaultValue; | ||
} | ||
/** | ||
* Increments the Halstead `metric` for the given `identifier` for the ModuleReport and any current class or method | ||
@@ -309,2 +343,5 @@ * report being tracked. | ||
*/ | ||
}, { | ||
key: 'halsteadItemEncountered', | ||
value: function halsteadItemEncountered(metric, identifier) { | ||
@@ -406,3 +443,3 @@ var currentClassReport = this.getCurrentClassReport(); | ||
* | ||
* @param {ModuleReport} metric - The Halstead metric being processed. | ||
* @param {string} metric - The Halstead metric being processed. | ||
* @param {Array<string>} identifiers - An array of Halstead identifiers. | ||
@@ -422,2 +459,27 @@ */ | ||
/** | ||
* Sets the setting indexed by the given key and returns true if successful. | ||
* | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} value - A value to set to `this.settings[key]`. | ||
* | ||
* @returns {boolean} | ||
*/ | ||
}, { | ||
key: 'setSetting', | ||
value: function setSetting(key, value) { | ||
/* istanbul ignore if */ | ||
if (typeof key !== 'string' || key === '') { | ||
throw new TypeError('setSetting error: \'key\' is not a \'string\' or is empty.'); | ||
} | ||
if (this.settings === 'object') { | ||
this.settings[key] = value; | ||
return true; | ||
} | ||
return false; | ||
} | ||
/** | ||
* Provides a convenience method to increment metric sums given an object hash of indices. | ||
@@ -448,3 +510,57 @@ * | ||
} | ||
/** | ||
* Formats this ModuleReport given the type. | ||
* | ||
* @param {string} name - The name of formatter to use. | ||
* | ||
* @param {object} options - (Optional) One or more optional parameters to pass to the formatter. | ||
* | ||
* @returns {string} | ||
*/ | ||
}, { | ||
key: 'toFormat', | ||
value: function toFormat(name) { | ||
var options = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1]; | ||
return _TransformFormat2.default.format(this, name, options); | ||
} | ||
}], [{ | ||
key: 'getFormatFileExtensions', | ||
value: function getFormatFileExtensions() { | ||
return _TransformFormat2.default.getFileExtensions(); | ||
} | ||
/** | ||
* Returns the supported format names. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
}, { | ||
key: 'getFormatNames', | ||
value: function getFormatNames() { | ||
return _TransformFormat2.default.getNames(); | ||
} | ||
/** | ||
* Returns the supported format types. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
}, { | ||
key: 'getFormatTypes', | ||
value: function getFormatTypes() { | ||
return _TransformFormat2.default.getTypes(); | ||
} | ||
/** | ||
* Provides a default array and indices for summing maintainability metrics via `sumMetrics`. | ||
* | ||
* @returns {{sums: number[], indices: {cyclomatic: number, effort: number, loc: number, maintainability: number, params: number}}} | ||
*/ | ||
}, { | ||
key: 'getMaintainabilityMetrics', | ||
@@ -459,3 +575,3 @@ value: function getMaintainabilityMetrics() { | ||
if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') { | ||
throw new TypeError('parse error: `object` is not an `object`.'); | ||
throw new TypeError('parse error: \'object\' is not an \'object\'.'); | ||
} | ||
@@ -469,4 +585,4 @@ | ||
if (report.classes.length > 0) { | ||
report.classes = report.classes.map(function (report) { | ||
return _ClassReport2.default.parse(report); | ||
report.classes = report.classes.map(function (classReport) { | ||
return _ClassReport2.default.parse(classReport); | ||
}); | ||
@@ -476,4 +592,4 @@ } | ||
if (report.methods.length > 0) { | ||
report.methods = report.methods.map(function (report) { | ||
return _MethodReport2.default.parse(report); | ||
report.methods = report.methods.map(function (methodReport) { | ||
return _MethodReport2.default.parse(methodReport); | ||
}); | ||
@@ -480,0 +596,0 @@ } |
@@ -22,3 +22,3 @@ 'use strict'; | ||
/** | ||
* Provides a wrapper around an array of Halstead properties object hashes which should contain an | ||
* Provides a wrapper around an array of Halstead property object hashes which should contain an | ||
* `identifier` field and potentially a `filter` field. | ||
@@ -25,0 +25,0 @@ */ |
@@ -120,7 +120,11 @@ 'use strict'; | ||
return this._data.identifier.map(function (entry) { | ||
return typeof entry === 'function' ? entry.apply(undefined, params) : entry; | ||
var value = typeof entry === 'function' ? entry.apply(undefined, params) : entry; | ||
return typeof value === 'number' ? value.toString() : value; | ||
}); | ||
} | ||
return typeof this._data.identifier === 'function' ? (_data2 = this._data).identifier.apply(_data2, params) : this._data.identifier; | ||
var value = typeof this._data.identifier === 'function' ? (_data2 = this._data).identifier.apply(_data2, params) : this._data.identifier; | ||
return typeof value === 'number' ? value.toString() : value; | ||
} | ||
@@ -127,0 +131,0 @@ }, { |
@@ -11,2 +11,6 @@ 'use strict'; | ||
var _TransformFormat = require('../../transform/TransformFormat'); | ||
var _TransformFormat2 = _interopRequireDefault(_TransformFormat); | ||
var _ModuleReport = require('../../module/report/ModuleReport'); | ||
@@ -16,2 +20,6 @@ | ||
var _MathUtil = require('../../utils/MathUtil'); | ||
var _MathUtil2 = _interopRequireDefault(_MathUtil); | ||
var _StringUtil = require('../../utils/StringUtil'); | ||
@@ -27,2 +35,6 @@ | ||
* Provides the default project report object which stores data pertaining to all modules / files contained. | ||
* | ||
* All module / file reports are stored in the `reports` member variable as ModuleReports. | ||
* | ||
* Various helper methods found in ModuleReport and AbstractReport help increment associated data during collection. | ||
*/ | ||
@@ -40,4 +52,5 @@ | ||
function ProjectResult(moduleReports) { | ||
var settings = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | ||
function ProjectResult() { | ||
var moduleReports = arguments.length <= 0 || arguments[0] === undefined ? void 0 : arguments[0]; | ||
var settings = arguments.length <= 1 || arguments[1] === undefined ? { serializeReports: true } : arguments[1]; | ||
@@ -50,3 +63,3 @@ _classCallCheck(this, ProjectResult); | ||
*/ | ||
this.settings = (typeof settings === 'undefined' ? 'undefined' : _typeof(settings)) === 'object' ? settings : {}; | ||
this.settings = (typeof settings === 'undefined' ? 'undefined' : _typeof(settings)) === 'object' ? settings : { serializeReports: true }; | ||
@@ -135,2 +148,5 @@ /** | ||
* | ||
* @param {boolean} serializeReports - (Optional) Allows overriding of ModuleReport serialization; | ||
* default: undefined. | ||
* | ||
* @returns {ProjectResult} | ||
@@ -143,16 +159,54 @@ */ | ||
value: function finalize() { | ||
if (typeof this.settings.serializeReports === 'boolean' && !this.settings.serializeReports) { | ||
var serializeReports = arguments.length <= 0 || arguments[0] === undefined ? void 0 : arguments[0]; | ||
var serialize = this.getSetting('serializeReports'); | ||
// Allow an override opportunity. | ||
if (typeof serializeReports === 'boolean') { | ||
serialize = serializeReports; | ||
} | ||
if (serialize) { | ||
this.reports.forEach(function (report) { | ||
report.finalize(); | ||
}); | ||
} else { | ||
this.reports = this.reports.map(function (report) { | ||
return { filePath: report.filePath, srcPath: report.srcPath, srcPathAlias: report.srcPathAlias }; | ||
}); | ||
} else { | ||
this.reports.forEach(function (report) { | ||
report.finalize(); | ||
}); | ||
} | ||
return this; | ||
return _MathUtil2.default.toFixedTraverse(this); | ||
} | ||
/** | ||
* Returns the supported format file extension types. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
}, { | ||
key: 'getSetting', | ||
/** | ||
* Returns the setting indexed by the given key. | ||
* | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} defaultValue - A default value to return if no setting for the given key is currently stored. | ||
* | ||
* @returns {*} | ||
*/ | ||
value: function getSetting(key) { | ||
var defaultValue = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1]; | ||
/* istanbul ignore if */ | ||
if (typeof key !== 'string' || key === '') { | ||
throw new TypeError('getSetting error: \'key\' is not a \'string\' or is empty.'); | ||
} | ||
return _typeof(this.settings) === 'object' && typeof this.settings[key] !== 'undefined' ? this.settings[key] : defaultValue; | ||
} | ||
/** | ||
* Deserializes a JSON object representing a ProjectResult. | ||
@@ -166,38 +220,34 @@ * | ||
}, { | ||
key: 'toStringAdjacency', | ||
key: 'setSetting', | ||
/** | ||
* Returns a string representing the adjacency relationships by printing out the report index followed by | ||
* dependent ModuleReport indices / `srcPaths`. | ||
* Sets the setting indexed by the given key and returns true if successful. | ||
* | ||
* @returns {string} | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} value - A value to set to `this.settings[key]`. | ||
* | ||
* @returns {boolean} | ||
*/ | ||
value: function toStringAdjacency() { | ||
var _this = this; | ||
var result = ''; | ||
value: function setSetting(key, value) { | ||
/* istanbul ignore if */ | ||
if (!Array.isArray(this.adjacencyList)) { | ||
return result; | ||
if (typeof key !== 'string' || key === '') { | ||
throw new TypeError('setSetting error: \'key\' is not a \'string\' or is empty.'); | ||
} | ||
this.reports.forEach(function (report, index) { | ||
result += index + ':\t' + report.srcPath + '\n'; | ||
if (this.settings === 'object') { | ||
this.settings[key] = value; | ||
return true; | ||
} | ||
_this.adjacencyList[index].forEach(function (reportIndex) { | ||
result += '\t' + reportIndex + ':\t' + _this.reports[reportIndex].srcPath + '\n'; | ||
}); | ||
result += '\n'; | ||
}); | ||
return result; | ||
return false; | ||
} | ||
/** | ||
* Returns a string representing the visibilty relationships by printing out the report index followed by | ||
* indirect reverse dependency ModuleReport indices / `srcPaths`. | ||
* Formats this ProjectResult given the type. | ||
* | ||
* @param {string} name - The name of formatter to use. | ||
* | ||
* @param {object} options - (Optional) One or more optional parameters to pass to the formatter. | ||
* | ||
* @returns {string} | ||
@@ -207,26 +257,38 @@ */ | ||
}, { | ||
key: 'toStringVisibility', | ||
value: function toStringVisibility() { | ||
var _this2 = this; | ||
key: 'toFormat', | ||
value: function toFormat(name) { | ||
var options = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1]; | ||
var result = ''; | ||
return _TransformFormat2.default.format(this, name, options); | ||
} | ||
}], [{ | ||
key: 'getFormatFileExtensions', | ||
value: function getFormatFileExtensions() { | ||
return _TransformFormat2.default.getFileExtensions(); | ||
} | ||
/* istanbul ignore if */ | ||
if (!Array.isArray(this.visibilityList)) { | ||
return result; | ||
} | ||
/** | ||
* Returns the supported format names. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
this.reports.forEach(function (report, index) { | ||
result += index + ':\t' + report.srcPath + '\n'; | ||
}, { | ||
key: 'getFormatNames', | ||
value: function getFormatNames() { | ||
return _TransformFormat2.default.getNames(); | ||
} | ||
_this2.visibilityList[index].forEach(function (reportIndex) { | ||
result += '\t' + reportIndex + ':\t' + _this2.reports[reportIndex].srcPath + '\n'; | ||
}); | ||
/** | ||
* Returns the supported format types. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
result += '\n'; | ||
}); | ||
return result; | ||
}, { | ||
key: 'getFormatTypes', | ||
value: function getFormatTypes() { | ||
return _TransformFormat2.default.getTypes(); | ||
} | ||
}], [{ | ||
}, { | ||
key: 'parse', | ||
@@ -236,3 +298,3 @@ value: function parse(object) { | ||
if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') { | ||
throw new TypeError('parse error: `object` is not an `object`.'); | ||
throw new TypeError('parse error: \'object\' is not an \'object\'.'); | ||
} | ||
@@ -239,0 +301,0 @@ |
@@ -1,2 +0,2 @@ | ||
"use strict"; | ||
'use strict'; | ||
@@ -9,2 +9,8 @@ Object.defineProperty(exports, "__esModule", { | ||
var _ObjectUtil = require('./ObjectUtil'); | ||
var _ObjectUtil2 = _interopRequireDefault(_ObjectUtil); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
@@ -22,7 +28,9 @@ | ||
_createClass(MathUtil, null, [{ | ||
key: "compactMatrix", | ||
key: 'compactMatrix', | ||
/** | ||
* Compacts a 2D matrix testing entries against a testValue with a default value of `1` for inclusion. The resulting | ||
* compacted list has an array per row with entries that correspond to the column index that passed the test. | ||
* compacted array only has object hash entries for rows that contain column entries that pass the test. Each entry | ||
* has a `row` entry as a number corresponding to a row index and a `cols` entry which is an array of numbers | ||
* representing all column indexes that pass the test. This works well for large sparse matrices. | ||
* | ||
@@ -32,3 +40,3 @@ * @param {Array<Array<number>>} matrix - A matrix to compact / compress. | ||
* | ||
* @returns {Array<Array<number>>} | ||
* @returns {Array<{row: number, cols: Array<number>}>} | ||
*/ | ||
@@ -40,11 +48,14 @@ value: function compactMatrix(matrix) { | ||
matrix.forEach(function (row) { | ||
var rowArray = []; | ||
compacted.push(rowArray); | ||
matrix.forEach(function (rowEntry, row) { | ||
var cols = []; | ||
row.forEach(function (entry, entryIndex) { | ||
if (entry === testValue) { | ||
rowArray.push(entryIndex); | ||
rowEntry.forEach(function (colEntry, colIndex) { | ||
if (colEntry === testValue) { | ||
cols.push(colIndex); | ||
} | ||
}); | ||
if (cols.length > 0) { | ||
compacted.push({ row: row, cols: cols }); | ||
} | ||
}); | ||
@@ -65,3 +76,3 @@ | ||
}, { | ||
key: "create2DArray", | ||
key: 'create2DArray', | ||
value: function create2DArray() { | ||
@@ -96,3 +107,3 @@ var length = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; | ||
}, { | ||
key: "getMedian", | ||
key: 'getMedian', | ||
value: function getMedian(values) { | ||
@@ -122,6 +133,37 @@ // Sort by number. | ||
}, { | ||
key: "getPercent", | ||
key: 'getPercent', | ||
value: function getPercent(value, limit) { | ||
return limit === 0 ? 0 : value / limit * 100; | ||
} | ||
/** | ||
* Performs a naive depth traversal of an object / array. The data structure _must not_ have circular references. | ||
* The result of the `toFixed` method is invoked for each leaf or array entry modifying any floating point number | ||
* in place. | ||
* | ||
* @param {object} data - An object or array. | ||
* | ||
* @returns {*} | ||
*/ | ||
}, { | ||
key: 'toFixedTraverse', | ||
value: function toFixedTraverse(data) { | ||
return _ObjectUtil2.default.depthTraverse(data, MathUtil.toFixed); | ||
} | ||
/** | ||
* Converts floating point numbers to a fixed decimal length of 3. This saves space and avoids precision | ||
* issues with serializing / deserializing. | ||
* | ||
* @param {*} val - Any value; only floats are processed. | ||
* | ||
* @returns {*} | ||
*/ | ||
}, { | ||
key: 'toFixed', | ||
value: function toFixed(val) { | ||
return typeof val === 'number' && !Number.isInteger(val) ? Math.round(val * 1000) / 1000 : val; | ||
} | ||
}]); | ||
@@ -133,2 +175,2 @@ | ||
exports.default = MathUtil; | ||
module.exports = exports["default"]; | ||
module.exports = exports['default']; |
@@ -1,9 +0,21 @@ | ||
"use strict"; | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
value: true | ||
}); | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; | ||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
var _templateObject = _taggedTemplateLiteral(['', '', '', '', ''], ['', '', '', '', '']); | ||
var _ObjectUtil = require('./ObjectUtil'); | ||
var _ObjectUtil2 = _interopRequireDefault(_ObjectUtil); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
@@ -16,26 +28,226 @@ | ||
var StringUtil = function () { | ||
function StringUtil() { | ||
_classCallCheck(this, StringUtil); | ||
} | ||
function StringUtil() { | ||
_classCallCheck(this, StringUtil); | ||
} | ||
_createClass(StringUtil, null, [{ | ||
key: "compare", | ||
_createClass(StringUtil, null, [{ | ||
key: 'compare', | ||
/** | ||
* Compares two strings. | ||
* | ||
* @param {string} lhs - Left-hand side. | ||
* @param {string} rhs - Right-hand side. | ||
* | ||
* @returns {number} | ||
*/ | ||
value: function compare(lhs, rhs) { | ||
return lhs.toLowerCase().localeCompare(rhs.toLowerCase()); | ||
} | ||
}]); | ||
/** | ||
* Compares two strings. | ||
* | ||
* @param {string} lhs - Left-hand side. | ||
* @param {string} rhs - Right-hand side. | ||
* | ||
* @returns {number} | ||
*/ | ||
value: function compare(lhs, rhs) { | ||
return lhs.toLowerCase().localeCompare(rhs.toLowerCase()); | ||
} | ||
return StringUtil; | ||
/** | ||
* Increments the indentation amount. | ||
* | ||
* @param {number} indentation - Current indentation amount. | ||
* @param {number} amount - (Optional) indentation amount; default: 3. | ||
* | ||
* @returns {number} | ||
*/ | ||
}, { | ||
key: 'incrementIndent', | ||
value: function incrementIndent(indentation) { | ||
var amount = arguments.length <= 1 || arguments[1] === undefined ? 3 : arguments[1]; | ||
return indentation + amount; | ||
} | ||
/** | ||
* Creates an indentation string given the indentation amount. | ||
* | ||
* @param {number} indentation - Current indentation amount. | ||
* @param {string} string - A string to append. | ||
* | ||
* @returns {string} | ||
*/ | ||
}, { | ||
key: 'indent', | ||
value: function indent(indentation) { | ||
var string = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1]; | ||
return new Array(indentation + 1).join(' ') + string; | ||
} | ||
/** | ||
* Provides a way to output a given string value with concatenated data from safely accessing an objects data / | ||
* entries given an accessor string which describes the entries to walk. To access deeper entries into the object | ||
* format the accessor string with `.` between entries to walk. | ||
* | ||
* @param {string} string - A string to prepend to the object data received. | ||
* @param {object} object - An object to access entry data. | ||
* @param {string} accessor - A string describing the entries to access. | ||
* @param {number} newLine - (Optional) A number of new line characters to append; default: `1`. | ||
* @param {string} appendString - (Optional) A string to potentially append; default: `''`; | ||
* @param {function} tagFunction - (Optional) A template tag function to apply; default: `void 0`; | ||
* | ||
* @returns {string} | ||
*/ | ||
}, { | ||
key: 'safeStringObject', | ||
value: function safeStringObject(string, object, accessor) { | ||
var newLine = arguments.length <= 3 || arguments[3] === undefined ? 1 : arguments[3]; | ||
var appendString = arguments.length <= 4 || arguments[4] === undefined ? '' : arguments[4]; | ||
var tagFunction = arguments.length <= 5 || arguments[5] === undefined ? void 0 : arguments[5]; | ||
var value = _ObjectUtil2.default.safeAccess(object, accessor); | ||
if (typeof value === 'undefined') { | ||
return ''; | ||
} | ||
var end = '\n'; | ||
// Create the ending new line result if it is not the default of `1`. | ||
if (newLine === 0 || newLine > 1) { | ||
end = new Array(newLine + 1).join('\n'); | ||
} | ||
return typeof tagFunction === 'function' ? tagFunction(_templateObject, string, value, appendString, end) : '' + string + value + appendString + end; | ||
} | ||
/** | ||
* Provides a convenience method producing a block of safeStringObject results. | ||
* | ||
* @param {object} object - An object to access entry data. | ||
* | ||
* @param {string|Array<string|number|function>} entries - | ||
* Multiple arrays or strings. If the entry is not an array it will simply | ||
* be appended. If the entry is an array then entries in this array correspond | ||
* to the following parameters which are forwarded onto `safeStringObject`. | ||
* The indexes correspond to the following: | ||
* ``` | ||
* [0] (string) - The string to prepend. | ||
* [1] (string) - The accessor string describing the lookup operation. | ||
* [2] (number) - (Optional) The number of newlines characters to append. | ||
* [3] (string) - (Optional) A string to append to the end. | ||
* [4] (function) - (Optional) A template tag function to apply. | ||
* ``` | ||
* | ||
* @returns {string} | ||
*/ | ||
}, { | ||
key: 'safeStringsObject', | ||
value: function safeStringsObject(object) { | ||
for (var _len = arguments.length, entries = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
entries[_key - 1] = arguments[_key]; | ||
} | ||
return StringUtil.safeStringsPrependObject.apply(StringUtil, ['', object].concat(entries)); | ||
} | ||
/** | ||
* Provides a convenience method producing a block of safeStringObject results with the option to prepend a | ||
* given string. | ||
* | ||
* @param {*} origPrepend - An additional value to prepend to all results. | ||
* | ||
* @param {object} object - An object to access entry data. | ||
* | ||
* @param {string|Array<string|number|function>} entries - | ||
* Multiple arrays or strings. If the entry is not an array it will simply | ||
* be appended. If the entry is an array then entries in this array correspond | ||
* to the following parameters which are forwarded onto `safeStringObject`. | ||
* The indexes correspond to the following: | ||
* ``` | ||
* [0] (string) - The string to prepend. | ||
* [1] (string) - The accessor string describing the lookup operation. | ||
* [2] (number) - (Optional) The number of newlines characters to append. | ||
* [3] (string) - (Optional) A string to append to the end. | ||
* [4] (function) - (Optional) A template tag function to apply. | ||
* ``` | ||
* | ||
* @returns {string} | ||
*/ | ||
}, { | ||
key: 'safeStringsPrependObject', | ||
value: function safeStringsPrependObject(origPrepend, object) { | ||
if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') { | ||
return ''; | ||
} | ||
var output = []; | ||
var skipPrepend = false; | ||
for (var _len2 = arguments.length, entries = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { | ||
entries[_key2 - 2] = arguments[_key2]; | ||
} | ||
for (var cntr = 0; cntr < entries.length; cntr++) { | ||
var entry = entries[cntr]; | ||
// Skip prepend action if last entry did not include a new line. | ||
var prepend = skipPrepend ? '' : origPrepend; | ||
skipPrepend = Array.isArray(entry) && typeof entry[2] === 'number' && entry[2] === 0; | ||
// Process an array entry otherwise simply append `entry` to output if it is a string. | ||
if (Array.isArray(entry)) { | ||
switch (entry.length) { | ||
case 2: | ||
output.push(StringUtil.safeStringObject('' + prepend + entry[0], object, entry[1])); | ||
break; | ||
case 3: | ||
output.push(StringUtil.safeStringObject('' + prepend + entry[0], object, entry[1], entry[2])); | ||
break; | ||
case 4: | ||
output.push(StringUtil.safeStringObject('' + prepend + entry[0], object, entry[1], entry[2], entry[3])); | ||
break; | ||
case 5: | ||
output.push(StringUtil.safeStringObject('' + prepend + entry[0], object, entry[1], entry[2], entry[3], entry[4])); | ||
break; | ||
default: | ||
throw new Error('safeStringsPrependObject error: entry at \'' + cntr + '\' has the wrong length \'' + entry.length + '\'.'); | ||
} | ||
} else if (typeof entry === 'string' && entry !== '') { | ||
output.push('' + prepend + entry); | ||
} | ||
} | ||
return output.join(''); | ||
} | ||
/** | ||
* Provides a tagged template method to escape HTML elements. | ||
* | ||
* @param {Array<string>} literal - Literal components of template string. | ||
* @param {Array<*>} values - Values to substitute. | ||
* | ||
* @returns {string} | ||
*/ | ||
}, { | ||
key: 'tagEscapeHTML', | ||
value: function tagEscapeHTML(literal) { | ||
for (var _len3 = arguments.length, values = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { | ||
values[_key3 - 1] = arguments[_key3]; | ||
} | ||
return values.reduce(function (previous, value, index) { | ||
return previous + String(value).replace('<', '<').replace('>', '>') + literal[index + 1]; | ||
}, literal[0]); | ||
} | ||
}]); | ||
return StringUtil; | ||
}(); | ||
exports.default = StringUtil; | ||
module.exports = exports["default"]; | ||
module.exports = exports['default']; |
{ | ||
"name": "typhonjs-escomplex-commons", | ||
"version": "0.0.8", | ||
"version": "0.0.9", | ||
"homepage": "https://github.com/typhonjs-node-escomplex/typhonjs-escomplex-commons/", | ||
@@ -23,2 +23,3 @@ "description": "Provides core common utilities for typhonjs-escomplex modules and plugins.", | ||
"typhonjs-config-eslint": "^0.4.0", | ||
"typhonjs-escomplex-test-data": "git+https://git@github.com/typhonjs-node-escomplex/typhonjs-escomplex-test-data.git", | ||
"typhonjs-npm-build-test": "^0.3.0" | ||
@@ -25,0 +26,0 @@ }, |
@@ -5,3 +5,5 @@ import AbstractReport from './AbstractReport'; | ||
/** | ||
* Provides a class report. | ||
* Provides the class report object which stores data pertaining to a single ES6 class. | ||
* | ||
* Methods that are stored as MethodReports in the `methods` member variable. | ||
*/ | ||
@@ -61,3 +63,3 @@ export default class ClassReport extends AbstractReport | ||
this.methods.forEach((report) => { report.finalize(); }); | ||
this.methods.forEach((methodReport) => { methodReport.finalize(); }); | ||
@@ -77,16 +79,16 @@ return this; | ||
/* istanbul ignore if */ | ||
if (typeof object !== 'object') { throw new TypeError('parse error: `object` is not an `object`.'); } | ||
if (typeof object !== 'object') { throw new TypeError(`parse error: 'object' is not an 'object'.`); } | ||
const report = Object.assign(new ClassReport(), object); | ||
const classReport = Object.assign(new ClassReport(), object); | ||
// Must explicitly assign `aggregate` to `report._methodReport` and re-assign data. | ||
report.aggregate = Object.assign(report._methodReport, object.aggregate); | ||
// Must explicitly assign `aggregate` to `classReport._methodReport` and re-assign data. | ||
classReport.aggregate = Object.assign(classReport._methodReport, object.aggregate); | ||
if (report.methods.length > 0) | ||
if (classReport.methods.length > 0) | ||
{ | ||
report.methods = report.methods.map((report) => { return MethodReport.parse(report); }); | ||
classReport.methods = classReport.methods.map((methodReport) => { return MethodReport.parse(methodReport); }); | ||
} | ||
return report; | ||
return classReport; | ||
} | ||
} |
@@ -5,3 +5,5 @@ import AbstractReport from './AbstractReport'; | ||
/** | ||
* Provides a method report. | ||
* Provides the method report object which stores data pertaining to a single method / function. | ||
* | ||
* | ||
*/ | ||
@@ -103,3 +105,3 @@ export default class MethodReport extends AbstractReport | ||
/* istanbul ignore if */ | ||
if (typeof object !== 'object') { throw new TypeError('parse error: `object` is not an `object`.'); } | ||
if (typeof object !== 'object') { throw new TypeError(`parse error: 'object' is not an 'object'.`); } | ||
@@ -106,0 +108,0 @@ return Object.assign(new MethodReport(), object); |
@@ -5,4 +5,12 @@ import AbstractReport from './AbstractReport'; | ||
import MathUtil from '../../utils/MathUtil'; | ||
import TransformFormat from '../../transform/TransformFormat'; | ||
/** | ||
* Provides the default report object which stores data pertaining to a single file / module being processed. | ||
* Provides the module report object which stores data pertaining to a single file / module being processed. | ||
* | ||
* All ES Module classes are stored in the `classes` member variable as ClassReports. Methods that are not part of a | ||
* class are stored as MethodReports in the `methods` member variable. | ||
* | ||
* Various helper methods found in ModuleReport and AbstractReport help increment associated data during collection. | ||
*/ | ||
@@ -20,3 +28,3 @@ export default class ModuleReport extends AbstractReport | ||
*/ | ||
constructor(lineStart, lineEnd, settings = {}) | ||
constructor(lineStart = 0, lineEnd = 0, settings = {}) | ||
{ | ||
@@ -215,3 +223,3 @@ super(new MethodReport('', lineStart, lineEnd, 0)); | ||
return this; | ||
return MathUtil.toFixedTraverse(this); | ||
} | ||
@@ -240,2 +248,32 @@ | ||
/** | ||
* Returns the supported format file extension types. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
static getFormatFileExtensions() | ||
{ | ||
return TransformFormat.getFileExtensions(); | ||
} | ||
/** | ||
* Returns the supported format names. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
static getFormatNames() | ||
{ | ||
return TransformFormat.getNames(); | ||
} | ||
/** | ||
* Returns the supported format types. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
static getFormatTypes() | ||
{ | ||
return TransformFormat.getTypes(); | ||
} | ||
/** | ||
* Provides a default array and indices for summing maintainability metrics via `sumMetrics`. | ||
@@ -251,2 +289,22 @@ * | ||
/** | ||
* Returns the setting indexed by the given key. | ||
* | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} defaultValue - A default value to return if no setting for the given key is currently stored. | ||
* | ||
* @returns {*} | ||
*/ | ||
getSetting(key, defaultValue = undefined) | ||
{ | ||
/* istanbul ignore if */ | ||
if (typeof key !== 'string' || key === '') | ||
{ | ||
throw new TypeError(`getSetting error: 'key' is not a 'string' or is empty.`); | ||
} | ||
return typeof this.settings === 'object' && typeof this.settings[key] !== 'undefined' ? this.settings[key] : | ||
defaultValue; | ||
} | ||
/** | ||
* Increments the Halstead `metric` for the given `identifier` for the ModuleReport and any current class or method | ||
@@ -313,3 +371,3 @@ * report being tracked. | ||
/* istanbul ignore if */ | ||
if (typeof object !== 'object') { throw new TypeError('parse error: `object` is not an `object`.'); } | ||
if (typeof object !== 'object') { throw new TypeError(`parse error: 'object' is not an 'object'.`); } | ||
@@ -323,3 +381,3 @@ const report = Object.assign(new ModuleReport(), object); | ||
{ | ||
report.classes = report.classes.map((report) => { return ClassReport.parse(report); }); | ||
report.classes = report.classes.map((classReport) => { return ClassReport.parse(classReport); }); | ||
} | ||
@@ -329,3 +387,3 @@ | ||
{ | ||
report.methods = report.methods.map((report) => { return MethodReport.parse(report); }); | ||
report.methods = report.methods.map((methodReport) => { return MethodReport.parse(methodReport); }); | ||
} | ||
@@ -362,3 +420,3 @@ | ||
* | ||
* @param {ModuleReport} metric - The Halstead metric being processed. | ||
* @param {string} metric - The Halstead metric being processed. | ||
* @param {Array<string>} identifiers - An array of Halstead identifiers. | ||
@@ -375,2 +433,27 @@ */ | ||
/** | ||
* Sets the setting indexed by the given key and returns true if successful. | ||
* | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} value - A value to set to `this.settings[key]`. | ||
* | ||
* @returns {boolean} | ||
*/ | ||
setSetting(key, value) | ||
{ | ||
/* istanbul ignore if */ | ||
if (typeof key !== 'string' || key === '') | ||
{ | ||
throw new TypeError(`setSetting error: 'key' is not a 'string' or is empty.`); | ||
} | ||
if (this.settings === 'object') | ||
{ | ||
this.settings[key] = value; | ||
return true; | ||
} | ||
return false; | ||
} | ||
/** | ||
* Provides a convenience method to increment metric sums given an object hash of indices. | ||
@@ -391,2 +474,16 @@ * | ||
} | ||
/** | ||
* Formats this ModuleReport given the type. | ||
* | ||
* @param {string} name - The name of formatter to use. | ||
* | ||
* @param {object} options - (Optional) One or more optional parameters to pass to the formatter. | ||
* | ||
* @returns {string} | ||
*/ | ||
toFormat(name, options = undefined) | ||
{ | ||
return TransformFormat.format(this, name, options); | ||
} | ||
} | ||
@@ -393,0 +490,0 @@ |
import TraitHalstead from './TraitHalstead'; | ||
/** | ||
* Provides a wrapper around an array of Halstead properties object hashes which should contain an | ||
* Provides a wrapper around an array of Halstead property object hashes which should contain an | ||
* `identifier` field and potentially a `filter` field. | ||
@@ -6,0 +6,0 @@ */ |
@@ -106,8 +106,13 @@ /** | ||
{ | ||
return typeof entry === 'function' ? entry(...params) : entry; | ||
const value = typeof entry === 'function' ? entry(...params) : entry; | ||
return typeof value === 'number' ? value.toString() : value; | ||
}); | ||
} | ||
return typeof this._data.identifier === 'function' ? this._data.identifier(...params) : this._data.identifier; | ||
const value = typeof this._data.identifier === 'function' ? this._data.identifier(...params) : | ||
this._data.identifier; | ||
return typeof value === 'number' ? value.toString() : value; | ||
} | ||
} |
@@ -1,6 +0,13 @@ | ||
import ModuleReport from '../../module/report/ModuleReport'; | ||
import StringUtil from '../../utils/StringUtil'; | ||
import TransformFormat from '../../transform/TransformFormat'; | ||
import ModuleReport from '../../module/report/ModuleReport'; | ||
import MathUtil from '../../utils/MathUtil'; | ||
import StringUtil from '../../utils/StringUtil'; | ||
/** | ||
* Provides the default project report object which stores data pertaining to all modules / files contained. | ||
* | ||
* All module / file reports are stored in the `reports` member variable as ModuleReports. | ||
* | ||
* Various helper methods found in ModuleReport and AbstractReport help increment associated data during collection. | ||
*/ | ||
@@ -17,3 +24,3 @@ export default class ProjectResult | ||
*/ | ||
constructor(moduleReports, settings = {}) | ||
constructor(moduleReports = void 0, settings = { serializeReports: true }) | ||
{ | ||
@@ -24,3 +31,3 @@ /** | ||
*/ | ||
this.settings = typeof settings === 'object' ? settings : {}; | ||
this.settings = typeof settings === 'object' ? settings : { serializeReports: true }; | ||
@@ -108,8 +115,20 @@ /** | ||
* | ||
* @param {boolean} serializeReports - (Optional) Allows overriding of ModuleReport serialization; | ||
* default: undefined. | ||
* | ||
* @returns {ProjectResult} | ||
*/ | ||
finalize() | ||
finalize(serializeReports = void 0) | ||
{ | ||
if (typeof this.settings.serializeReports === 'boolean' && !this.settings.serializeReports) | ||
let serialize = this.getSetting('serializeReports'); | ||
// Allow an override opportunity. | ||
if (typeof serializeReports === 'boolean') { serialize = serializeReports; } | ||
if (serialize) | ||
{ | ||
this.reports.forEach((report) => { report.finalize(); }); | ||
} | ||
else | ||
{ | ||
this.reports = this.reports.map((report) => | ||
@@ -120,8 +139,54 @@ { | ||
} | ||
else | ||
return MathUtil.toFixedTraverse(this); | ||
} | ||
/** | ||
* Returns the supported format file extension types. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
static getFormatFileExtensions() | ||
{ | ||
return TransformFormat.getFileExtensions(); | ||
} | ||
/** | ||
* Returns the supported format names. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
static getFormatNames() | ||
{ | ||
return TransformFormat.getNames(); | ||
} | ||
/** | ||
* Returns the supported format types. | ||
* | ||
* @returns {string[]} | ||
*/ | ||
static getFormatTypes() | ||
{ | ||
return TransformFormat.getTypes(); | ||
} | ||
/** | ||
* Returns the setting indexed by the given key. | ||
* | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} defaultValue - A default value to return if no setting for the given key is currently stored. | ||
* | ||
* @returns {*} | ||
*/ | ||
getSetting(key, defaultValue = undefined) | ||
{ | ||
/* istanbul ignore if */ | ||
if (typeof key !== 'string' || key === '') | ||
{ | ||
this.reports.forEach((report) => { report.finalize(); }); | ||
throw new TypeError(`getSetting error: 'key' is not a 'string' or is empty.`); | ||
} | ||
return this; | ||
return typeof this.settings === 'object' && typeof this.settings[key] !== 'undefined' ? this.settings[key] : | ||
defaultValue; | ||
} | ||
@@ -139,3 +204,3 @@ | ||
/* istanbul ignore if */ | ||
if (typeof object !== 'object') { throw new TypeError('parse error: `object` is not an `object`.'); } | ||
if (typeof object !== 'object') { throw new TypeError(`parse error: 'object' is not an 'object'.`); } | ||
@@ -153,56 +218,39 @@ const result = Object.assign(new ProjectResult(), object); | ||
/** | ||
* Returns a string representing the adjacency relationships by printing out the report index followed by | ||
* dependent ModuleReport indices / `srcPaths`. | ||
* Sets the setting indexed by the given key and returns true if successful. | ||
* | ||
* @returns {string} | ||
* @param {string} key - A key used to store the setting parameter. | ||
* @param {*} value - A value to set to `this.settings[key]`. | ||
* | ||
* @returns {boolean} | ||
*/ | ||
toStringAdjacency() | ||
setSetting(key, value) | ||
{ | ||
let result = ''; | ||
/* istanbul ignore if */ | ||
if (!Array.isArray(this.adjacencyList)) { return result; } | ||
if (typeof key !== 'string' || key === '') | ||
{ | ||
throw new TypeError(`setSetting error: 'key' is not a 'string' or is empty.`); | ||
} | ||
this.reports.forEach((report, index) => | ||
if (this.settings === 'object') | ||
{ | ||
result += `${index}:\t${report.srcPath}\n`; | ||
this.settings[key] = value; | ||
return true; | ||
} | ||
this.adjacencyList[index].forEach((reportIndex) => | ||
{ | ||
result += `\t${reportIndex}:\t${this.reports[reportIndex].srcPath}\n`; | ||
}); | ||
result += '\n'; | ||
}); | ||
return result; | ||
return false; | ||
} | ||
/** | ||
* Returns a string representing the visibilty relationships by printing out the report index followed by | ||
* indirect reverse dependency ModuleReport indices / `srcPaths`. | ||
* Formats this ProjectResult given the type. | ||
* | ||
* @param {string} name - The name of formatter to use. | ||
* | ||
* @param {object} options - (Optional) One or more optional parameters to pass to the formatter. | ||
* | ||
* @returns {string} | ||
*/ | ||
toStringVisibility() | ||
toFormat(name, options = undefined) | ||
{ | ||
let result = ''; | ||
/* istanbul ignore if */ | ||
if (!Array.isArray(this.visibilityList)) { return result; } | ||
this.reports.forEach((report, index) => | ||
{ | ||
result += `${index}:\t${report.srcPath}\n`; | ||
this.visibilityList[index].forEach((reportIndex) => | ||
{ | ||
result += `\t${reportIndex}:\t${this.reports[reportIndex].srcPath}\n`; | ||
}); | ||
result += '\n'; | ||
}); | ||
return result; | ||
return TransformFormat.format(this, name, options); | ||
} | ||
} |
@@ -0,1 +1,3 @@ | ||
import ObjectUtil from './ObjectUtil'; | ||
/** | ||
@@ -8,3 +10,5 @@ * Provides common math utilities. | ||
* Compacts a 2D matrix testing entries against a testValue with a default value of `1` for inclusion. The resulting | ||
* compacted list has an array per row with entries that correspond to the column index that passed the test. | ||
* compacted array only has object hash entries for rows that contain column entries that pass the test. Each entry | ||
* has a `row` entry as a number corresponding to a row index and a `cols` entry which is an array of numbers | ||
* representing all column indexes that pass the test. This works well for large sparse matrices. | ||
* | ||
@@ -14,3 +18,3 @@ * @param {Array<Array<number>>} matrix - A matrix to compact / compress. | ||
* | ||
* @returns {Array<Array<number>>} | ||
* @returns {Array<{row: number, cols: Array<number>}>} | ||
*/ | ||
@@ -21,8 +25,9 @@ static compactMatrix(matrix, testValue = 1) | ||
matrix.forEach((row) => | ||
matrix.forEach((rowEntry, row) => | ||
{ | ||
const rowArray = []; | ||
compacted.push(rowArray); | ||
const cols = []; | ||
row.forEach((entry, entryIndex) => { if (entry === testValue) { rowArray.push(entryIndex); } }); | ||
rowEntry.forEach((colEntry, colIndex) => { if (colEntry === testValue) { cols.push(colIndex); } }); | ||
if (cols.length > 0) { compacted.push({ row, cols }); } | ||
}); | ||
@@ -86,2 +91,29 @@ | ||
} | ||
} | ||
/** | ||
* Performs a naive depth traversal of an object / array. The data structure _must not_ have circular references. | ||
* The result of the `toFixed` method is invoked for each leaf or array entry modifying any floating point number | ||
* in place. | ||
* | ||
* @param {object} data - An object or array. | ||
* | ||
* @returns {*} | ||
*/ | ||
static toFixedTraverse(data) | ||
{ | ||
return ObjectUtil.depthTraverse(data, MathUtil.toFixed); | ||
} | ||
/** | ||
* Converts floating point numbers to a fixed decimal length of 3. This saves space and avoids precision | ||
* issues with serializing / deserializing. | ||
* | ||
* @param {*} val - Any value; only floats are processed. | ||
* | ||
* @returns {*} | ||
*/ | ||
static toFixed(val) | ||
{ | ||
return typeof val === 'number' && !Number.isInteger(val) ? Math.round(val * 1000) / 1000 : val; | ||
} | ||
} |
@@ -0,1 +1,3 @@ | ||
import ObjectUtil from './ObjectUtil'; | ||
/** | ||
@@ -18,2 +20,174 @@ * Provides common string utilities. | ||
} | ||
/** | ||
* Increments the indentation amount. | ||
* | ||
* @param {number} indentation - Current indentation amount. | ||
* @param {number} amount - (Optional) indentation amount; default: 3. | ||
* | ||
* @returns {number} | ||
*/ | ||
static incrementIndent(indentation, amount = 3) | ||
{ | ||
return indentation + amount; | ||
} | ||
/** | ||
* Creates an indentation string given the indentation amount. | ||
* | ||
* @param {number} indentation - Current indentation amount. | ||
* @param {string} string - A string to append. | ||
* | ||
* @returns {string} | ||
*/ | ||
static indent(indentation, string = '') | ||
{ | ||
return (new Array(indentation + 1)).join(' ') + string; | ||
} | ||
/** | ||
* Provides a way to output a given string value with concatenated data from safely accessing an objects data / | ||
* entries given an accessor string which describes the entries to walk. To access deeper entries into the object | ||
* format the accessor string with `.` between entries to walk. | ||
* | ||
* @param {string} string - A string to prepend to the object data received. | ||
* @param {object} object - An object to access entry data. | ||
* @param {string} accessor - A string describing the entries to access. | ||
* @param {number} newLine - (Optional) A number of new line characters to append; default: `1`. | ||
* @param {string} appendString - (Optional) A string to potentially append; default: `''`; | ||
* @param {function} tagFunction - (Optional) A template tag function to apply; default: `void 0`; | ||
* | ||
* @returns {string} | ||
*/ | ||
static safeStringObject(string, object, accessor, newLine = 1, appendString = '', tagFunction = void 0) | ||
{ | ||
const value = ObjectUtil.safeAccess(object, accessor); | ||
if (typeof value === 'undefined') { return ''; } | ||
let end = '\n'; | ||
// Create the ending new line result if it is not the default of `1`. | ||
if (newLine === 0 || newLine > 1) { end = new Array(newLine + 1).join('\n'); } | ||
return typeof tagFunction === 'function' ? tagFunction`${string}${value}${appendString}${end}` : | ||
`${string}${value}${appendString}${end}`; | ||
} | ||
/** | ||
* Provides a convenience method producing a block of safeStringObject results. | ||
* | ||
* @param {object} object - An object to access entry data. | ||
* | ||
* @param {string|Array<string|number|function>} entries - | ||
* Multiple arrays or strings. If the entry is not an array it will simply | ||
* be appended. If the entry is an array then entries in this array correspond | ||
* to the following parameters which are forwarded onto `safeStringObject`. | ||
* The indexes correspond to the following: | ||
* ``` | ||
* [0] (string) - The string to prepend. | ||
* [1] (string) - The accessor string describing the lookup operation. | ||
* [2] (number) - (Optional) The number of newlines characters to append. | ||
* [3] (string) - (Optional) A string to append to the end. | ||
* [4] (function) - (Optional) A template tag function to apply. | ||
* ``` | ||
* | ||
* @returns {string} | ||
*/ | ||
static safeStringsObject(object, ...entries) | ||
{ | ||
return StringUtil.safeStringsPrependObject('', object, ...entries); | ||
} | ||
/** | ||
* Provides a convenience method producing a block of safeStringObject results with the option to prepend a | ||
* given string. | ||
* | ||
* @param {*} origPrepend - An additional value to prepend to all results. | ||
* | ||
* @param {object} object - An object to access entry data. | ||
* | ||
* @param {string|Array<string|number|function>} entries - | ||
* Multiple arrays or strings. If the entry is not an array it will simply | ||
* be appended. If the entry is an array then entries in this array correspond | ||
* to the following parameters which are forwarded onto `safeStringObject`. | ||
* The indexes correspond to the following: | ||
* ``` | ||
* [0] (string) - The string to prepend. | ||
* [1] (string) - The accessor string describing the lookup operation. | ||
* [2] (number) - (Optional) The number of newlines characters to append. | ||
* [3] (string) - (Optional) A string to append to the end. | ||
* [4] (function) - (Optional) A template tag function to apply. | ||
* ``` | ||
* | ||
* @returns {string} | ||
*/ | ||
static safeStringsPrependObject(origPrepend, object, ...entries) | ||
{ | ||
if (typeof object !== 'object') { return ''; } | ||
const output = []; | ||
let skipPrepend = false; | ||
for (let cntr = 0; cntr < entries.length; cntr++) | ||
{ | ||
const entry = entries[cntr]; | ||
// Skip prepend action if last entry did not include a new line. | ||
const prepend = skipPrepend ? '' : origPrepend; | ||
skipPrepend = Array.isArray(entry) && typeof entry[2] === 'number' && entry[2] === 0; | ||
// Process an array entry otherwise simply append `entry` to output if it is a string. | ||
if (Array.isArray(entry)) | ||
{ | ||
switch (entry.length) | ||
{ | ||
case 2: | ||
output.push(StringUtil.safeStringObject(`${prepend}${entry[0]}`, object, entry[1])); | ||
break; | ||
case 3: | ||
output.push(StringUtil.safeStringObject(`${prepend}${entry[0]}`, object, entry[1], entry[2])); | ||
break; | ||
case 4: | ||
output.push( | ||
StringUtil.safeStringObject(`${prepend}${entry[0]}`, object, entry[1], entry[2], entry[3])); | ||
break; | ||
case 5: | ||
output.push(StringUtil.safeStringObject(`${prepend}${entry[0]}`, | ||
object, entry[1], entry[2], entry[3], entry[4])); | ||
break; | ||
default: | ||
throw new Error( | ||
`safeStringsPrependObject error: entry at '${cntr}' has the wrong length '${entry.length}'.`); | ||
} | ||
} | ||
else if (typeof entry === 'string' && entry !== '') | ||
{ | ||
output.push(`${prepend}${entry}`); | ||
} | ||
} | ||
return output.join(''); | ||
} | ||
/** | ||
* Provides a tagged template method to escape HTML elements. | ||
* | ||
* @param {Array<string>} literal - Literal components of template string. | ||
* @param {Array<*>} values - Values to substitute. | ||
* | ||
* @returns {string} | ||
*/ | ||
static tagEscapeHTML(literal, ...values) | ||
{ | ||
return values.reduce((previous, value, index) => | ||
{ | ||
return previous + String(value).replace('<', '<').replace('>', '>') + literal[index + 1]; | ||
}, literal[0]); | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
339413
71
7724
3