@vapaaradikaali/helpers.js

0.41.3 • Public • Published

Build Status Coverage Status

Modules

Errors

Classes

BrowserEvents
Config
Datamap
Dataset
LocalizationError
InvalidTimestamp
InvalidFormatter
Localization
Storage
TreeError
PropertyError
PropertyError
NodeNotFound
Tree

Functions

setSchema(schema)Config

Set JSON schema validation for the configuration. This sets the main schema for the configuration instead of adding a schema by its id, which can be used to add optional referenced schemas.

addSchema(schema)Config

Add a JSON schema to config validator. Use this to add any referenced schemas and Config.setSchema for the main schema.

normalizeSchemaId(id)string

Normalize schema id

buildUrl([args])

Build URL from the given parameters

buildUrl(protocol, [host], [port], [username], [password], [location], [query])string

Build URL from the given parameters

castObjectAsArray(source, recurse)array

Cast an indexed object as array

castToArray(input)mixed

Cast values

copyObject(source)mixed

Create a deep copy of an object or an array

escapeSql(arg, [quote], [force])mixed

Escape SQL argument

expandObject(input)

Expand a flattened object. This method unpacks values flattened with flattenObject

flattenObject(input)

Flatten an object. This is a serialization method that takes an object and flattens it into a single-level object with deep keys joined with a dot.

getClassName(input)string

Get unique class names from a string or an array input

getObjectPaths(source)Array.<string>

Get an array or a set mapped by the given attribute

getObjectPaths(source)Array.<string>

Get object paths

getPath(path)Array.<string>

Internal helper to get path from the given argument

getRandomString(length)

Get random string of the given length

getValue(source, path, [defaultValue])mixed

Get value by path, each node separated by a dot (.). If an array of paths is given, the first available value is returned. If no value is found the default value is returned.

getValue(haystack, needles)boolean

Check if the haystack has all of the needles

getValue(haystack, needles)boolean

Check if the haystack has any of the needles

getValue(haystack, needles)boolean

Check if the haystack has other values than the needle

httpBuildQuery(query, options)string

Build a HTTP query from an object

intersection()array

Get intersection of the given arrays

isEqual(value)

Compare two or more items to check if they are equal

isInstance(source, targets, loose)boolean

Check if the given object is instance of the given types

isObject(value)boolean

Check if the input value is a plain object

roundTo(value, [precision], [method])

Round to precision

sleep(duration)

Sleep for the given amount of time

sortObject(input)

Sort an object by key or an array by its values

splitStringIntoChunks(input, length, separator, [left])string

Split string into chunks of the given size and merge them with the given separator string. Default chunk grouping order is from right to left.

Errors

Errors~ConfigError

Kind: inner class of Errors Summary:

Config error

.

new ConfigError()

Config error

Errors~ConfigNotFoundError ⇐ ConfigError

Kind: inner class of Errors Summary:

Config not found error

. Extends: ConfigError

new ConfigNotFoundError()

Config not found error

Errors~ConfigParseError ⇐ ConfigError

Kind: inner class of Errors Summary:

Config parse error

. Extends: ConfigError

new ConfigParseError()

Config parse error

BrowserEvents

Kind: global class Summary:

Browser events class

.

new BrowserEvents()

Browser events class

browserEvents.on(eventName, callback)

Register an event listener

Kind: instance method of BrowserEvents Summary:

Register an event listener

.
Param Type Description
eventName string

Event name

callback function

Event listener

browserEvents.off(eventName, [callback])

Unregister event listeners, optionally only the given

Kind: instance method of BrowserEvents Summary:

Unregister event listeners, optionally only the given

.
Param Type Description
eventName string

Event name

[callback] function

Event listener

browserEvents.trigger(eventName)

Trigger an event

Kind: instance method of BrowserEvents Summary:

Trigger an event

.
Param Type Description
eventName string

Event name

...args mixed

Event arguments

Config

Kind: global class Summary:

Configuration class

.

new Config()

Configuration class

config.constructor([values], [schema])

Constructor

Kind: instance method of Config Summary:

Constructor

.
Param Type Description
[values] object

Instance values

[schema] object

Instance schema

config.setDefaultValues() ⇒ Config

Set default values

Kind: instance method of Config Summary:

Set default values

. Returns: Config -

Self

config.getValidator() ⇒ jsonschema.Validator

Get a singleton instance of validator

Kind: instance method of Config Summary:

Get a singleton instance of validator

. Returns: jsonschema.Validator -

Validator instance

config.getPath(path) ⇒ array

Internal helper to get path from the given argument

Kind: instance method of Config Summary:

Internal helper to get path from the given argument

. Returns: array -

Path as an array

Param Type Description
path mixed

String or an array of strings

