2.3.0 • Published 3 years ago

@ramster/general-tools v2.3.0

Weekly downloads
2
License
MIT
Repository
gitlab
Last release
3 years ago

npm node pipeline Coverage Status

npm npm

Ramster General Tools

A general toolkit module that contains various utility methods. Can be used both in the browser and in node. It's mostly meant as a companion to ramster and ramster-ui, but works just as fine on its own.

Table Of Contents

  • Getting Started
  • arraySort - Sorts an array of objects by a list of inner properties. Supports SQL-style sorting by multiple field names and directions.
  • changeKeyCase - Changes the case of all keys in an object or string and its children between loweCamelCase and UpperCamelCase, based on the provided map.
  • checkRoutes - Checks whether a route exists in a list of HTTP routes. Supports ExpressJS-style route parameters, i.e. /users/item/:id.
  • decodeQueryValues - Recursively performs decodeURIComponent on an object or value and returns the decoded object.
  • emptyToNull - Takes an object or value and transforms undefined, null and empty strings to null. Recursively does so for objects without mutating the provided data.
  • findVertexInGraph - Finds a vertex in a graph, then returns it and its path.
  • flattenObject - Takes a deeply nested object and flattens it into top-level key-value pairs. Particularly suitable for turning nested objects into get params.
  • getNested - Extracts a value from a deeply nested object, for example foo.bar.0.baz from {foo: {bar: {baz: 'test'}}}.
  • setNested - Sets a value in a deeply nested object, for example foo.bar.0.baz in {foo: {bar: {baz: 'test'}}}.
  • stringifyNestedObjects - Takes a nested object and turns its non-Date, non-null object keys into stringified json keys, which can later be decoded by the decodeQueryValues method.

Getting Started

It's really simple - just do

npm i @ramster/general-tools 

and you're good to go. Both the "import" and "require" syntax are supported, so either of these are valid:

import {getNested} from '@ramster/general-tools'
const {getNested} = require('@ramster/general-tools')

arraySort

Sorts an array of objects by a list of inner properties. Supports SQL-style sorting by multiple field names and directions.

import {arraySort, IArraySortSortingDirections} from '@ramster/general-tools'

const arrayToBeSorted = [
	{firstName: 'John', lastName: 'Doe'},
	{firstName: 'Jane', lastName: 'Doe'},
	{firstName: 'Peter', lastName: 'Parker'},
	{firstName: 'Peter', lastName: 'parker'}
]
const sortedArray = arraySort(
	arrayToBeSorted,
	[
		{direction: IArraySortSortingDirections.Ascending, fieldName: 'firstName'},
		{direction: IArraySortSortingDirections.Descending, fieldName: 'lastName'}
	],
	{caseSensitive: true}
)
// this will give us:
// [
//     {firstName: 'Jane', lastName: 'Doe'}
//     {firstName: 'John', lastName: 'Doe'}
//     {firstName: 'Peter', lastName: 'parker'}
//     {firstName: 'Peter', lastName: 'Parker'}
// ]
console.log(sortedArray)

Method parameters

parametertyperequireddescription
arrayArray(any)yesThe array to be sorted.
orderByArray(IArraySortOrderBy)yesThe ordering options - the fields and directions to sort the array by (see below).
optionsIArraySortOptionsnoAdditonal ordering options, such as case sensitivity (see below).

IArraySortOrderBy details

parametertyperequireddescription
directionIArraySortSortingDirectionsyesCan be IArraySortSortingDirections.Ascending or IArraySortSortingDirections.Descending.
fieldNamestringyesThe object field to sort by.

IArraySortOptions details

parametertyperequireddescription
caseSensitivebooleannoWhether the sorting should be case sensitive when sorting strings. If not set to true, strings will be lowercased before being sorted.

changeKeyCase

Changes the case of all keys in an object or string and its children between loweCamelCase and UpperCamelCase, based on the provided map.

import {changeKeyCase} from '@ramster/general-tools'

const keyCaseMap = {ProductId: 'productId', UserId: 'userId'},
	inputObject = {ProductId: 10, UserId: 15},
	inputString = '?ProductId=10&UserId=15'

const ouputObject = changeKeyCase(inputObject, keyCaseMap),
	outputString = changeKeyCase(inputString, keyCaseMap)

// this will give us:
// {productId: 10, userId: 15}
console.log(outputObject)

// this will give us:
// '?productId=10&userId=15'
console.log(outputString)

Method parameters

