@yamato-daiwa/es-extensions
TypeScript icon, indicating that this package has built-in type declarations

1.6.11 • Public • Published

Yamato Daiwa ES Extensions 〔YDEE〕

No any type No dependencies NPM Version IntelliJ IDEA plugin

Helper functions and classes aimed to reduce the routine code. Build-in TypeScript type safety without any type. Oriented to TypeScript users investing the time to quality including type-safety.

Hero image of @yamato-daiwa/es-extensions

Installation

npm i @yamato-daiwa/es-extensions -E

Notice about "Unpacked size" (displaying in npmjs.com)

The displaying "Unpacked size" (for example, 633 kB for version 1.4.5 as in image below) is the total size of all built CommonJS and ECMAScript modules.

image

ECMAScript modules are preferred for the browser JavaScript while CommonJS - for Node.js.

For the websites and web applications where each kilobyte on count it is possible to automatically exclude the unused functionality of @yamato-daiwa/es-extensions (and possibly other dependencies) from built JavaScript. The JavaScript bundlers like Webpack can exclude the unused functionality under certain conditions. For the TypeScript and Webpack combination case, it is required to use ECMAScript modules to activate the tree shaking functionality (works on production mode).

Documentation

Get functionality

All available functionality could be imported from @yamato-daiwa/es-extensions:

export { isUndefined, isNull } from "@yamato-daiwa/es-extensions";

Functionality reference

RawObjectDataProcessor

The tool for the validation and processing of unknown at advance external data (from HTTP requests/responses, files, etc.).

Pre-made pre-validation modifiers

Intended to be used when some property is expected to be the string but also expected to be a valid number if to parse it.

convertPotentialStringToFloatIfPossible
Tries to convert the string to decimal fraction; returns the number in success case otherwise returns the initial value.
convertPotentialStringToIntegerIfPossible
Tries to convert the string to integer; returns the number in success case otherwise returns the initial value.
convertPotentialStringToNumberIfPossible
Tries to convert the string to integer or decimal fraction (depending on decimal part separator presence); returns the number in success case otherwise returns the initial value.

Numbers

formatNumberWith4KetaKanji
Formats number with 4-digits Kanji 万, 億, 兆, 系 (CJK ideographic characters)
getArithmeticMean
Computed the arithmetic mean of arbitrary quantity of number.
isStringifiedNonNegativeIntegerOfRegularNotation
Checks is the value of string contains the number of non-scientific notation.
roundDownToSpecificIntegerPlaceValue
Rounds up the number to specific nearest integer place value.
roundToSpecificNearestIntegerPlaceValue
Rounds the number to specific nearest integer place value.
roundToSpecifiedNearestDecimalPlaceValue
Rounds the number to specific decimal place (tens, hundreds, thousands, etc.).
roundUpToSpecificIntegerPlaceValue
Rounds the number to specific nearest integer place value.
separateEach3DigitsGroupWithComma
Formats the number separating each 3 digits group with comma
separateEach4DigitsGroupWithComma
Formats the number separating each 4 digits group with comma

Strings

All functions working with strings are supporting the surrogate pairs. If some function works incorrectly with surrogate pairs, it means the bug; please feel free to open issue in this case.

areStringifiedDigitsOnly
Checks is string value consists exclusively from the digits.
capitalizeFirstCharacter
Capitalizes first character of target string value.
EmailAddress
Class working with email addresses. Currently, consists from validating function and regular expression of valid emails.
explodeCasedPhraseToWords
Explodes the string containing grammatically normal or cased (camel case, snake case, etc.) expression to words and returns the array of them. Currently, 26 latin characters of English alphabet are supported.
getLastCharacter
Returns the last character of target string value.
getPositionsOfAllSubstringOccurrences
Returns the positions of each occurrence of specified substring.
hasStringOnlySpecificCharacters
Checks does string including specified characters only without regular expression
removeAllSpecifiedCharacters
Removes specified characters from the string value.
removeLastCharacter
Removes last character.
removeNonDigitsCharacters
Removes all characters from the string except digits.
removeNthCharacter
Removes the character in specified position from the string. Supports the surrogate pairs.
removeSpecificCharacterFromCertainPosition
Removes specific character from the specific position.
replace2OrMoreSpacesTo1
Replaces 2 or more spaces to 1.
replaceBrHTML_TagToNewLineEscapeSequence
Replaces the "br" HTML tag to new line (line feed) escape sequence.
insertSubstring
Insets nullable substring with optional condition and transformations.
insertSubstringIf
Insets substring conditionally.
isIPv4AddressLiesInRange
Check does specified IP address lies in specific range.
reverseString
Reverses the characters sequence in string value.
splitString
Alternative of native String.prototype.split(); unlike it supports the UTF16 surrogate pairs.
stringifyAndFormatArbitraryValue
Converts to readable string and formats if possible any type of data.
replaceDoubleBackslashesWithForwardSlashes
Replaces double backslashes with forward slashes.
toLowerCamelCase
Converts the string containing grammatically normal or cased (camel case, snake case, etc.) expression to (lower) camel case. Currently, 26 latin characters of English alphabet are supported.
toScreamingSnakeCase
Converts the string containing grammatically normal or cased (camel case, snake case, etc.) expression to screaming snake case. Currently, 26 latin characters of English alphabet are supported.
toUpperCamelCase
Converts the string containing grammatically normal or cased (camel case, snake case, etc.) expression to upper camel case AKA Pascal case. Currently, 26 latin characters of English alphabet are supported.
trimSpaces
Trims prepended and/or appended space characters; unlike native String.prototype.trim() acts selectively on specified spaces kinds.