config.set([path], value) ⇒ Config

Set configuration value

Kind: instance method of Config Summary:

Set configuration value

. Returns: Config -

Self

Param Type Description
[path] string | Array.<string>

or an array of strings

value mixed

Any value that can be serialized as JSON

config.del([path])

Delete a configuration value

Kind: instance method of Config Summary:

Delete a configuration value

.
Param Type Description
[path] string | Array.<string>

or an array of strings

config.validateBeforeSet([path], value) ⇒ Config

Validate the value before setting it

Kind: instance method of Config Summary:

Validate the value before setting it

. Returns: Config -

Self

Param Type Description
[path] string | Array.<string>

or an array of strings

value mixed

Any value that can be serialized as JSON

config.validate([values], [schema]) ⇒ Config

Validate configuration

Kind: instance method of Config Summary:

Validate configuration

. Returns: Config -

Self

Param Type Description
[values] object

Values; stored values when omitted

[schema] object

Schema to validate against

config.setValuesToPath([path], value, target) ⇒ object

Set value to path for the given target object

Kind: instance method of Config Summary:

Set value to path for the given target object

. Returns: object -

Target object

Param Type Description
[path] string | Array.<string>

or an array of strings

value mixed

Any value that can be serialized as JSON

target object

Target object

config.get(paths, defaultValue) ⇒ mixed

Get configuration value

Kind: instance method of Config Summary:

Get configuration value

. Returns: mixed -

Stored configuration value or the given default value

Param Type Description
paths string | Array.<string>

String or an array of strings

defaultValue mixed

Default value if the stored is null or undefined

config.toJSON() ⇒ object

JSON serializer

Kind: instance method of Config Summary:

JSON serializer

. Returns: object -

JSON serializeable object

Datamap

Kind: global class Summary:

Replacement for Javascript's native Map that is very slow to access data versus a purecode object.

new Datamap()

Replacement for Javascript's native Map that is very slow to access data versus a purecode object. This will also utilize methods familiar from Array and Set for iterating, copying, filtering, mapping, reducing the content.

datamap.length : number

Datamap length

Kind: instance constant of Datamap Summary:

Datamap length

.

datamap.size : number

Datamap size, alias to length

Kind: instance constant of Datamap Summary:

Datamap size, alias to length

.

datamap.clone : function

Clone a datamap, alias for copy

Kind: instance constant of Datamap Summary:

Clone a datamap, alias for copy

.

datamap.has(key) ⇒ boolean

Check if the datamap has the given key

Kind: instance method of Datamap Summary:

Check if the datamap has the given key

. Returns: boolean -

True if a value exists

Param Type Description
key mixed

Map key

datamap.get(key) ⇒ mixed

Get the datamap value

Kind: instance method of Datamap Summary:

Get the datamap value

. Returns: mixed -

Stored value

Param Type Description
key mixed

Map key

datamap.set(key, value)

Set the datamap value

Kind: instance method of Datamap Summary:

Set the datamap value

.
Param Type Description
key mixed

Map key

value mixed

Stored value

datamap.add(value)

Add an indexed datamap value

Kind: instance method of Datamap Summary:

Add an indexed datamap value

.
Param Type Description
value object

Any value

datamap.setIndex(index)

Set index for datamap values

Kind: instance method of Datamap Summary:

Set index for datamap values

.
Param Type Description
index string

Any value

datamap.keys() ⇒ Array.<string>

Get the datamap keys

Kind: instance method of Datamap Summary:

Get the datamap keys

. Returns: Array.<string> -

Stored keys

datamap.values() ⇒ Array.<mixed>

Get the datamap values

Kind: instance method of Datamap Summary:

Get the datamap values

. Returns: Array.<mixed> -

Stored values

datamap.clear()

Clear the datamap

Kind: instance method of Datamap Summary:

Clear the datamap

.

datamap.delete(key)

Delete a datamap key

Kind: instance method of Datamap Summary:

Delete a datamap key

.
Param Type Description
key mixed

Map key

datamap.forEach(iterator)

Iterate a datamap

Kind: instance method of Datamap Summary:

Iterate a datamap

.
Param Type Description
iterator function

Iterator callback function

datamap.map(iterator) ⇒ Array.<mixed>

Map function for a datamap

Kind: instance method of Datamap Summary:

Map function for a datamap

. Returns: Array.<mixed> -

Iterator output

Param Type Description
iterator function

Iterator callback function

datamap.reduce(iterator, initialValue) ⇒ mixed

Reduce function for a datamap

Kind: instance method of Datamap Summary:

Reduce function for a datamap

. Returns: mixed -

Iterator output

Param Type Description
iterator function

Iterator callback function

initialValue mixed

Initial value

