UNPKG

@wider/utils_proto

Version:

A set of extensions to basic objects giving uniform behaviour in various technical environments

71 lines (59 loc) 2.29 kB
'use strict'; const $moduleName = "@wider/utils_proto/proto_number"; /** * Provide extensions to the javascript **Number** prototype * @module @wider/utils_proto/proto_number * * @copyright Copyright (C) 1985..2021 Martin Baker. http://y-d-r.co.uk * @author Martin W Baker * @license ISC Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ const numberPrototypes = { /** * always give the n (default 2 hence its chosen name) digits before the decimal place of a number - padding with 0 at left if need be * * if number is ***NaN*** then this returns ***aN*** * @returns {string} * @function two() */ wider_two: function(digits) { return ("0".repeat(digits || 2) + parseInt(this)).slice(digits || -2); }, /** * * fills all the bits lower than the most significant bit with 1's * * eg given any value 8 to 15 returns 15 since 2^3 is the most significant bit 100 in binary and so we have binary(1111) = 15 as all the bits * * used predominantly in bit implication logics with masks * @function bitsUpTo() * @returns {BigInteger} */ wider_bitsUpTo: function() { let ref = parseInt(this); var result = 0; while (!isNaN(ref) && ref) { ref >>>= 1; result = result << 1 | 1; } return result; } }; /** * @private * @param {object} target - this will normally be the javascript Function object - but if you dont want to change that object then provide your own equivalent */ function assignNumber(target = Number) { /* set the prototype of the javascript Function object or if it already exists then extend it */ if (target.prototype) Object.assign(target.prototype, numberPrototypes); else target.prototype = numberPrototypes; return numberPrototypes; } assignNumber.$moduleName = $moduleName; if (global.$wider) global.$wider.registry.register($moduleName, assignNumber, "protoNumber", "utils"); export default assignNumber;