UNPKG

@railrunner16/raildash

Version:

Lodash, but better

2,106 lines (2,017 loc) 55 kB
/** * @method assign * @description A polyfill for `Object.assign` * * @memberof Object * * @see {@link https://u.rr16.tk/l/cSZTj16} */ if (typeof Object.assign != 'function') Object.assign = function (target, varArgs) { if (target == null) throw new TypeError('Cannot convert undefined or null to object'); var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource != null) for (var nextKey in nextSource) if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) to[nextKey] = nextSource[nextKey]; } return to; }; /** * @method reduce * @description A polyfill for `Array.prototype.reduce` * * @memberof Array# * * @see {@link https://u.rr16.tk/l/aG7UjJu} */ if (!Array.prototype.reduce) Array.prototype.reduce = function (callback) { if (this === null) throw new TypeError('Array.prototype.reduce called on null or undefined'); if (typeof callback !== 'function') throw new TypeError(callback + " is not a function"); var o = Object(this), len = o.length >>> 0, k = 0, value; if (arguments.length >= 2) value = arguments[1]; else { while (k < len && !(k in o)) k++; if (k >= len) throw new TypeError('Reduce of empty array with no initial value'); value = o[k++]; } while (k < len) { if (k in o) value = callback(value, o[k], k, o); k++; } return value; }; /** * @method quadraticFormula * @description Calculate the quadratic formula * * @param {Number} a The first coefficient * @param {Number} b The second coefficient * @param {Number} c The third coefficient * @returns {Number} The result * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Math# * @public */ var quadraticFormula = (function (a, b, c) { return ((-b) - Math.sqrt(Math.pow(b, 2) + 4 * a * c)) / (2 * a); }); /** * @method degreesToRadians * @description Convert degrees to radians * * @param {Number} degrees The amount of degrees to convert to radians * @returns {Number} The converted amount of radians * * @since 0.0.2 * @version 0.1.0 * * @memberof _.Math# * @public */ var degreesToRadians = (function (degrees) { return degrees * Math.PI / 180; }); /** * @method radiansToDegrees * @description Convert radians to degrees * * @param {Number} radians The amount of radians to convert to degrees * @returns {Number} The converted amount of degrees * * @since 0.0.2 * @version 0.1.0 * * @memberof _.Math# * @public */ var radiansToDegrees = (function (radians) { return radians * 180 / Math.PI; }); /** * @method isMultipleOf * @description Check if `n1` is a multiple of `n2` * * @param {Number} n1 The possible multiple of `n2` * @param {Number} n2 The number to check for a possible multiple * @returns {Boolean} Whether or not `n1` is a multiple of `n2` * * @since 1.0.2 * @version 0.1.0 * * @memberof _.Math# * @public */ var isMultipleOf = (function (n1, n2) { return n1 % n2 === 0; }); /** * @method isNegative * @description Check if a numerical value is negative * * @param {Number} num The number to check * @returns {Boolean} Whether or not the number is negative * * @since 0.0.2 * @version 0.1.0 * * @memberof _.Math# * @public */ var isNegative = (function (num) { return -(Math.abs(num)) == num; }); /** * @method average * @description Find the average of an array of numbers * * @param {Array} nums The numbers to average * @returns {Number} The average of all the numbers * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Math# * @public */ var average = (function (nums) { var finalNum = 0; for (var _i = 0, nums_1 = nums; _i < nums_1.length; _i++) { var num = nums_1[_i]; finalNum += num; } return finalNum / nums.length; }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } /** * @class MathError * @description An error in mathematics * * @extends Error * * @since 0.0.1 * @version 0.1.1 * * @private */ var MathError = /** @class */ (function (_super) { __extends(MathError, _super); function MathError() { var message = []; for (var _i = 0; _i < arguments.length; _i++) { message[_i] = arguments[_i]; } var _this = _super.apply(this, message) || this; _this.name = 'MathError'; Error.captureStackTrace(_this, MathError); return _this; } return MathError; }(Error)); /** * @method random * @description Generate a random number between two values * * @param {Number} min The minimum number if `max` is given, if not, the maximum number * @param {Number} max The maximum number * @returns {Number} The randomly generated number * @throws MathError * * @since 0.0.4 * @version 0.1.1 * * @memberof _.Math# * @pubic */ var random = (function (min, max) { if (max === void 0) { max = null; } if (!isFinite(min)) throw new MathError('`min` must be finite!'); if (max == null) { max = min; min = 0; } else { if (!isFinite(max)) throw new MathError('`max` must be finite!'); } return min + Math.floor(Math.random() * (max - min + 1)); }); /** * @method isEven * @description Check whether `n` is even * * @param {Number} n The number to check * @returns {Boolean} Whether or not `n` is even * * @since 0.1.0 * @version 0.1.0 * * @memberof _.Math# * @public * * @example * _.Math.isEven(1); * // => false * @example * _.Math.isEven(2); * // => true */ var isEven = (function (n) { return n % 2 == 0; }); /** * @method isOdd * @description Check whether `n` is odd * * @param {Number} n The number to check * @returns {Boolean} Whether or not `n` is odd * * @since 0.1.0 * @version 0.1.0 * * @memberof _.Math# * @public * * @example * _.Math.isOdd(1); * // => true * @example * _.Math.isOdd(2); * // => false */ var isOdd = (function (n) { return Math.abs(n % 2) == 1; }); /** * @method mult * @description Multiply an array of numbers * * @param {Array} nums The array of numbers to multiply * @returns {Number} The product of all the numbers * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Math# * @public */ var mult = (function (nums) { var finalNum = nums[0]; for (var i = 1; i < nums.length; i++) { finalNum *= nums[i]; } return finalNum; }); /** * @method add * @description Add an array of numbers together * * @param {Array} nums The array of numbers to add together * @returns {Number} The sum of all the numbers * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Math# * @public */ var add = (function (nums) { var finalNum = 0; for (var i = 0; i < nums.length; i++) { finalNum += nums[i]; } return finalNum; }); /** * @method sq * @description Square a number * * @param {number} n The number to square * @returns {number} `n` squared * * @since 0.1.1 * @version 0.1.0 * * @memberof _.Math# * @public * * @todo Write examples * @todo Write unit tests */ var sq = (function (n) { return n * n; }); /** * @class Math * @description Math utilities * * @since 0.0.1 * @version 0.1.0 * * @memberof _ * @public */ var RailMath = /** @class */ (function () { function RailMath() { } RailMath.quadraticFormula = quadraticFormula; RailMath.degreesToRadians = degreesToRadians; RailMath.radiansToDegrees = radiansToDegrees; RailMath.isMultipleOf = isMultipleOf; RailMath.isNegative = isNegative; RailMath.average = average; RailMath.random = random; RailMath.isEven = isEven; RailMath.isOdd = isOdd; RailMath.mult = mult; RailMath.add = add; RailMath.sq = sq; return RailMath; }()); /** * @method isObjectLike * @description Check if a value is similar in structure to an object * * @param {*} value The value to check * @returns {Boolean} Whether or not the value is object-like * * @since 0.0.6 * @version 0.1.0 * * @memberof _.Type# * @public */ var isObjectLike = (function (value) { return !!value && typeof value == 'object'; }); /** * @method isUndefined * @description Check if a value is undefined * * @param {*} val The value to check * @returns {Boolean} Whether or not the value is undefined * * @since 0.0.6 * @version 0.1.0 * * @memberof _.Type# * @public */ var isUndefined = (function (val) { return val === void 0; }); /** * @function getTag * @description Get the object tag, e.g. `[object Object]`, for any symbol * * @param {*} obj The symbol to retrieve the tag for * @returns {String} The symbol's tag * * @since 0.0.3 * @version 0.1.0 * * @private */ var getTag = (function (obj) { return Object.prototype.toString.call(obj); }); /** * @method isFunction * @description Check if a value is a function * * @param {*} val The value to check * @returns {Boolean} Whether or not the value is a function * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Type# * @public */ var isFunction = (function (val) { return getTag(val) == '[object Function]'; }); /** * @function isBoolean * @description Check if a value is a boolean. * * @param {*} val - The value to check. * @returns {boolean} Whether or not the value is a boolean. * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Type# * @public * * @example * _.Type.isBoolean(false); * // => true * @example * _.Type.isBoolean('umm, no'); * // => false * @example * _Type.isBoolean(1 + 1 === 2); * // => true */ var isBoolean = (function (val) { return getTag(val) == '[object Boolean]'; }); /** * @method isNumber * @description Check if a value is a number * * @param {*} val The value to check * @returns {Boolean} Whether or not the value is a number * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Type# * @public */ var isNumber = (function (val) { return getTag(val) == '[object Number]'; }); /** * @method isObject * @description Check if a value is an object * * @param {*} val The value to check * @returns {Boolean} Whether or not the value is an object * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Type# * @public */ var isObject = (function (val) { return getTag(val) == '[object Object]'; }); /** * @method isString * @description Check if a value is a string * * @param {*} val The value to check * @returns {Boolean} Whether or not the value is a string * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Type# * @public */ var isString = (function (val) { return getTag(val) == '[object String]'; }); /** * @function isArray * @description Check if a value is an array. * * @param {*} val - The value to check. * @returns {boolean} Whether or not the value is an array. * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Type# * @public * * @example * _.Type.isArray([]); * // => true * @example * _.Type.isArray('heck no'); * // => false */ var isArray = (function (val) { return getTag(val) == '[object Array]'; }); /** * @method isNaN * @description Check if a value is explicitly equal to NaN * * @param {*} val The value to check * @returns {Boolean} Whether or not the value is explicitly `NaN` * * @since 0.0.6 * @version 0.1.0 * * @memberof _.Type# * @public */ var isNaN$1 = (function (val) { return isNumber(val) && isNaN(val); }); /** * @class Type * @description Type utilities * * @since 0.0.1 * @version 0.1.0 * * @memberof _ * @public */ var Type = /** @class */ (function () { function Type() { } Type.isObjectLike = isObjectLike; Type.isUndefined = isUndefined; Type.isFunction = isFunction; Type.isBoolean = isBoolean; Type.isNumber = isNumber; Type.isObject = isObject; Type.isString = isString; Type.isArray = isArray; Type.isNaN = isNaN$1; return Type; }()); /** * Regex to validate a phone number * @type {RexExp} * * @since 0.0.7 * @version 0.1.0 * * @see {@link http://refiddle.com/o12f} * * @private */ var phoneNumber = /^(\+?( |-|\.)?\d{1,2}( |-|\.)?)?(\(?\d{3}\)?|\d{3})( |-|\.)?(\d{3}( |-|\.)?\d{4})$/gi; /** * Regex to validate an email address * @type {RexExp} * * @since 0.0.7 * @version 0.1.0 * * @see {@link http://refiddle.com/o12g} * * @private */ var email = /^([a-zA-Z0-9_\-.]+)@([a-zA-Z0-9_\-.]+)\.([a-zA-Z]{2,5})$/gi; /** * Regex to validate a CSS color * @type {RexExp} * * @since 0.0.7 * @version 0.1.0 * * @see {@link http://refiddle.com/o12h} * * @private */ var cssColor = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d.]+%?\))$/gi; /** * Regex to camelCase a string * @type {RexExp} * * @since 0.0.8 * @version 0.1.0 * * @todo Put on refiddle * * @private */ var camelCase = /^([A-Z])|[\s-_]+(\w)/gi; /** * Regex to find newlines * @type {RexExp} * * @since 0.1.2 * @version 0.1.0 * * @private */ var newLine = /\r\n?|\n/gi; /** * @method validatePhoneNumber * @description Validate a possible phone number * * @param {String} str The possible phone number to validate * @returns {Boolean} Whether or not the string is a valid phone number * * @since 0.0.7 * @version 0.1.0 * * @memberof _.Validation# * @public */ var validatePhoneNumber = (function (str) { return phoneNumber.test(str); }); /** * @method validateCssColor * @description Validate a CSS color * * @param {String} str The CSS color string to be validated * @return {Boolean} Whether or not the input string is a CSS color * * @since 0.0.1 * @version 0.2.0 * * @memberof _.Validation# * @public */ var validateCssColor = (function (str) { return cssColor.test(str); }); /** * @method validateEmail * @description Validate a possible email * * @param {String} str The possible email to validate * @returns {Boolean} Whether or not the string is a valid email address * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Validation# * @public */ var validateEmail = (function (str) { return email.test(str); }); /** * @class Validation * @description Validation utilities * * @since 0.0.1 * @version 0.1.0 * * @memberof _ * @public */ var Validation = /** @class */ (function () { function Validation() { } Validation.validatePhoneNumber = validatePhoneNumber; Validation.validateCssColor = validateCssColor; Validation.validateEmail = validateEmail; return Validation; }()); /** * @see {@link https://github.com/component/pad} */ /** * Pad `str` to `len` with optional `c` char, * favoring the left when unbalanced. * * @param {String} str * @param {Number} len * @param {String} c=' ' * @returns {String} * * @since 0.1.3 * @version 0.1.0 * * @memberof _.String# * @public */ function pad(str, len, c) { if (c === void 0) { c = ' '; } if (str.length >= len) return str; len = len - str.length; var left = Array(Math.ceil(len / 2) + 1).join(c); var right = Array(Math.floor(len / 2) + 1).join(c); return left + str + right; } /** * Pad `str` left to `len` with optional `c` char. * * @param {String} str * @param {Number} len * @param {String} c=' ' * @returns {String} * * @since 0.1.3 * @version 0.1.0 * * @memberof _.String# * @public */ function padLeft(str, len, c) { if (c === void 0) { c = ' '; } if (str.length >= len) return str; return Array(len - str.length + 1).join(c) + str; } /** * Pad `str` right to `len` with optional `c` char. * * @param {String} str * @param {Number} len * @param {String} c=' ' * @returns {String} * * @since 0.1.3 * @version 0.1.0 * * @memberof _.String# * @public */ function padRight(str, len, c) { if (c === void 0) { c = ' '; } if (str.length >= len) return str; return str + Array(len - str.length + 1).join(c); } /** * @method makeString * @description Safely converts any value into a string * * @param {*} object The value to convert to a string * @returns {String} The conversion result * * @since 0.0.8 * @version 0.1.0 * * @memberof _.String# * @protected */ var makeString = (function (object) { if (object == null) return ''; return '' + object; }); /** * @method escapeRegexOps * @description Escape regex operations for use in a RegExp constructor * * @param {String} str The string to escape for regex use * @returns {String} the escaped version of `str` * * @since 0.0.8 * @version 0.1.0 * * @memberof _.String# * @public */ var escapeRegexOps = (function (str) { return makeString(str).replace(/[|\\{}()[\]^$+*?.]/gi, '\\$&'); }); /** * @method isAlphaNumeric * @description Check whether `str` only contains alphanumeric characters * * @param {String} str The string to check * @returns {Boolean} Whether or not `str` only contains alphanumeric characters * * @since 0.1.1 * @version 0.1.0 * * @memberof _.String# * @public * * @todo Write examples * @todo Write unit tests */ var isAlphaNumeric = (function (str) { return !/[^0-9a-z\xDF-\xFF]/.test(makeString(str).toLowerCase()); }); /** * @method toArray * @description Separates `str` into an array * * @param {String} str The string to separate into an array * @param {String|RegExp} sep='' The string to separate `str` by * @returns {Array} `str` separated by `sep` * * @since 0.1.2 * @version 0.1.0 * * @memberof _.String# * @public */ var toArray = (function (str, sep) { if (sep === void 0) { sep = ''; } return makeString(str).split(sep); }); /** * @method chars * @description Turn a string into an array of characters * * @param {String} str The string to split into characters * @returns {Array} The characters that make up `str` * * @since 0.0.8 * @version 0.1.1 * * @memberof _.String# * @public * * @example * _.String.chars('Hello!'); * // => ['H', 'e', 'l', 'l', 'o', '!'] */ var chars = (function (str) { return toArray(makeString(str)); }); /** * @method reverse * @description Reverse a string * * @param {String} str The string to reverse * @returns {String} The reverse of `str` * * @since 0.0.8 * @version 0.1.0 * * @memberof _.String# * @public * * @example * _.String.reverse('foobar'); * // => 'raboof' */ var reverse = (function (str) { return chars(str).reverse().join(''); }); /** * @method isPalindrome * @description Check if a string, when stripped of everything but letters and numbers, is a palindrome * * @param {String} str The string to check * @returns {Boolean} Whether or not the string is a palindrome * * @since 0.0.2 * @version 0.1.1 * * @memberof _.String# * @public */ var isPalindrome = (function (str) { return str == reverse(makeString(str)); }); var charset = 'abcdefghijklmnopqrstuvwxyz0123456789'.split(''); /** * @method randomString * @description Generate a random string. Good for generating strong passwords. DO _**NOT**_ USE THIS TO GENERATE UUIDs! * * @param {Number} len=7 The length of the random string. * @returns {String} The random string * * @since 0.0.1 * @version 0.1.0 * * @memberof _.String# * @public */ var randomString = (function (len) { if (len === void 0) { len = 7; } var chars = []; for (var i = 0; i < len; i++) { var char = charset[Math.floor(Math.random() * charset.length)]; switch (Math.floor(Math.random() * 2)) { case 0: char = char.toLowerCase(); break; case 1: char = char.toUpperCase(); break; default: throw new MathError('Math.random() failed.'); } chars.push(char); } return chars.join(''); }); /** * @method isUpperCase * @description Check if `str` is upper case * * @param {String} str The string to check * @returns {Boolean} Whether or not `str` is upper case * * @since 0.0.8 * @version 0.1.0 * * @memberof _.String# * @public */ var isUpperCase = (function (str) { str = makeString(str); return str === str.toUpperCase(); }); /** * @method upperFirst * @description Upper case the first letter of `str` * * @param {String} str The string to be uppercased * @returns {String} The uppercased string * * @since 0.0.1 * @version 0.1.0 * * @memberof _.String# * @public */ var upperFirst = (function (str) { return makeString(str).replace(/^\w/ig, function (c) { return c.toUpperCase(); }); }); /** * @method capitalize * @description Properly capitalize a string * * @param {String} str The string to capitalize * @returns {String} The capitalized string * * @since 0.0.1 * @version 0.1.0 * * @memberof _.String# * @public * * @example * _.String.titleCase('salutations, universe'); * // => 'Salutations, Universe' * @example * _.String.titleCase('SALUTATIONS, UNIVERSE'); * // => 'Salutations, Universe' */ var capitalize = (function (str) { return upperFirst(str.toLowerCase()); }); /** * @method lowerFirst * @description Lower case the first letter of `str` * * @param {String} str The string to be lowercased * @returns {String} The lowercased string * * @since 0.0.1 * @version 0.1.1 * * @memberof _.String# * @public */ var lowerFirst = (function (str) { return makeString(str).replace(/^\w/ig, function (c) { return c.toLowerCase(); }); }); /** * @method camelCase * @description Convert a string to camel case * * @param {String} str The string to camel case * @returns {String} The camel cased string * * @since 0.0.1 * @version 0.1.0 * * @memberof _.String# * @public * * @example * _.String.camelCase('clearly-kebab-case'); * // => 'clearlyKebabCase' * @example * _.String.camelCase('clearly_snake_case'); * // => 'clearlySnakeCase' * @example * _.String.camelCase('ClearlyPascalCase'); * // => 'clearlyPascalCase' * @example * _.String.camelCase('clearly human case'); * // => 'clearlyHumanCase' * @example * _.String.camelCase('Clearly Title Case'); * // => 'clearlyTitleCase' */ var camelCase$1 = (function (str) { return str.replace(camelCase, function (match, p1, p2) { if (p2) return p2.toUpperCase(); return p1.toLowerCase(); }); }); /** * @method pascalCase * @description Convert `str` to pascal case * * @param {String} str The string to convert * @returns {String} The pascal case representation of `str` * * @since 0.0.8 * @version 0.2.0 * * @memberof _.String# * @public * * @example * _.String.pascalCase('a'); * // => 'A' * @example * _.String.pascalCase('foo bar baz'); * // => 'FooBarBaz' * @example * _.String.pascalCase('foo_bar-baz'); * // => 'FooBarBaz' * @example * _.String.pascalCase('foo.bar.baz'); * // => 'FooBarBaz' * @example * _.String.pascalCase('foo/bar/baz'); * // => 'FooBarBaz' * @example * _.String.pascalCase('foo[bar)baz'); * // => 'FooBarBaz' */ var pascalCase = (function (str) { return upperFirst(camelCase$1(makeString(str))); }); /** * @method fromArray * @description Join an array into a string * * @param {Array} arr The array to join with `joinStr` * @param {String} joinStr The string to join `arr` with * @returns {String} `arr` joined into a string by `joinStr` * * @since 0.1.2 * @version 0.1.0 * * @memberof _.String# * @public */ var fromArray = (function (arr, joinStr) { if (joinStr === void 0) { joinStr = ''; } if (!isArray(arr)) throw new TypeError('Expected an array!'); return arr.join(joinStr); }); /** * @method kebabCase * @description Convert `str` to kebab case * * @param {String} str The string to convert to kebab case * @returns {String} The converted string * * @since 0.0.1 * @version 0.2.0 * * @memberof _.String# * @public */ var kebabCase = (function (str) { return str.replace(/([a-z][A-Z])/g, function (match) { return match.substr(0, 1) + '-' + match.substr(1, 1).toLowerCase(); }).toLowerCase().replace(/[^-a-z0-9]+/g, '-').replace(/^-+/, '').replace(/-+$/, '').replace(/-{2,}/, '-'); }); /** * @method snakeCase * @description Convert `str` to snake case * * @param {String} str The string to convert * @returns {String} The snake cased string * * @since 0.0.8 * @version 0.1.0 * * @memberof _.String# * @public */ var snakeCase = (function (str) { return str.trim().replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase(); }); /** * @method swapCase * @description Swap the cases on `str` * * @param {String} str The string to invert the capitalization of * @returns {String} `str` with inverse capitalization * * @since 0.0.8 * @version 0.1.1 * * @memberof _.String# * @public * * @example * _.String.swapCase('Salutations, uNIVERSE!'); * // => 'sALUTATIONS, Universe!' */ var swapCase = (function (str) { var letters = chars(str); var newLetters = []; for (var _i = 0, letters_1 = letters; _i < letters_1.length; _i++) { var letter = letters_1[_i]; newLetters.push(isUpperCase(letter) ? letter.toLowerCase() : letter.toUpperCase()); } return newLetters.join(''); }); /** * @method endsWith * @description Check to see if `str` ends with a specific substring * * @param {String} str The string to check for `suffix` * @param {String} suffix The suffix to check at the end of `str` * @returns {Boolean} Whether or not `str` ends with `suffix` * * @since 0.0.1 * @version 0.1.0 * * @memberof _.String# * @public */ var endsWith = (function (str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }); /** * @method truncate * @description Truncate `str` at the given char * * @param {String} str The string to truncate * @param {Number} [amt=150] The amount of chars to truncate after * @returns {String} The truncated string * * @since 0.0.1 * @version 0.1.0 * * @memberof _.String# * @public */ var truncate = (function (str, amt) { if (amt === void 0) { amt = 150; } str = makeString(str); return str.length > amt ? str.slice(0, amt) : str; }); /** * @method surround * @description Surround `str` on both sides with `wrapper` * * @param {String} str The string to surround with `wrapper` * @param {String} wrapper The string to surround `str` with * @returns {String} The surrounded string * * @since 0.0.8 * @version 0.1.0 * * @memberof _.String# * @public * * @example * _.String.surround('foo', 'ab'); * // => 'abfooab' */ var surround = (function (str, wrapper) { return [wrapper, str, wrapper].join(''); }); /** * @method isAlpha * @description Check whether `str` is strictly alphabetic * * @param {String} str The string to check * @returns {Boolean} whether `str` is strictly alphabetic * * @since 0.1.0 * @version 0.1.0 * * @memberof _.String# * @public * * @todo Write examples * @todo Write unit tests */ var isAlpha = (function (str) { return !/[^a-z\xDF-\xFF]|^$/.test(makeString(str).toLowerCase()); }); /** * @method isEmpty * @description Check whether a string is null, undefined, or has whitespace only * * @param {String} str The string to check * @returns {Boolean} Whether or not `str` is empty * * @since 0.1.1 * @version 0.1.0 * * @memberof _.String# * @public * * @todo Write examples * @todo Write unit tests */ var isEmpty = (function (str) { return str === null || str === undefined ? true : /^[\s\xa0]*$/.test(str); }); /** * @method slugify * @description Slugify a string * * @param {String} text The text to slugify * @returns {String} The slug of `text` * * @since 1.0.1 * @version 0.1.0 * * @memberof _.String# * @public * * @todo Write examples * @todo Write unit tests * * @see {@link https://u.rr16.tk/l/J3ANsIU} */ var slugify = (function (text) { return text.toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/&/g, '') // Replace & with empty .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, '') // Trim - from end of text .replace(/-$/, ''); // Remove last - }); /** * @method repeat * @description Repeat `str` a certain number of times * * @param {String} str='' The string to repeat * @param {Number} count=1 The amount of times to repeat the string * @returns {String} The repeated string * * @since 0.0.3 * @version 0.1.0 * * @memberof _.String# * @public * * @example * _.String.repeat('foo', 5); * // => 'foofoofoofoofoo' * @example * _.String.repeat('foo'); * // => 'foo' * @example * _.String.repeat('foo', 0); * // => '' */ var repeat = (function (str, count) { if (str === void 0) { str = ''; } if (count === void 0) { count = 1; } if (!isFinite(count)) throw new MathError('`count` must be a finite number!'); return Array(count >= 0 ? count + 1 : -1).join(str); }); var format = (function (format) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return format.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); }); /** * @method count * @description Count the number of times a substring appears in a string * * @param {String} string The string to traverse * @param {String|RegExp} target The value to search for * @param {Number} start=0 The index of the string to start counting at * @param {Number} [end=null] The index of the string to stop counting at * @returns {Number} The amount of times the target value appeared in the string * * @since 0.0.4 * @version 0.1.0 * * @memberof _.String# * @public */ var count = (function (string, target, start, end) { if (target === void 0) { target = ''; } if (start === void 0) { start = 0; } if (end === void 0) { end = null; } end = end === null ? string.length : end; var me = string.slice(start, end); if (getTag(target) == '[object RegExp]') { if (!target.global) { target = new RegExp(target.source, (target.ignoreCase ? 'i' : '') + (target.multiLine ? 'm' : '') + 'g'); } var count = 0; me.replace(target, function () { count++; }); return count; } return me.slice(start, end).split(target).length - 1; }); /** * @method lines * @description Split `str` on every newline * * @param {String} str The string to split * @returns {Array} The array of lines * * @since 0.0.9 * @version 0.1.1 * * @memberof _.String# * @public */ var lines = (function (str) { if (str == null) return []; return toArray(makeString(str), newLine); }); /** * @method strip * @description Strip characters from a string * * @param {String} str The string to strip characters from * @param {Array} chars=[' '] The characters to remove from `str` * * @since 0.1.1 * @version 0.1.1 * * @memberof _.String# * @public * * @todo Write examples */ var strip = (function (str, chars) { if (chars === void 0) { chars = [' ']; } str = makeString(str); for (var _i = 0, chars_1 = chars; _i < chars_1.length; _i++) { var item = chars_1[_i]; str = str.split(item).join(''); } return str; }); /** * @method join * @description Join `args` together * * @param {String} separator='' The string to join `args` with * @param {*} ...args The items to join with `separator` * @returns {String} `args` joined by `separator` * * @since 0.1.0 * @version 0.1.1 * * @memberof _.String# * @public */ var join = (function (separator) { if (separator === void 0) { separator = ''; } var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return args.join(makeString(separator)); }); /** * @method map * @description Iterate through all the chars in `str`, and perform the given callback with each char * * @param {String} str The string to iterate * @param {Function} callback The function to call on each char in `str` * @returns {String} The resulting string after iteration * * @since 0.0.8 * @version 0.1.0 * * @memberof _.String# * @public * * @example * _.String.map('Hello world', function(x) { * return x; * }); * // => 'Hello world' * @example * _.String.map(12345, function(x) { * return x; * }); * // => '12345' * @example * _.String.map('Hello world', function(x) { * if (x === 'o') x = 'O'; * return x; * }); * // => 'HellO wOrld' */ var map = (function (str, callback) { str = makeString(str); if (str.length === 0 || typeof callback !== 'function') return str; return str.replace(/./g, callback); }); /** * @class String * @description String utilities * * @since 0.0.1 * @version 0.1.0 * * @memberof _ * @public */ var RailString = /** @class */ (function () { function RailString() { } RailString.escapeRegexOps = escapeRegexOps; RailString.isAlphaNumeric = isAlphaNumeric; RailString.isPalindrome = isPalindrome; RailString.randomString = randomString; RailString.isUpperCase = isUpperCase; RailString.makeString = makeString; RailString.capitalize = capitalize; RailString.lowerFirst = lowerFirst; RailString.upperFirst = upperFirst; RailString.pascalCase = pascalCase; RailString.fromArray = fromArray; RailString.camelCase = camelCase$1; RailString.kebabCase = kebabCase; RailString.snakeCase = snakeCase; RailString.swapCase = swapCase; RailString.endsWith = endsWith; RailString.truncate = truncate; RailString.surround = surround; RailString.padRight = padRight; RailString.padLeft = padLeft; RailString.isAlpha = isAlpha; RailString.isEmpty = isEmpty; RailString.toArray = toArray; RailString.reverse = reverse; RailString.slugify = slugify; RailString.repeat = repeat; RailString.format = format; RailString.count = count; RailString.chars = chars; RailString.lines = lines; RailString.strip = strip; RailString.join = join; RailString.map = map; RailString.pad = pad; return RailString; }()); /** * @method isEmptyObject * @description Check if an object is empty * * @param {Object} obj The object to check * @returns {Boolean} Whether or not the object is empty * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Iter# * @public */ var isEmptyObject = (function (obj) { for (var name in obj) { return false; } return true; }); /** * @function has * @description Determine whether an object has a certain property * * @param {Object} obj The object to check for the given property * @param {String} path The property to check the object for * @returns {Boolean} Whether or not the object has the specified property * * @since 0.0.5 * @version 0.1.0 * * @private */ var has = (function (obj, path) { return obj != null && Object.prototype.hasOwnProperty.call(obj, path); }); /** * @method keys * @description Get an object's keys * * @param {Object} obj The object to extract keys from * @returns {Array} The object's keys * * @since 0.0.5 * @version 0.1.0 * * @memberof _.Iter# * @public */ var keys = (function (obj) { if (!isObject(obj)) return []; if (Object.keys) return Object.keys(obj); var keys = []; for (var key in obj) if (has(obj, key)) keys.push(key); return keys; }); var deepEqual = function (x, y) { var tx = typeof x, ty = typeof y; return x && y && tx === 'object' && tx === ty ? (keys(x).length === keys(y).length && keys(x).every(function (key) { return deepEqual(x[key], y[key]); })) : (x === y); }; /** * @method cloneObject * @description Clone an Object * * @param {Object} obj The object to clone * @returns {Object} The clone of the object * * @since 0.0.1 * @version 0.1.0 * * @memberof _.Iter# * @public */ var cloneObject = (function (obj) { return Object.assign({}, obj); }); var arraysEqual = (function (a, b) { if (a === b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; for (var i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; }); var filterOnly = (function (arr, toKeep) { var newArray = []; switch (getTag(toKeep)) { case '[object RegExp]': newArray = arr.filter(function (i) { return toKeep.test(i); }); break; default: newArray = arr.filter(function (i) { return i === toKeep; }); break; } return newArray; }); /** * @class ValueError * @description An error that occurs when an unexpected value is found * * @extends Error * * @since 0.0.7 * @version 0.1.0 * * @private */ var ValueError = /** @class */ (function (_super) { __extends(ValueError, _super); function ValueError() { var message = []; for (var _i = 0; _i < arguments.length; _i++) { message[_i] = arguments[_i]; } var _this = _super.apply(this, message) || this; _this.name = 'ValueError'; Error.captureStackTrace(_this, ValueError); return _this; } return ValueError; }(Error)); /** * @method filterOut * @description Filter unwanted values out of an array * * @param {Array} arr The array to filter values out of * @param {Array|String|RegExp} The value(s) to filter out of the array * @returns {Array} The filtered array * @throws ValueError * * @since 0.0.7 * @version 0.1.0 * * @memberof _.Iter# * @public */ var filterOut = (function (arr, toRemove) { switch (getTag(toRemove)) { case '[object Array]': var _loop_1 = function (item) { arr = arr.filter(function (i) { return i !== item; }); }; for (var _i = 0, toRemove_1 = toRemove; _i < toRemove_1.length; _i++) { var item = toRemove_1[_i]; _loop_1(item); } break; case '[object String]': arr = arr.filter(function (i) { return i !== toRemove; }); break; case '[object RegExp]': arr = arr.filter(function (i) { return !(toRemove.test(i.toString())); }); break; default: throw new ValueError('`toRemove` must be one of type: {Array|String|RegExp}'); } return arr; }); /** * @method invert * @description Invert an object, e.g.: * ```js * { * 'test1': 'yeet', * 'test2': 'skrt' * } * ``` * will become: * ```js * { * 'yeet': 'test1', * 'skrt': 'test2' * } * ``` * * @param {Object} obj The object to invert * @returns {Object} The inverted object * * @since 0.0.5 * @version 0.1.0 * * @memberof _.Iter# * @public */ var invert = (function (obj) { var result = {}; var keyList = keys(obj); for (var i = 0, length = keyList.length; i < length; i++) { result[obj[keyList[i]]] = keyList[i]; } return result; }); var range = (function (len) { if (!isNumber(len)) throw new TypeError('Expected a number.'); var range = new Array(len); for (var i = 0; i < len; i++) range[i] = ''; return range; }); /** * @method take * @description Retrieve a certain amount (`amt`) of elements from the beginning of `arr` * * @param {Array} arr=[] The array to retrieve items from * @param {Number} [amt=1] The amount of items to take from `arr` * @returns {Array} The items that were taken from `arr` * * @since 0.1.0 * @version 0.1.0 * * @memberof _.Iter# * @public * * @todo Write examples * @todo Write unit tests */ var take = (function (arr, amt) { if (amt === void 0) { amt = 1; } if (amt > arr.length) return arr; if (amt == 0 || arr.length == 0) return []; return arr.slice(0, amt); }); /** * @method chunk * @description Divide an array into chunks * * @param {Array<any>} arr The array to divide * @param {Number} chunk The size of chunks to divide the array into * @returns {Array<Array<any>>} The array of chunks * * @since 1.0.2 * @version 0.1.0 * * @memberof _.Iter# * @public * * @example * const arr = [1, 2, 3, 4, 5, 6]; * * _.Iter.chunk(arr, 2); * // => [[1, 2], [3, 4], [5, 6]] * _.Iter.chunk(arr, 4); * // => [[1, 2, 3, 4], [5, 6]] */ var chunk = (function (arr, chunk) { var res = []; var len = arr.length; var _len = Math.ceil(arr.length / chunk); var _chunk = 0; chunk = chunk > len ? len : chunk; for (var i = 0; i < _len; i++) { var _arr = []; if (i === _len - 1 && chunk > _len) for (var j = 0; j < (len - chunk); j++) _arr.push(arr[_chunk + j]); else for (var j = 0; j < chunk; j++) _arr.push(arr[_chunk + j]); _chunk = chunk + _chunk; res.push(_arr); } return res; }); /** * @class Iter * @description Utilities for iterables * * @since 0.0.1 * @version 0.1.0 * * @memberof _ * @public */ var Iter = /** @class */ (function () { function Iter() { } Iter.isEmptyObject = isEmptyObject; Iter.deepEquals = deepEqual; Iter.arraysEqual = arraysEqual; Iter.cloneObject = cloneObject; Iter.filterOnly = filterOnly; Iter.filterOut = filterOut; Iter.invert = invert; Iter.range = range; Iter.keys = keys; Iter.take = take; Iter.chunk = chunk; return Iter; }()); /** * An abstract person * * @abstract * * @since 0.0.1 * @version 0.1.0 * * @memberof _.abstracts * @public */ var Person = /** @class */ (function () { /** * Create a person * @param {String} firstName The person's first name * @param {String} lastName The person's last name * @param {Number} birthYear The person's birth year, e.g. `2003` * @param {Number} sex The person's sex, represented as a `0` for male, and a `1` for female */ function Person(firstName, lastName, birthYear, sex) { this.firstName = upperFirst(firstName.toLowerCase()); this.lastName = upperFirst(lastName.toLowerCase()); this._birthYear = birthYear; this._sex = sex === 0 ? 'Male' : 'Female'; } /** * The person's age in years * * @since 0.1.0 * @version 0.2.0 * * @memberof _.abstracts.Person# * @public */ Person.prototype.getAge = function () { var time = new Date(); var thisYear = time.getFullYear(); return thisYear - this._birthYear >= 0 ? thisYear - this._birthYear : 0; }; /** * The person's full name * * @since 0.1.0 * @version 0.2.0 * * @memberof _.abstracts.Person# * @public */ Person.prototype.getName = function () { return this.firstName + " " + this.lastName; }; return Person; }()); /** * @class Employee * @description An abstract employee * * @extends _.abstracts.Person * * @since 0.0.1 * @version 0.1.0 * * @memberof _.abstracts * @public */ var Employee = /** @class */ (function (_super) { __extends(Employee, _super); /** * @constructs Employee * * @param {String} firstName The employee's first name * @param {String} lastName The employee's last name * @param {Number} birthYear The employee's birth year, e.g. `2003` * @param {Number} sex The employee's sex, represented as a `0` for male, and a `1` for female * @param {String} jobTitle The employee's job title * @param {Boolean} manager=false Whether or not this employee is a manager * @param {Number} salary=14 The amount in dollars that the employee makes per hour * * @memberof _.abstracts.Employee */ function Employee(firstName, lastName, birthYear, sex, jobTitle, manager, salary) { if (manager === void 0) { manager = false; } if (salary === void 0) { salary = 14; } var _this = _super.call(this, firstName, lastName, birthYear, sex) || this; _this.isManager = manager; _this.job = upperFirst(jobTitle.toLowerCase()); _this.salary = salary; return _this; } /** * @method promotion * @description The employee gets a job promotion * * @param {String} newJob The new job title that the employee is promoted to * @param {Boolean} toManager=false Whether or not to promote this employee to a manager position * * @since 0.1.0 * * @memberof _.abstracts.Employee# * @public */ Employee.prototype.promotion = function (newJob, toManager) { if (toManager === void 0) { toManager = false; } if (toManager) this.isManager = true; this.job = upperFirst(newJob.toLowerCase()); this.salary += (0.2 * this.salary); }; /** * @method getRaise * @description Give this employee a raise * * @param {Number} amount The amount to raise the employee's salary by * @returns {Number} The employee's new salary * * @since 0.1.0 * * @memberof _.abstracts.Employee# * @public */ Employee.prototype.getRaise = function (amount) { this.salary += amount; return this.salary; }; return Employee; }(Person)); /** * @class VariableNotDefinedError * @description An error that is thrown when a variable needs to exist, but doesn't * * @extends Error * * @since 0.0.1 * @version 0.1.1 * * @private */ var VariableNotDefinedError = /** @class */ (function (_super) { __extends(VariableNotDefinedError, _super); function VariableNotDefinedError() { var message = []; for (var _i = 0; _i < arguments.length; _i++) { message[_i] = arguments[_i]; } var _this = _super.apply(this, message) || this; _this.name = 'VariableNotDefinedError'; Error.captureStackTrace(_this, VariableNotDefinedError); return _this; } return VariableNotDefinedError; }(Error)); /** * @class User * @description An abstract user * * @extends _.abstracts.Person * * @since 0.0.1 * @version 0.1.0 * * @memberof _.abstracts * @public */ var User = /** @class */ (function (_super) { __extends(User, _super); /** * @constructs User * * @param {String} firstName The user's first name * @param {String} lastName The user's last name * @param {Number} birthYear The user's birth year, e.g. `2003` * @param {Number} sex The user's sex, represented as a `0` for male, and a `1` for female * @param {String} email The user's email * @param {String} username The user's username * @param {String} [password] The user's password. If not specified, defaults to a 7 character long random string * @param {String} phone=null The user's phone number * * @memberof _.abstracts.User * @public */ function User(firstName, lastName, birthYear, sex, email, username, password, phone) { if (phone === void 0) { phone = null; } var _this = _super.call(this, firstName, lastName, birthYear, sex) || this; _this.email = validateEmail(email) ? email : null; _this.phone = phone; _this._password = password ? password : randomString(); _this.username = username; return _this; } /** * @method setUsername * @description Set this user's username * * @param {String} newUsername The new username to give the user * @returns {String} The user's new username * * @since 0.1.0 * * @memberof _.abstracts.User# * @public */ User.prototype.setUsername = function (newUsername) { if (!newUsername) throw new VariableNotDefinedError('You must supply a value for `newUsername`!'); this.username = newUsername; return this.username; }; return User; }(Person)); /** * @class abstracts * @description Abstract classes for use in any project * * @since 0.0.1 * @version 0.1.0 * * @memberof _ * @public */ var abstracts = { Employee: Employee, Person: Person, User: User }; /** * @method strToHex