datamap.filter(iterator) ⇒ Datamap

Filter function for Datamap

Kind: instance method of Datamap Summary:

Filter function for Datamap

. Returns: Datamap -

Filtered datamap

Param Type Description
iterator function

Iterator callback function

datamap.copy() ⇒ Datamap

Copy function for datamap

Kind: instance method of Datamap Summary:

Copy function for datamap

. Returns: Datamap -

Copy of the datamap

datamap.slice([start], [end]) ⇒ Datamap

Slice function for datamap

Kind: instance method of Datamap Summary:

Slice function for datamap

. Returns: Datamap -

Sliced copy of the datamap

Param Type Description
[start] number

Start index

[end] number

End index

Datamap.Options : Options

Options object for Datamaps

Kind: static constant of Datamap Summary:

Options object for Datamaps

.

Dataset

Kind: global class Summary:

Dataset

. Implements: Set

new Dataset([data], [options])

Dataset

Param Type Description
[data] Array | Set

Initial data

[options] object

Options

dataset.size

Alias "length" for "size"

Kind: instance property of Dataset Summary:

Alias "length" for "size"

.

dataset.includes

Alias "includes" for "has"

Kind: instance property of Dataset Summary:

Alias "includes" for "has"

.

dataset.contains

Alias "contains" for has

Kind: instance property of Dataset Summary:

Alias "contains" for has

.

dataset.clear

Alias "truncate" for "clear"

Kind: instance property of Dataset Summary:

Alias "truncate" for "clear"

.

dataset.*iterator()

Iterator protocol

Kind: instance method of Dataset Summary:

Iterator protocol

.

dataset.toArray() ⇒

Convert dataset to an array

Kind: instance method of Dataset Summary:

Convert dataset to an array

. Returns:

Array

dataset.addToMap(values) ⇒ Dataset

Add values to map. This is for backwards compatibility.

Kind: instance method of Dataset Summary: Add values to map. Returns: Dataset -

This instance

Param Type Description
values mixed

An individual value, an array or a Set

dataset.add(values)

Add an item

Kind: instance method of Dataset Summary:

Add an item

.
Param Type Description
values Array.<mixed>

Any value

dataset.addToIndices(values) ⇒ Dataset

Add values to indices

Kind: instance method of Dataset Summary:

Add values to indices

. Returns: Dataset -

This instance

Param Type Description
values mixed

An individual value, an array or a Set

dataset.copy() ⇒ Dataset

Copy the current dataset

Kind: instance method of Dataset Summary:

Copy the current dataset

. Returns: Dataset -

Copy of this instance

dataset.merge(data) ⇒ Dataset

Merge datasets

Kind: instance method of Dataset Summary:

Merge datasets

. Returns: Dataset -

Merged datasets

Param Type Description
data Array.<Dataset>

Datasets to merge

dataset.concat()

Alias for merge

Kind: instance method of Dataset Summary:

Alias for merge

.

dataset.delete(values)

Delete an item

Kind: instance method of Dataset Summary:

Delete an item

.
Param Type Description
values Array.<mixed>

Any value

dataset.clear()

Clear the dataset

Kind: instance method of Dataset Summary:

Clear the dataset

.

dataset.getById(id) ⇒ mixed

Get item by id

Kind: instance method of Dataset Summary:

Get item by id

. Returns: mixed -

Stored value

Param Type Description
id number | string

Value of the id property

dataset.getByIndex(index, id) ⇒ mixed

Get item by indexed value

Kind: instance method of Dataset Summary:

Get item by indexed value

. Returns: mixed -

Stored value

Param Type Description
index string

Index

id number | string

Value of the id property

dataset.getByProperty(prop, value, recursive)

Get by property

Kind: instance method of Dataset Summary:

Get by property

.
Param Type Description
prop string

Property

value mixed

Needle

recursive string

Recursive property

dataset.map(iterator) ⇒ Dataset

Map like an array map

Kind: instance method of Dataset Summary:

Map like an array map

. Returns: Dataset -

Dataset of the values returned by the iterator

Param Type Description
iterator function

Iterator function

dataset.filetr(iterator, matchAny) ⇒ Array.<mixed>

Filter like an array filter

Kind: instance method of Dataset Summary:

Filter like an array filter

. Returns: Array.<mixed> -

An array with the value iterator gives

Param Type Description
iterator function | object

Iterator function or an object filter

matchAny boolean

Match any flag

dataset.reduce(reducer, initial) ⇒ mixed

Reduce the dataset

Kind: instance method of Dataset Summary:

Reduce the dataset

. Returns: mixed -

Reduced value

Param Type Description
reducer function

Reducer function

initial mixed

Initial value

dataset.sort(callback) ⇒ Dataset

