@ideam/common
v1.1.0
Published
Common utilities and functions for node/typescript application
Downloads
22
Readme
Node.js Common
A set of common utilities that can be used accross node.js/typescript applications
Builder
An implementation of a builder pattern for node.js, which works on classes, array or objects
Array Builder
Allows you create and modify and array
import { Builder } from '@ideam/common';
let y = Builder.from(['1','2'])
.addIf(someCondition, '3')
.addIf(someCondition, '3')
.replace('4', value => Number(value) < 1)
.build()
Object Builder
Modify a javascript object
import { Builder } from '@ideam/common';
let y = Builder.from({name: 'a', age: 12})
.addIf(showGender, 'gender', 'male')
.removeIf(!showAge, 'age')
.build()
Class Builder
Allows you not use constructor arguments but instead use a strongly types builder. Usefull, where you have any constructor arguments where some of which are optional so ordering of arguments becomes messy. Instead of placing the argument in the contructor you can decorate all arguments with @BuildProp() these can then be set in the builder before the class is instantiated. The afterBuilt hook can be used to implement any logic that would otherwise be in the constructor
import { Builder, BuildProp, Buildable } from '@ideam/common';
@Buildable()
class MyClass extends Buildable {
@BuildProp(true)
name: string
@BuildProp(true)
age:: number;
@BuildProp(false, 'male')
gender: string;
afterBuilt() {
// do something that you would to in the constructor
}
}
let y = Builder.from(MyClass)
.name('a')
.age(12)
.build()
Annotations
A standard way of defining strongly typed metadata on an object/property. Common used with working with typescript decorators
import { Annotation, Class} from '@ideam/common';
// Define an annotation
const MyAnnotation = Annotation<string>('myAnnotationKey');
const MyCustomDecorator = (name: string) => (target: Class<any>) => {
// use annotation to set metadata, typically in decorators like this example
Annotation.set(target, name)
}
// apply decorator which sets the annoation
@MyCustomDecorator('some-name')
class MyClass {}
// Get the value of the annotation for a class
const value = MyAnnotation.get(MyClass); // 'some-name'When you define the type as an array you can use the push or replace methods
import { Annotation } from '@ideam/common';
const MyAnnotation = Annotation<string[]>('myAnnotationKey')
class MyClass {}
MyAnnotation.push(MyClass, 'a')
MyAnnotation.replace(MyClass, 'b', item => item === 'a')Utility Functions
Arrays
asyncMap- similiar to Array.map but for each functionsalidateUniqueValues- ensures no duplicates exist in a list based on a comparitor functionremoveDuplicates- removes similiar items from a list based on a comparitor functionsgetDuplicate- finds similiar items from a list based on a comparitor functionsarrayValue- ensures a value is an array
import { arrayValue } from '@ideam/common';
let a = arrayValue(1) = // equals [1]
let b = arrayValue(["a"]) // equals ["a"]
let c = arrayValue(null) // equals []removeWhere- removes items from list that match conditionreplaceWhere- replaces items in a list that
Dictionary
For working with key-value pairs, these functions can be done calling the dictionary function which takes in object as its argument. Maps similiar functions to the native array
- filter - filters out the keys based on a condition
- map - changes the value of each item in the dictionary
- forEach - iterates over all items
- toArray - returns an array with each item containing the key and value
import { dictionary } from '@ideam/common';
const data = {
'key1': 1,
'key2': 2
}
// returns a new dictionary with each value incremented by one
let a = dictionary(data).map((val, key, i) => val + 1)
// returns new dictionary but only with the fields that map the filter condition
let b = dictionary(data).filter((item, key) => key.endsWith('1'))
// returns an array with the structure { key: string, value: T}
let c = dictionary(data).toArray()
// performs some function for each item in dictionary
dictionary(data).forEach((val, key, i) => val + 1) General
General helper functions
epochSeconds- Returns the current epoch time in secondsepochMillis- Returns the current epoch time in millisecondsisNothing- Checks whether the provided item is null or undefined.getClass- Returns the prototype of the provided value.getConstructor-Returns the constructor of the provided valuekeys- Returns an array of the keys of the provided object.values- Returns an array of the values of the provided object.clone- Creates a deep copy of an object or arraytoDictionary- Converts an array of items into a dictionary using the provided id function, which becomes they key of the dictionary.merge- Merges two objects together, recursively.uuid- Generates a UUID v4 stringtruncate- truncates the provided text to the specified length, adding an ellipsis if necessary.
Type Functions
used for working with types in code
isConstructor- Checks whether provided argument is a class constructorisObjectWithProperties- checks if argument is an object and if that object contains one or more propertiesisObject- checks if the argument is an object
Types
Some common generic typescript types
Class<T>- a class referenceInstanceType<T>- the instance created by the class referenceDeepPartial<T>- All the properties of an object become optional, applies recursivelyDeepRequired<T>- All the properties of an object become not optional, applies recursively
