@knownout/lib
v0.1.4
Published
Utility functions library
Downloads
3
Readme
🧱 Utility functions library
Select documentation language: English (selected), Русский
This is a service project for providing common functionality as a npm package. Below is a list of available features with a short description, documentation and usage.
Functions
| # | Name | Description | |----:|:-----------------------------------------------------|:-------------------------------------------------------------------------| | 1 | classNames | Create class names from any type of objects | | 2 | mergeObjects | Combine objects that go sequentially into groups | | 3 | mergeStringArray | Combine array entries that go sequentially (add-on over mergeObjects) | | 4 | limitNumber | Limit a certain number to an upper and lower bound | | 5 | computeArrayWeights | Calculate weight of strings array items based on another string (query) | | 6 | sortByWeights | Sort strings array by computed weights | | 7 | computeProgress | Calculate progress (0-100) based on provided current, min and max values | | 8 | compareStrings | Compare two strings with specific filters | | 9 | cleanString | Clean string with or without regular expression | | 10 | rotateArray | Rotate an array to specified direction by one or more steps |
Classes
| # | Name | Description | |----:|:----------------------------------------------------------|:-------------------------------------------------------| | 1 | DateConverter | Convert date from unix or from date to selected format | | 2 | StringExtractor | Extract special entries from string | | 3 | StringProcessor | Modify strings with special properties | | 4 | StorageController | Browser storage data controller | | 5 | MakeFormData | Simplifying the creation of FormData objects | | 6 | Random | Several random value generators | | 7 | MakeElement (deprecated) | Plain html elements constructor |
Functions documentation
classNames function
- Signature:
(...args: any[]) => string
.
A function to generate class names from objects of any type. All array type arguments will be flattened, objects will be
converted as {[className]: Boolean}
. Each entry will be automatically truncated.
classNames("hello", { world: true, "not": null }) // => "hello world"
mergeObjects function
- Signature:
(objects: TObject[], mergeKey: [ string, any ], minMergeLimit: number = 2) => TObject[]
Complicated function for merging objects with identical key by this scheme (for A
):
{ A, A, B, A, A, B, B } => { [A, A], B, [A, A], B B }
. The minMergeLimit
property determines how many elements with
the selected key must be sequentially placed in one place for merging.
mergeObjects([ { key: "A", text: "Hello" }, { key: "A", text: "World" }, { key: "B", text: "Not" } ], { key: "A" })
// Execution result
[
[
{
"key": "A",
"text": "Hello"
},
{
"key": "A",
"text": "World"
}
],
{
"key": "B",
"text": "Not"
}
]
mergeStringArray function
- Signature:
(array: string[], minMergeLimit: number = 2) => string[]
Works the same as mergeObjects, but for string arrays.
limitNumber function
- Signature:
(value: number, top?: number | TLimitNumberOptions | null, bottom?: number | null) => number
Limit a certain number to an upper and lower bound, pass null to remove specific bound and use next one.
limitNumber(10, 5, 0) // => 5
limitNumber(15, null, 10) // => 15
limitNumber(15, {
bottom: 10
}) // => 15
limitNumber(-10, 5, 0) // => 0
limitNumber(-10, {
top: 5,
bottom: 0
}) // => 0
computeArrayWeights function
- Signature:
(query: string, array: string[]) => number[]
Calculates weight of the elements of a strings array based on a specific query. The less weight is better.
computeArrayWeights("Hello", [ "henlo", "hellow", "okay", "goodbye" ])
// Execution result
[
0.0375234521575985,
0,
1.0793465577596266,
0.6635071090047393
]
sortByWeights function
- Signature:
(query: string, array: string[]) => string[]
Sorting the array of strings by the computed weights from the previous function. The entries most like the query will be higher.
sortByWeights("Hello", [ "ok", "good", "henlow", "henlo" ]) // => ["henlow", "henlo", "good", "ok"]
computeProgress function
- Signature:
(value: number, max = 100, min = 0) => number
Calculate progress (0-100) based on provided current, min and max values. Calculates using this
formula: X = (A * 100) / (B - C)
.
computeProgress(10, 200, 100) // => 10
computeProgress(10, 200) // => 5
compareStrings function
- Signature:
(a: string, b: string) => { result: boolean, weight: number }
Compare two strings with specific filters and returns comparison result (boolean) and comparison weight (number, lower is better).
compareStrings("Hello", "henlo") // => { "result": true, "weight": 0.0375234521575985 }
compareStrings("Hello", "nothello") // => { "result": false, "weight": 0.707635009310987 }
compareStrings("Hello", "hello") // => { "result": true, "weight": 0 }
cleanString function
- Signature:
(entry: string, cleanRegexp?: RegExp) => string
Cleaning a string with or without a regular expression. Automatically trim input and remove extra spaces.
cleanString("Hello world ") // => "Hello world"
rotateArray function
- Signature:
<T = unknown[]>(array: T, right = true, steps = 1) => T
Rotate an array to specified direction by one or more steps.
rotateArray([ 1, 2, 3, 4, 5 ]) // => [5, 1, 2, 3, 4]
rotateArray([ 1, 2, 3, 4, 5 ], true, 3) // => [3, 4, 5, 1, 2]
rotateArray([ 1, 2, 3, 4, 5 ], false) // => [2, 3, 4, 5, 1]
Classes documentation
DateConverter class
- Constructor signature:
(entry: Date | string | number, unix = true)
Utility class to convert date, javascript or unix timestamps to specific forms.
Methods list
toUnuxTimestamp() => number
- convert date to unix timestamp.toReadable (mappings: TMonthMappings = russianMonths, format: string = this.defaultReadableFormat) => string
- convert date to human-readable format using name mappings and format property.
Mappings scheme
{
casing: {
"regularEnding": "caseEnding"
},
months: [
"firstMonthName",
"secondMonthName",
"..."
]
}
Usage
// Date.now() / 1000 is a unix timestamp
const converter = new DateConverter(Date.now() / 1000)
converter.toReadable() // => 10 мая 2022
converter.toUnixTimestamp // => 1652187277
StringExtractor class
- Constructor signature:
(public entry: string)
Utility class for retrieving specific entries defined as regular expressions from the provided string.
Methods list
get extract (): { entry: string; extracted: { [p: string]: string[]; }; }
- extract specific entities from string using defined extractors.attach (...extractors: (RegExp | [ RegExp, string ])[]): this
- attach regular expression extractor to current instance.
Usage
const extractor = new StringExtractor("Hello !weird #world")
extractor.attach(/#[A-z]*/g, [ /![A-z]*/, "excl" ])
extractor.extract // => { entry: 'Hello', extracted: { '#': [ 'world' ], excl: [ '!weird' ] } }
// Extracted values can be accessed using extracted property
extractor.extracted // => same to extractor.extract method execution result
// Also updated property extractor.entry, now it is equal to 'Hello'
StringProcessor class
- Constructor signature:
(public entry: string)
Utility class for modifying strings with special properties.
Methods list
get extractor () => StringExtractor
- get StringExtractor class instance.get wordsList () => string[]
- generate words array from current entry.get removeDuplicates () => this
- remove duplicate words from entry usingmergeStringArray
utility function.
removeDuplicate
method return StringProcessor class instance, removing result writing directly into entry.
compare (value: string) => { result: boolean, weight: number }
- compare current entry with specific string usingcompareStrings
function.get clean () => this
- clean entry string usingcleanString
function.limitWordsCount (limit: number, ellipsis: boolean = true, numbers = true) => this
- limit words count in current entry (act likeremoveDuplicates
, writes result directly into entry).filter (...filters: (RegExp | string)[]) => this
- apply regular expressions or strings as filters (like word filter) to the current entry.
Usage
const processor = new StringProcessor("Hey, hello hello weird world!");
// will not work with upper/lower case and punctuation
processor.removeDuplicates;
processor.entry // => 'Hey, hello weird world!'
processor.wordsList // => [ 'Hey,', 'hello', 'weird', 'world!' ]
// Cuz' this method write directly into entry, you cannot restore deleted words
processor.limitWordsCount(3)
processor.entry // => Hey, hello weird...
StorageController class
- Constructor signature:
(public readonly storage: Storage)
An add-on over the native browser storage. Provides simplified interaction interface (slower than native due to JSON transformations).
Methods list
getItem<T = any> (key: string) => false | T
- get item from defined browser storage by a specific key and parse item data like JSON content.setItem<T = any> (key: string, value: T) => this
- stringify provided value and write it to the defined browser storage.removeItem (key: string) => this
- remove item from defined browser storage.exist (key: string) => boolean
- check if specific key exists in the defined storage.
Usage
const controller = new StorageController(localStorage);
// Methods can be chained
controller.setItem("keyName", { key: "World" });
controller.getItem("keyName").key // => `World`
MakeFormData class
- Constructor signature:
(items?: { [key: string]: any })
Utility class for creating FormData objects that can be chained.
Methods list
fetchObject () => { method: string, body: FormData }
- get native FormData object as object suitable for the fetch function.add (items: { [key: string]: any }, forceJson: boolean = false) => this
- an add-on over the native method for adding a FormData object, allows simultaneous application of several elements (forceJson used to force non-file entries conversion as JSON objects).remove (...items: string[]) => this
- an add-on over the native remove method of the FormData object allows deleting multiple items at the same time.
FormData can be accessed with .entry
property of MakeFormData instance.
Usage
const formData = new MakeFormData();
formData.add({ key: "Hello world" });
formData.entry // => FormData
formData.fetchObject // => { method: "POST", body: FormData }
Random class
- Constructor signature:
does not have a constructor
Utility class for generating various types of random values.
Methods list
static string (length: number, pattern: string = "AZ,az,09") => string
- fixed length random string generator.
string
method gets the range of values from the pattern by converting characters into char code, because of this,
they only work as you would expect if there are patterns that have sequentially character codes: AZ, az, 09, etc
.
static arrayElement<T = unknown> (array: T[]) => T
- random array element picker.static number (min: number, max: number) => number
- random number generator with upper and lower bounds.uniqueValues<T = any> (count: number, generator: Function) => Set<T>
- generate unique random values for each instance of the class (so far in one instance unique values will be generated each time)
uniqueValues
method stores generated values inside an instance variable (RAM), so if you create a different instance,
generated values may be repeated.
The uniqueValues
method will throw an error after 10,000 generation attempts, this error means that all possible
values have already generated.
Random class instance methods (same to static ones):
string (length: number, pattern: string = "AZ,az,09") => string
arrayElement<T = unknown> (array: T[]) => T
number (min: number, max: number) => number
About patterns
The pattern must pass as a string containing values (not longer than two characters) separated by a comma. Each value will either convert to an array of characters (if the length equal 2) or simply passed to the generated array (if the length equal 1).
Pattern conversion examples:
AD → [A, B, C, D]
AC,ac → [A, B, C, a, b, c]
02,AB,@,# → [0, 1, 2, A, B, @, #]
Static methods usage
Random.string(10, "AZ,09") // => 'RLDL0QQLWV'
Random.arrayElement([ 1, 2, 3, 4, 5 ]) // => 4
Random.number(100, 212) // => 107
Random.number(100.3, 212.5) // => 153.52220396806507
Instance methods usage
const random = new Random();
random.uniqueValues(5, () => Random.string(3))
// => Set(5) { 'YRd', 'GI3', 'ig2', 'D8o', 'Ro0' }
// Other instance methods are just wrappers around
// static methods.
MakeElement class (deprecated)
- Constructor signature:
<K extends keyof HTMLElementTagNameMap> (tag: K)
Utility class for easily creating and manipulating HTML elements.
@deprecated (documentation can still be found in the sources or inside bin/classes/MakeElement.d.ts
)
re-knownout - https://github.com/re-knownout/ [email protected]