Objects

getObjectPropertySafely
Works as optional chaining but could be used for any fully-qualified name and returns value which being considered as unknown. Intended to be used when the schema of value is not known enough (for example, because of lack of TypeScript type definition).

Arrays

Retrieving of elements
getArrayElementSatisfiesThePredicateIfSuchElementIsExactlyOne
Returns the element of specified array matching with the predicate if such element is exactly one, otherwise error will be thrown or null will be returned depending on dedicated option's value.
getLastElementOfArray
Returns the last element of array, herewith depending on dedicated parameter either UnexpectedEventError will be thrown of null will be returned if target array is empty.
Retrieving of indexes
getIndexesOfArrayElementsWhichSatisfiesThePredicate
Returns the array of indexes of array elements which are satisfies to predicate function.
getIndexOfArrayElementSatisfiesThePredicateIfSuchElementIsExactlyOne
Returns the index of array element satisfies the predicate if such element is exactly one, otherwise error will be thrown or null will be returned depending on dedicated option's value.
Replacing of elements
replaceArrayElementsByIndexesImmutably
Creates the copy of target array and replaces the elements by specified indexes.
replaceArrayElementsByPredicates
Replaces array elements by one or more predicates, herewith the replacing could be mutable or not depending on dedicated option.
Adding of elements
addElementsToArray
Adds one or more elements to the start, end or specified position of target array, herewith the adding could be mutable or not depending on dedicated property of named parameters object.
Removing of elements
removeArrayElementsByIndexes
Removes array elements by indexes, herewith the removing could be mutable or not depending on dedicated option.
removeArrayElementsByPredicates
Removes array elements by one or more predicates, herewith the removing could be mutable or not depending on dedicated option.
Other
twoDimensionalizeArray
Converts flat array to 2-dimensional array with nested arrays of fixed elements count.

Sets

addMultipleElementsToSet
Adds multiple elements to set.

Maps

addMultiplePairsToMap
Adds multiple entries to map.
createMapBasedOnOtherMap
Creates map based on other map.
filterMap
Filters map by specified predicate.

Date and Time

getDaysCountInSpecificMonth
Returns days count in specified year and month.
getMonthNameByNumber
Converts the month number (from 0 or 1) to element of MonthsNames enumeration.
getMonthNumberByName
Converts the element of MonthsNames enumeration to number of month (from 0 or 1).
getNextMonthNumber
Returns next month number in relation to specified year and month number; numeration from 0 and 1 is available for both parameter and returned value.
getPreviousMonthNumber
Returns previous month number in relation to specified year and month number; numeration from 0 and 1 is available for both parameter and returned value.
getYearOfNextMonth
Returns the year of next month in relation to specified year and month.
getYearOfPreviousMonth
Returns the year of previous month in relation to specified year and month.
millisecondsToSeconds
Converts milliseconds amount to amount of seconds.
secondsToMilliseconds
Converts seconds amount to amount of milliseconds.
TimePoint
The alternative to native Date allows to build the formatted date/time strings easily.

Types

ParsedJSON and related
The native object including the Array case which could be the result of JSON parsing.
InheritEnumerationKeys
Allows to create the object with same keys as reference enumeration.
PartialBy
Makes specified properties of base type optional.

Type guards

Default value subsituters

The nullish coalescing operator makes below functions redundant, but they still could be used in the environments with old ECMAScript versions.

substituteWhenNull
Substitutes the second argument's value when first one is null.
substituteWhenUndefined
Substitutes the second argument's value when first one is undefined.

Value transformers

  • emptyStringToNull
  • nullToEmptyString
  • nullToUndefined
  • nullToZero
  • undefinedToEmptyArray
  • undefinedToEmptyString
  • undefinedToNull

Random values generators