parametertyperequireddescription
keyMapObject - {inputKey: string: string}yesThe map of keys to be converted, i.e. {statusId: 'StatusId', productId: 'ProductId'} or {StatusId: 'statusId', ProductId: 'productId'}.
inputstring or ObjectyesThe input string or object.

checkRoutes

Changes the case of all keys in an object or string and its children between loweCamelCase and UpperCamelCase, based on the provided map.

import {checkRoutes} from '@ramster/general-tools'

const routes = [
	'/main',
	'/api/:component/list'
]
const firstResult = checkRoutes('/api/users/list', routes),
	secondResult = checkRoutes('/foo/bar', routes)
// this will give us:
// true
console.log(firstResult)

// this will give us:
// false
console.log(secondResult)

Method parameters

parametertyperequireddescription
routestringyesThe route to be checked.
routesstringyesThe array of routes to check in.

decodeQueryValues

Recursively performs decodeURIComponent on an object or value and returns the decoded object. Additionally, if an object is provided, any key that starts with "json" will be parsed using JSON.parse().

import {decodeQueryValues} from '@ramster/general-tools'

const inputObject = {
	foo: '%2Fbar',
	number: '15',
	boolean: 'true',
	_json_test: '{"key1": "value1", "key2": "35", "key3": "false"}'
}
const firstResult = decodeQueryValues(inputObject),
	secondResult = decodeQueryValues(inputObject, {castTrueAndFalseToBoolean: true, parseNumbersToFloat: true)
// this will give us:
// {
//     foo: '/bar',
//     number: '15',
//     boolean: 'true',
//     test: {
//         key1: 'value1',
//         key2: '35',
//         key3: 'false'
//     }
// }
console.log(firstResult)

// this will give us:
// {
//     foo: '/bar',
//     number: 15,
//     boolean: true,
//     test: {
//         key1: 'value1',
//         key2: 35,
//         key3: false
//     }
// }
console.log(secondResult)

Method parameters

parametertyperequireddescription
inputanyyesThe object or value to be decoded.
optionsIDecodeQueryValuesOptionsno(see below) Flags for additonal processing to be performed on the input, such as casting strings to booleans and parsing string numbers to float

IDecodeQueryValuesOptions details

parametertyperequireddescription
castTrueAndFalseToBooleanbooleannoWhether to attempt to cast "true" to true and "false" to false.
parseNumbersToFloatbooleannoWhether to attempt to parse string numbers to float.

emptyToNull

Takes an object or value and transforms undefined, null and empty strings to null. Recursively does so for objects without mutating the provided data.

import {emptyToNull} from '@ramster/general-tools'

// this will give us:
// {test: null, test3: null, test4: 'test'}
console.log(emptyToNull({test: null, test2: undefined, test3: '', test4: 'test'}))

Method parameters

parametertyperequireddescription
dataanyyesThe object or value to transform.

findVertexInGraph

Finds a vertex in a graph, then returns it and its path in the form of an IFindVertexInGraphReturnData object (see the last table below for more info on this object).

import {findVertexInGraph, IFindVertexInGraphSearchTypes} from '@ramster/general-tools'

// this will give us:
// {pathToVertex: '0.children.10.children.15', vertex: {data: 't1'}}
console.log(
	findVertexInGraph(
		{
			0: {
				children: {
					10: {
						children: {
							15: {data: 't1'}
						},
						data: 'test'
					}
				},
				data: 't0'
			}
		}
	),
	15,
	{searchType: IFindVertexInGraphSearchTypes.DFS}
)

Method parameters

parametertyperequireddescription
graphIFindVertexInGraphGraphyesThe graph to search in.
vertexIdstringyesThe id of the vertex to search for.
optionsIFindVertexInGraphOptionsyesMethod options, such as the search type (currently DFS only) - see below.

IFindVertexInGraphGraph details

parametertyperequireddescription
[vertexId: string]IFindVertexInGraphGraphVertexyesThe child vertices.

IFindVertexInGraphGraphVertex details

parametertyperequireddescription
childrenIFindVertexInGraphGraphnoThe child vertices in the form of a graph.
dataanynoA data object containing any data for the vertex.

IFindVertexInGraphOptions details

parametertyperequireddescription
currentVertexPathstringnoThe base path at the start of method executing. Automatically set by the method internally.
searchTypeIFindVertexInGraphSearchTypesyesThe type of search algorithm to use (current only DFS is supported).

IFindVertexInGraphSearchTypes enum details

valuedescription
DFSMakes the method run a depth-first search algorithm.

IFindVertexInGraphReturnData details

parametertypedescription
pathToVertexstring or nullThe path to the vertex, including the vertex id.
vertexIFindVertexInGraphGraphVertex or nullThe vertex itself, including its children and data.

flattenObject

Takes a deeply nested object and flattens it into top-level key-value pairs. Particularly suitable for turning nested objects into get params.

import {flattenObject} from '@ramster/general-tools'

let result = flattenObject(
	{
		testKey: [{testKey1: 'test'}, date],
		testKey2: 'test test test',
		testKey3: {testKey4: [null, 'test', {tq: 11}]},
		testKey4: null
	}
)
// this will give us:
// [
// 	{key: 'testKey[][testKey1]', value: 'test'},
// 	{key: 'testKey[]', value: date.toString()},
// 	{key: 'testKey2', value: 'test test test'},
// 	{key: 'testKey3[testKey4][]', value: 'test'},
// 	{key: 'testKey3[testKey4][][tq]', value: 11}
// ]
console.log(result)

Method parameters

parametertyperequireddescription
object{fieldName: string: any}yesThe object to flatten.

getNested

Extracts a value from a deeply nested object, for example foo.bar.0.baz from {foo: {bar: {baz: 'test'}}}.

import {getNested} from '@ramster/general-tools'

const inputObject = {
	foo: [
		{bar: 'test'},
		{bar: 'test2'},
		{bar: 'test'},
		{bar: 'test3'}
	]
}
const firstResult = getNested(inputObject, 'foo.0.bar'),
	secondResult = getNested(inputObject, 'foo.bar'),
	thirdResult = getNested(inputObject, 'foo.bar', {arrayItemsShouldBeUnique: true})
// this will give us:
// 'test'
console.log(firstResult)

// this will give us:
// ['test', 'test2', 'test', 'test3']
console.log(secondResult)

// this will give us:
// ['test', 'test2', 'test3']
console.log(thirdResult)

Method parameters

parametertyperequireddescription
parentanyyesThe object to retrieve the value from.
fieldstringyesThe path to the field.
optionsIGetNestedOptionsnoMethod executiom options, such as arrayItemsShouldBeUnique.

IGetNestedOptions details

parametertyperequireddescription
arrayItemsShouldBeUniquebooleannoIf a field in the path is an array, whether its values should be taken as-is or unique. (see the third example above)

setNested

Sets a value in a deeply nested object, for example foo.bar.0.baz in {foo: {bar: {baz: 'test'}}}.

import {setNested} from '@ramster/general-tools'

const inputObject = {
	foo: [
		{bar: 'test'},
		{bar: 'test2'},
		{bar: 'test'},
		{bar: 'test3'}
	]
}
const firstResult = setNested(inputObject, 'foo.0.bar', 'TEST'),
	secondResult = setNested(inputObject, 'foo.bar', 'TEST'),
	thirdResult = setNested(inputObject, 'foo.baz.bar', 'TEST')
// this will give us:
// true,
// {
//     foo: [
//         {bar: 'TEST'},
//         {bar: 'test2'},
//         {bar: 'test'},
//         {bar: 'test3'}
//     ]
// }
console.log(firstResult, inputObject)

// this will give us:
// true,
// {
//     foo: [
//         {bar: 'TEST'},
//         {bar: 'TEST'},
//         {bar: 'TEST'},
//         {bar: 'TEST'}
//     ]
// }
console.log(secondResult, inputObject)

// this will give us:
// false
console.log(thirdResult)

Method parameters

parametertyperequireddescription
parentanyyesThe object to retrieve the value from.
fieldstringyesThe path to the field.
valueanyyesThe value to set for the field.

stringifyNestedObject

Takes a nested object and turns its non-Date, non-null object keys into stringified json keys, which can later be decoded by the decodeQueryValues method.

import {stringifyNestedObject} from '@ramster/general-tools'

let date = new Date()
let result = stringifyNestedObject(
	{
		testKey: [{testKey1: 'test'}, date],
		testKey2: 'test test test',
		testKey3: {testKey4: [null, 'test', {tq: 11}]}
	}
)
// this will give us:
// {
// 	_json_testKey: '[{"testKey1":"test"},"2020-05-20T09:20:55.327Z"]',
// 	testKey2: 'test test test',
// 	_json_testKey3: '{"testKey4":[null,"test",{"tq":11}]}'
// }
console.log(result)

Method parameters

parametertyperequireddescription
data{key: string: any}yesThe object to stringify.
2.3.0

3 years ago

2.2.0

4 years ago

2.1.3

4 years ago

2.1.2

4 years ago

2.1.1

4 years ago

2.1.0

4 years ago

2.0.0

4 years ago