Sort a dataset. Unlike Array.sort this will not change the original data but will return a new sorted Dataset instead.

Kind: instance method of Dataset Summary: Sort a dataset. Returns: Dataset -

Sorted dataset

Param Type Description
callback function

Sort callback

dataset.reverse() ⇒ Dataset

Reverse a dataset. Unlike Array.reverse this will not change the original data but will return a new sorted Dataset instead.

Kind: instance method of Dataset Summary: Reverse a dataset. Returns: Dataset -

Reversed dataset

dataset.find(callback) ⇒ mixed

Find the first occurence from a dataset

Kind: instance method of Dataset Summary:

Find the first occurence from a dataset

. Returns: mixed -

Dataset item

Param Type Description
callback function

Find callback

dataset.findLast(callback) ⇒ mixed

Find the last occurence from a dataset

Kind: instance method of Dataset Summary:

Find the last occurence from a dataset

. Returns: mixed -

Dataset item

Param Type Description
callback function

Find callback

dataset.toJSON() ⇒ array

Serialize dataset as JSON

Kind: instance method of Dataset Summary:

Serialize dataset as JSON

. Returns: array -

JSON serializable array

dataset.splitIntoChunks(length) ⇒ Array.<Dataset>

Split the dataset into chunks

Kind: instance method of Dataset Summary:

Split the dataset into chunks

. Returns: Array.<Dataset> -

An array of datasets

Param Type Description
length number

Number of chunks

LocalizationError

Kind: global class Summary:

Localization error

.

new LocalizationError()

Localization error

InvalidTimestamp

Kind: global class Summary:

Invalid timestamp error

.

new InvalidTimestamp()

Invalid timestamp error

InvalidFormatter

Kind: global class Summary:

Invalid formatter error

.

new InvalidFormatter()

Invalid formatter error

Localization

Kind: global class Summary:

Localization class

.

new Localization([lang], [fallbackLang])

Localization class

Param Type Description
[lang] string

Localization language

[fallbackLang] string

Fallback language if the main language is not found

Example

`const l10n = new Localization('fi', 'en')`

localization.errors : object

Errors wrapper

Kind: instance constant of Localization Summary:

Errors wrapper

.

localization.registerLogger(logger) ⇒ Localization

Shorthand for the static method Localization.registerLogger

Kind: instance method of Localization Summary:

Shorthand for the static method Localization.registerLogger

. Returns: Localization -

This instance

Param Type Description
logger function

Callback function

localization.logger(level, args) ⇒ Localization

Call logger

Kind: instance method of Localization Summary:

Call logger

. Returns: Localization -

This instance

Param Type Description
level number

Log level

args array

Logger arguments

localization.registerLocale() ⇒ function

Alias to the static registerLocale method

Kind: instance method of Localization Summary:

Alias to the static registerLocale method

. Returns: function -

Constructor.toCase function

localization.registerLocales() ⇒ function

Alias to the static registerLocales method

Kind: instance method of Localization Summary:

Alias to the static registerLocales method

. Returns: function -

Constructor.toCase function

localization.getLocales([lang]) ⇒ object

Get locales, an instance convenience alias for the static method Localization.getLocales

Kind: instance method of Localization Summary:

Get locales, an instance convenience alias for the static method Localization.getLocales

. Returns: object -

Registered locales

Param Type Description
[lang] string

Language constraint

localization.unregisterLocales() ⇒ function

Alias to the static registerLocales method

Kind: instance method of Localization Summary:

Alias to the static registerLocales method

. Returns: function -

Constructor.toCase function

localization.unregisterLocale() ⇒ function

Alias to the static registerLocales method

Kind: instance method of Localization Summary:

Alias to the static registerLocales method

. Returns: function -

Constructor.toCase function

localization.toCase() ⇒ function

Alias to the static toCase method

Kind: instance method of Localization Summary:

Alias to the static toCase method

. Returns: function -

Constructor.toCase function

Localization.UPPERCASE : string

Kind: static constant of Localization

Localization.LOWERCASE : string

Kind: static constant of Localization

Localization.TITLECASE : string

Kind: static constant of Localization

Localization.PARAGRAPHCASE : string

Kind: static constant of Localization

Localization.CAMELCASE : string

Kind: static constant of Localization

Localization.UNDERSCORECASE : string

Kind: static constant of Localization

Localization.INVALID_TIMESTAMP : Errors.InvalidTimestamp

Kind: static constant of Localization

Localization.errors : object

Static errros wrapper

Kind: static constant of Localization Summary:

Static errros wrapper

.

Localization.validateRounding(rounding)

Validate rounding type

Kind: static method of Localization Summary:

Validate rounding type

.
Param Type Description
rounding string