getRandomArrayElement
Returns the random element of specified array.
getRandomBoolean
Returns "true" or "false" randomly.
getRandomInteger
Returns random integer not less than specified **minimalValue** and more than **maximalValue**.
getRandomLatinCharacter
Returns random latin character.
getRandomObjectPropertyValue
Returns random object property value.
getRandomSubarray
Returns the selection of elements of specified array; minimal and maximal elements count could be specified.
getSpecificBooleanValueWithProbability
Returns specific boolean value with specified probability.

Constants and enumerations

Date and time
CHARACTERS_COUNT_OF_DATE_PART_IN_ISO8601_STRING
The character count represents the date without time in ISO8601 string. Has value 10; for example, in the 2013-03-10T02:00:00Z case the first 10 characters will be 2013-03-10. If you need to extract this date part from ISO8601 string (not just know the characters count), use getISO8601StringWithoutTimePart function.
DaysOfWeek
Allows to refer to the day of week by name, not by number what usually confusing with numeration from 0 (and also, first day of week is location dependent).
HOURS_PER_STELLAR_DAY
Has value 24. Everyone may know it but the meaning of this constant is avoiding of the magic numbers in the code.
MAXIMAL_DAYS_IN_MONTH
Has value 31. Everyone may know it but the meaning of this constant is avoiding of the magic numbers in the code.
MINUTES_PER_HOUR
Has value 60. Everyone may know it but the meaning of this constant is avoiding of the magic numbers in the code.
MONTHS_PER_YEAR
Has value 12. Everyone may know it but the meaning of this constant is avoiding of the magic numbers in the code.
MonthsNames
Allows to refer to the month by name, not by number what usually confusing with numeration from 0.
SECONDS_PER_MINUTE
Has value 60. Everyone may know it but the meaning of this constant is avoiding of the magic numbers in the code.
HTTP

Pagination

computeFirstItemNumberForSpecificPaginationPage
Computes the first item number for specified pagination page.
computeLastItemNumberForSpecificPaginationPage
Computes the last item number for specified pagination page.

Logging

Logger facade
Basic facade for providing of the high-quality logging with customizable output destinations, formatting and limitations.
Pre-made errors
AlgorithmMismatchError
Intended to be used in general cases when actual behaviour does not match with desired.
ClassRedundantSubsequentInitializationError
Intended to be used when the class developed as singleton has been attempted to initialize twice.
ClassRequiredInitializationHasNotBeenExecutedError
Intended to be used when the class besides the construction requires the initialization but the initializing method has not been called.
ConfigFileNotFoundError
Intended to be used when some utility requires the config file but it has not been found.
CrossBrowserIssueError
Intended to be used when some processing could not be executed because of certain browsers's limitations.
DataRetrievingFailedError
Intended to be used when the data retrieving from some external resource (server, database, file, etc.) failed.
DataSubmittingFailed
Intended to be used when the data submitting to any external resource (server, database, etc.) failed.
DOM_ElementRetrievingFailedError
Intended be used when some element retrieving from the DOM has been failed. It could occur not only on client side but also on server side, during rendering or HTML code processing.
FileReadingFailedError
Intended to be used when the file reading was not go as expected
ImproperUsageError
Intended to be used when the class/function has been attempted to use improperly. Herewith, try to name the function/methods such as it will be obvious how to use it and also limit the usage by TypeScript typing.
IncompatiblePropertiesInObjectTypeParameterError
Intended to be used when in parameter exampleParameter of object type one of properties exampleParameter.propertyA and exampleParameter.propertyB must be omitted but both has been specified.
InterProcessInteractionFailedError
Intended to be used when the interaction between NodeJS processed is not going as expected. Could be actual, for example, for the Electron.js where the main process and render process are exchanges by data.
InvalidConfigError
Intended to be used when config validation was not passed. Appending of the validation errors messages to InvalidConfigError's message is strongly recommended.
InvalidExternalDataError
Intended to be used when the data from the external data source does not match with expected. Appending of the validation errors messages to InvalidExternalDataError's message is strongly recommended.
InvalidParameterValueError
Intended to be used when the parameter's does not fit to some limitations. Although the TypeScript allows to define and check the parameter's type, no type check will not be executed once TypeScript will be compiled to JavaScript. Also, is the parameter has limitations like smallest numerical value or maximal characters count, InvalidParameterValueError has been developed for such cases.
ModuleDynamicLoadingFailedError
Recommended to throw when the module dynamical loading failed. Actual for bundlers like Webpack.
UnexpectedEventError
Intended to be used when the probability of the occurrence of some "else if" branch is very small and impossible for normal operation of the program.
UnsupportedScenarioError
Intended to be used when occurred some scenario which is not supported yet.

Readme

Keywords

Package Sidebar

Install

npm i @yamato-daiwa/es-extensions

Weekly Downloads

130

Version

1.6.11

License

MIT

Unpacked Size

844 kB

Total Files

609

Last publish

Collaborators

  • yd-tokugawa_t