Enumerates "round", "ceil", "floor"

Localization.getRoundedNumber(value, [precision], [rounding]) ⇒ number

Get rounded number

Kind: static method of Localization Summary:

Get rounded number

. Returns: number -

Rounded number

Param Type Default Description
value number | string

Number or a numeric string to round

[precision] number

Rounding precision

[rounding] string "&quot;round&quot;"

Enumerates "round", "ceil", "floor"

Localization.toCase(input, toCase) ⇒ string

Convert case for a string

Kind: static method of Localization Summary:

Convert case for a string

. Returns: string -

String converted to the given case

Param Type Description
input string

Input string

toCase string

Case for the output

Localization.registerLogger(logger)

Register a logger for the localization. This will log e.g. missing locales

Kind: static method of Localization Summary: Register a logger for the localization.

Param Type Description
logger function

Callback function

Example

Localization.registerLogger((...args) => console.log(...args))

Localization.registerLocale(locale, translations) ⇒ Localization

Register locales

Kind: static method of Localization Summary:

Register locales

. Returns: Localization -

This instance

Param Type Description
locale string

Locale key

translations object

Translations

Localization.registerLocales(data) ⇒ Localization

Register locales

Kind: static method of Localization Summary:

Register locales

. Returns: Localization -

This instance

Param Type Description
data object

Locales to register

Localization.getLocales([lang]) ⇒ object

Get locales

Kind: static method of Localization Summary:

Get locales

. Returns: object -

Registered locales

Param Type Description
[lang] string

Language constraint

Localization.unregisterLocales(data) ⇒ Localization

Unregister locales

Kind: static method of Localization Summary:

Unregister locales

. Returns: Localization -

This instance

Param Type Description
data mixed

Locales to be registered as a string or array of strings

Localization.unregisterLocale() ⇒ function

Alias to the static registerLocales method

Kind: static method of Localization Summary:

Alias to the static registerLocales method

. Returns: function -

Constructor.toCase function

Storage

Kind: global class Summary:

Storage class

.

new Storage(engine)

Storage class

Param Type Description
engine mixed

Storage engine

storage.setEngines(engine)

Set storage engine

Kind: instance method of Storage Summary:

Set storage engine

.
Param Type Description
engine mixed

Storage engine

storage.set(key, value, expiresAt)

Set stored value

Kind: instance method of Storage Summary:

Set stored value

.
Param Type Description
key string

Storage key

value mixed

Storage value

expiresAt mixed

ISO 8601 temporal, seconds as number or anything Moment.js accepts

storage.get(key, defaultValue) ⇒

Get stored value

Kind: instance method of Storage Summary:

Get stored value

. Returns:

mixed Stored value, default value or null

Param Type Description
key string

Storage key

defaultValue mixed

Value if storage does not have anything

storage.del(key)

Delete a storage key

Kind: instance method of Storage Summary:

Delete a storage key

.
Param Type Description
key string

Storage key

storage.clear()

Clear storage

Kind: instance method of Storage Summary:

Clear storage

.

Storage.StorageEngine : StorageEngine

Storage engine

Kind: static constant of Storage Summary:

Storage engine

.

Storage.validateKey(key)

Validate storage key

Kind: static method of Storage Summary:

Validate storage key

.
Param Type Description
key string

Storage key

Storage.getExpiresAt(expiresAt) ⇒ undefined | Moment

Get expires at

Kind: static method of Storage Summary:

Get expires at

. Returns: undefined | Moment -

Undefined when no expiration is given, an instance of Moment otherwise

Param Type Description
expiresAt mixed

ISO 8601 temporal, seconds as number or anything Moment.js accepts

Storage.hasExpired(expiresAt) ⇒ boolean

Check if the timestamp is in the past

Kind: static method of Storage Summary:

Check if the timestamp is in the past

. Returns: boolean -

True if expired, otherwise false

Param Type Description
expiresAt string

Expiration timestamp as ISO 8601 string

TreeError

Kind: global class Summary:

Tree error baseclass

. Implements: Error

new TreeError()

Tree error baseclass

PropertyError

Kind: global class Summary:

PropertyError

. Implements: TreeError

new PropertyError()

PropertyError

new PropertyError()

InvalidArgument

PropertyError

Kind: global class Summary:

InvalidArgument

. Implements: TreeError

new PropertyError()

PropertyError

new PropertyError()

InvalidArgument

NodeNotFound

Kind: global class Summary:

NodeNotFound

. Implements: TreeError

new NodeNotFound()

NodeNotFound

Tree

Kind: global class Summary:

Tree traversal class

.

new Tree([items], [idProperty], [parentProperty])

Tree traversal class

Param Type Default Description
[items] Array.<object>

Items

[idProperty] string "'id'"

Attribute used for identifier

[parentProperty] string "'parent'"

Attribute used for parent

Example

const nodes = [
      {
        attr_id: 1,
        attr_parent: null
      },
      {
        attr_id: 11,
        attr_parent: 1
      },
      {
        attr_id: 12,
        attr_parent: 1
      },
      {
        attr_id: 2,
        attr_parent: null
      }
    ]
    const tree = new Tree(nodes, 'attr_id', 'attr_parent)

tree.addNode() ⇒ Tree

An alias to addNodes

Kind: instance method of Tree Summary:

An alias to addNodes

. Returns: Tree -

This instance

tree.addNodes(items) ⇒ Tree

Add nodes to the tree

Kind: instance method of Tree Summary:

Add nodes to the tree

. Returns: Tree -

This instance

Param Type Description
items object | Array.<object>

Nodes to add

tree.getNode(needle) ⇒ Node

Get node

Kind: instance method of Tree Summary:

Get node

. Returns: Node -

Matching node

Param Type Description
needle mixed

Needle to search

tree.getBranch(needle, [metadata]) ⇒ Array.<object>

Get branch starting from the given node

Kind: instance method of Tree Summary:

Get branch starting from the given node

. Returns: Array.<object> -

Original items of the branch

Param Type Description
needle mixed

Needle to search

[metadata] boolean

Flag to define if the function should return Nodes instead of original objects

tree.getParents(needle, [metadata]) ⇒ Array.<object>

Get branch starting from the given node

Kind: instance method of Tree Summary:

Get branch starting from the given node

. Returns: Array.<object> -

Original items of the parent tree

Param Type Description
needle mixed

Needle to search

[metadata] boolean

Flag to define if the function should return Nodes instead of original objects

tree.getParents(needle, [metadata]) ⇒ object

Get root node for the given needle

Kind: instance method of Tree Summary:

Get root node for the given needle

. Returns: object -

Original items of the parent tree

Param Type Description
needle mixed

Needle to search

[metadata] boolean

Flag to define if the function should return Nodes instead of original objects

tree.getParents([needle], [metadata]) ⇒ object

Get leaves or the outmost part of the branch for the given needle

Kind: instance method of Tree Summary:

Get leaves or the outmost part of the branch for the given needle

. Returns: object -

Original items of the parent tree

Param Type Description
[needle] mixed

Needle to search

[metadata] boolean

Flag to define if the function should return Nodes instead of original objects

tree.isInTree(needle, haystack, [metadata]) ⇒ boolean

Get branch starting from the given node

Kind: instance method of Tree Summary:

Get branch starting from the given node

. Returns: boolean -

True if in the same tree, false if not

Param Type Description
needle mixed

Needle to search

haystack mixed

Haystrack to search

[metadata] boolean

Flag to define if the function should return Nodes instead of original objects

tree.getItems([metadata])

Get tree contents

Kind: instance method of Tree Summary:

Get tree contents

.
Param Type Description
[metadata] boolean

Flag to define if the function should return Nodes instead of original objects

tree.removeItem(needle)

Remove an item

Kind: instance method of Tree Summary:

Remove an item

.
Param Type Description
needle mixed

Needle to search

tree.removeItems([needles])

Remove multiple items or flush the whole tree if no needle is provided

Kind: instance method of Tree Summary:

Remove multiple items or flush the whole tree if no needle is provided

.
Param Type Description
[needles] mixed

Needles to search

tree.removeItems([needles])

Flush the whole tree

Kind: instance method of Tree Summary:

Flush the whole tree

.
Param Type Description
[needles] mixed

Needles to search

Tree.errors

Errors

Kind: static constant of Tree Summary:

Errors

.

Tree.DEFAULT_ID_PROPERTY : string

Default id property

Kind: static constant of Tree Summary:

Default id property

. Default: "id"

Tree.DEFAULT_PARENT_PROPERTY : string

Default parent property

Kind: static constant of Tree Summary:

Default parent property

. Default: "parent"

setSchema(schema) ⇒ Config

Set JSON schema validation for the configuration. This sets the main schema for the configuration instead of adding a schema by its id, which can be used to add optional referenced schemas.

Kind: global function Summary: Set JSON schema validation for the configuration. Returns: Config -

Self

Param Type Description
schema object

JSON schema

addSchema(schema) ⇒ Config

Add a JSON schema to config validator. Use this to add any referenced schemas and Config.setSchema for the main schema.

Kind: global function Summary: Add a JSON schema to config validator. Returns: Config -

Self

Param Type Description
schema object

JSON schema

normalizeSchemaId(id) ⇒ string

Normalize schema id

Kind: global function Summary:

Normalize schema id

. Returns: string -

Normalized schema id

Param Type Description
id string

Schema ID

buildUrl([args])

Build URL from the given parameters

Kind: global function Summary:

Build URL from the given parameters

.
Param Type Description
[args] string | Array.<string>

Arguments

Example

`buildUrl('postgresql', 'localhost', null, 'postgres', 'databaseName', { keepAlive: false })` returns `postgresql://postgres@localhost/databaseName?keepAlive=false`

buildUrl(protocol, [host], [port], [username], [password], [location], [query]) ⇒ string

Build URL from the given parameters

Kind: global function Summary:

Build URL from the given parameters

. Returns: string -

Constructed URL

Param Type Description
protocol string | object

Protocol or full configuration

[host] string

Host name

[port] number

Port

[username] string

Username

[password] string

Password

[location] string

Location

[query] object

Query parameters

Example

`buildUrl('postgresql', 'localhost', null, 'postgres', 'databaseName', { keepAlive: false })` returns `postgresql://postgres@localhost/databaseName?keepAlive=false`

castObjectAsArray(source, recurse) ⇒ array

Cast an indexed object as array

Kind: global function Summary:

Cast an indexed object as array

. Returns: array -

Array conversion of the object

Param Type Description
source object

Source object

recurse boolean

Recurse to child objects

castToArray(input) ⇒ mixed

Cast values

Kind: global function Summary:

Cast values

. Returns: mixed -

Merged object or array

Param Type Description
input mixed

Mixed input

Example

`castToArray(null)` returns an empty array `[]`
`castToArray('foo')` returns `['foo']`
`castToArray(['foo'])` returns `['foo']`
`castToArray({ foo: 'bar '})` returns `[{ foo: 'bar' }]`

copyObject(source) ⇒ mixed

Create a deep copy of an object or an array

Kind: global function Summary:

Create a deep copy of an object or an array

. Returns: mixed -

Copy of the given value

Param Type Description
source mixed

Source object/primitive to copy

escapeSql(arg, [quote], [force]) ⇒ mixed

Escape SQL argument

Kind: global function Summary:

Escape SQL argument

. Returns: mixed -

Escaped string or an object or and array of escaped strings

Param Type Default Description
arg mixed

Argument to escape

[quote] string "'&quot;'"

Quote type, either " or '

[force] boolean false

Flag to force quotes

Example

escapeSql takes a value (string, number, boolean, null) and escapes it if
it should be escaped. Second argument can be either the quote type (' and ")
are accepted. Third argument is force flag to force quote. If second argument
is a boolean value default quote type will be used and second argument will
be used as the force flag.

    escapeSql('foo')
    // returns foo

    escapeSql(123)
    // returns 123

    escapeSql('foo', true)
     // returns "foo"

    escapeSql('foo"bar')
    // returns "foo""bar"

If the first argument is an array or an object it will be recursively
escaped.

    escapeSql(['foo', 'bar'], '"', true)
    // returns ["\"foo\"", "\"bar\""]

    escapeSql({ foo: 'bar' }, "'", true)
    // returns { foo: "'bar'" }

expandObject(input)

Expand a flattened object. This method unpacks values flattened with flattenObject

Kind: global function Summary: Expand a flattened object.

Param Type Description
input object

Object to expand

Example Example:

expandObject({
{
  'foo.bar.value': true
  'foo.array': ['foo', 'bar']
}
})

will output

{
  foo: {
    bar: {
      value: true
    },
    array: ['foo', 'bar'],
  }
}

flattenObject(input)

Flatten an object. This is a serialization method that takes an object and flattens it into a single-level object with deep keys joined with a dot.

Kind: global function Summary: Flatten an object.

Param Type Description
input object

Object tree to flatten

Example

flattenObject({
  foo: {
    bar: {
      value: true
    },
    array: ['foo', 'bar'],
  }
})

will outpout

{
  'foo.bar.value': true
  'foo.array': ['foo', 'bar']
}

getClassName(input) ⇒ string

Get unique class names from a string or an array input

Kind: global function Summary:

Get unique class names from a string or an array input

. Returns: string -

Unique class names

Param Type Description
input string | Array.<string>

A string or an array

[...args] mixed

0...n other class names

getObjectPaths(source) ⇒ Array.<string>

Get an array or a set mapped by the given attribute

Kind: global function Summary:

Get an array or a set mapped by the given attribute

. Returns: Array.<string> -

Path as an array

Param Type Description
source object

Source object

getObjectPaths(source) ⇒ Array.<string>

Get object paths

Kind: global function Summary:

Get object paths

. Returns: Array.<string> -

Path as an array

Param Type Description
source object

Source object

getPath(path) ⇒ Array.<string>

Internal helper to get path from the given argument

Kind: global function Summary:

Internal helper to get path from the given argument

. Returns: Array.<string> -

Path as an array

Param Type Description
path string | Array.<string>

String or an array of strings

getRandomString(length)

Get random string of the given length

Kind: global function Summary:

Get random string of the given length

.
Param Type Description
length number

Length of the random string

getValue(source, path, [defaultValue]) ⇒ mixed

Get value by path, each node separated by a dot (.). If an array of paths is given, the first available value is returned. If no value is found the default value is returned.

Kind: global function Summary: Get value by path, each node separated by a dot (.). Returns: mixed -

Value stored in the path or the given default value

Param Type Description
source object

Source object

path string | Array.<string>

Path as a string or an array of strings for first-match

[defaultValue] mixed

Default value if nothing is found from the path(s)

getValue(haystack, needles) ⇒ boolean

Check if the haystack has all of the needles

Kind: global function Summary:

Check if the haystack has all of the needles

. Returns: boolean -

True if the haystack has any of the needles

Param Type Description
haystack mixed

Source object

needles mixed

Needles

getValue(haystack, needles) ⇒ boolean

Check if the haystack has any of the needles

Kind: global function Summary:

Check if the haystack has any of the needles

. Returns: boolean -

True if the haystack has any of the needles

Param Type Description
haystack mixed

Source object

needles mixed

Needles

getValue(haystack, needles) ⇒ boolean

Check if the haystack has other values than the needle

Kind: global function Summary:

Check if the haystack has other values than the needle

. Returns: boolean -

True if the haystack has any of the needles

Param Type Description
haystack mixed

Source object

needles mixed

Needles

httpBuildQuery(query, options) ⇒ string

Build a HTTP query from an object

Kind: global function Summary:

Build a HTTP query from an object

.
Param Type Description
query object

Query object

options object

Build options

intersection() ⇒ array

Get intersection of the given arrays

Kind: global function Summary:

Get intersection of the given arrays

. Returns: array -

Intersection

Param Type Description
...inputs array

Input arrays

isEqual(value)

Compare two or more items to check if they are equal

Kind: global function Summary:

Compare two or more items to check if they are equal

.
Param Type Description
value mixed

First item

...args mixed

Items to compare

isInstance(source, targets, loose) ⇒ boolean

Check if the given object is instance of the given types

Kind: global function Summary:

Check if the given object is instance of the given types

. Returns: boolean -

True if is instance, false if not

Param Type Description
source mixed

Source object to check

targets mixed

Target instances

loose boolean

Loose check

isObject(value) ⇒ boolean

Check if the input value is a plain object

Kind: global function Summary:

Check if the input value is a plain object

. Returns: boolean -

True if the input is an object, false if not

Param Type Description
value mixed

Any input type

roundTo(value, [precision], [method])

Round to precision

Kind: global function Summary:

Round to precision

.
Param Type Default Description
value number

Value to round

[precision] number 0

Precision

[method] string "&quot;round&quot;"

Rounding method, one of "round", "floor" or "ceil"

Example

Default precision is 0 and rounding method "round"

    roundTo(1.23) // Will yield 1
    roundTo(1.5) // Will yield 2

Positive precision allows more decimals, negative rounds to tens

    roundTo(1.23, 1) // Will yield 1.2
    roundTo(12.3, -1) // Will yield 10

"ceil" will round up and "floor" will round down

    roundTo(1.23, 0, 'ceil') // Will yield 2
    roundTo(1.8, 0, 'floor') // Will yield 1

sleep(duration)

Sleep for the given amount of time

Kind: global function Summary:

Sleep for the given amount of time

.
Param Type Description
duration number

Sleep time in milliseconds

sortObject(input)

Sort an object by key or an array by its values

Kind: global function Summary:

Sort an object by key or an array by its values

.
Param Type Description
input *

Any input

Example

sortObject({ foo: 'bar', bar: 'foo' }) // will output {"bar": "foo", "foo": "bar"}
    sortObject([3, 2, 1]) // will output [1, 2, 3]

splitStringIntoChunks(input, length, separator, [left]) ⇒ string

Split string into chunks of the given size and merge them with the given separator string. Default chunk grouping order is from right to left.

Kind: global function Summary:

Split string into chunks of the given size and merge them with the given separator string.

Returns: string -

String split into chunks with the given separator

Param Type Description
input string

Input string

length number

Chunk length

separator string

Separator between the chunks

[left] boolean

Start chunks from left to right instead of right to left

Readme

Keywords

none

Package Sidebar

Install

npm i @vapaaradikaali/helpers.js

Weekly Downloads

11

Version

0.41.3

License

ISC

Unpacked Size

384 kB

Total Files

133

Last publish

Collaborators

  • atmosphear