js-code-utils v2.3.5
JS Code Utilities
Various javascript utilities
Install
npm install --save js-code-utils
Usage
const codeUtils = require('js-code-utils');
const escapedString = codeUtils.escapeString('string');
//or you can destructure
const {delay} = require('js-code-utils');
await delay(2500);
ArrayUtils
asyncForEach
- Purpose: Iterates asynchronously over an array with the passed callback function to run for each iteration. You can also pass a function to run on completion as the third parameter.
- Returns: Promise - an array of whatever was returned from each iteration.
Example:
const {asyncForEach} = require('js-code-utils'); const axios = require('axios'); const functionToRunForEachItteration = async (currentValue, index) => { let response = await axios.get(currentValue.url); response.body.companyName = currentValue.company; return response.body; }; const functionToRunWhenDone = whatWasReturnedFromEachItteration => { console.log(whatWasReturnedFromEachItteration); }; const asyncCallsToMake = [ { url: 'http://someSite.com/user/1234', company: 'Some Company' }, { url: 'http://someSite.com/user/5678', company: 'Some Company' } ]; const asyncResponses = await asyncForEach(asyncCallsToMake, functionToRunForEachItteration, functionToRunWhenDone);
OtherUtils
checkFieldValueRequirements
- Purpose: Test the values of an object to match your requirements. Pass an object with the values you want to test. You can pass an optional
options
parameter withdepth
(integer) with how many levels deep you want to test. - Returns: Object with
erroredFields
(array with fields that didn't pass) andsuccess
(boolean). Example:
const {checkFieldValueRequirements, variableTypes} = require('js-code-utils'); checkFieldValueRequirements({ test: { enum: ['test', 'one', 'two'], // enum: ['test', 'one', 'two'], type: variableTypes.STRING, value: 'test' }, test2: { required: true, type: variableTypes.OBJECT, value: { deep1: { type: variableTypes.OBJECT, value: { deep2: { type: variableTypes.NUMBER, value: 'something' } } }, deep2: { type: variableTypes.BOOLEAN, value: true } } }, test3: { required: true, type: variableTypes.ARRAY, value: [ { thisThing: {type: variableTypes.number, value: '10'} } ], valuesType: variableTypes.OBJECT } }, { depth: 310 }); // returns // { // erroredFields: [ // 'test2.deep1.deep2 (value !== type)', // 'test3[0].thisThing (value !== type)' // ], // success: false // }
- Purpose: Test the values of an object to match your requirements. Pass an object with the values you want to test. You can pass an optional
delay
- Purpose: Delays code for
timeInMilliSeconds
- Returns: Promise.
Example:
const {delay} = require('js-code-utils'); await delay(timeInMilliSeconds);
- Purpose: Delays code for
Dispatcher
- Purpose: Dispatch events to and from different places in your code.
- Returns: Dispatcher instance.
Example:
const {Dispatcher} = require('js-code-utils'); const messenger = new Dispatcher(); messenger.on('someEvent', data => {console.log(data);}); messenger.dispatch('someEvent', {youCan: 'pass an object'}); messenger.dispatch('someEvent', 'or whatever you want');
Timer
- Purpose: Start a timer counting. You can pass an
options
parameter to the class withdisplayLog
to show the counter or not. - Returns: Timer instance.
Example:
const {Timer} = require('js-code-utils'); const timer = new Timer({displayLog: false}); timer.pause(); //pauses the timer (clears the interval) - can resume with timer.start() timer.reset(); //resets the timer to 00:00:00 timer.start(); //starts the timer timer.stop(); //stops the timer (clears the interval, resets the timer, and clears the line)
- Purpose: Start a timer counting. You can pass an
writeCsvFileToJsonFile
- Purpose: Writes a given csv file to a given path in json format. If you do not want to check the type of the given csv data pass false as the third parameter. Otherwise the type will be checked. If you want to convert a field to a specific type, the 4th parameter takes in an object with the field name as the key, and the type (all in caps) as the value.
- Returns: Promise.
Example:
const {writeCsvFileToJsonFile, variableTypes} = require('js-code-utils'); await writeCsvFileToJsonFile( 'csvFilePath.csv', 'destinationJsonFilePath.json', false, // check the type or not { field1: variableTypes.BOOLEAN, field2: variableTypes.NUMBER, field3: variableTypes.STRING, field4: variableTypes.DATE } );
StringUtils
checkMixedWords
- Purpose: Check the similarity of two strings. Will check the similarity of the strings even if the words are not in the same order. Case insensitive.
- Returns: Boolean - depending on if the two strings similarity is above the passed
threshold
; Example:
const {checkMixedWords} = require('js-code-utils'); const string1 = 'This is the first string'; const string2 = 'Is this the first string'; const threshold = 0.8; const match = checkMixedWords(string1, string2, threshold); // true
compareString
- Purpose: First checks with the similarity function and if it is not under the threshold it checks with checkMixedWords. Case insensitive.
- Returns: Boolean - depending on if the two strings similarity is above the passed
threshold
; Example:
const {compareString} = require('js-code-utils'); const string1 = 'This is a string'; const string2 = 'This is not a similar string'; const threshold = 0.8; const match = compareString(string1, string2, threshold); // false
editDistance
- Purpose: Checks the cost of changes that had to be made to make the two strings similar.
- Returns: Integer - cost of change.
Example:
const {editDistance} = require('js-code-utils'); const changes = editDistance('string1', 'string2'); // 1
escapeRegExp
- Purpose: Escape all regex characters and returns the escaped string.
- Returns: String escaped.
Example:
const {editDistance} = require('js-code-utils'); const escaped = escapeRegExp('asdf\s\+'); // asdfs+
escapeString
- Purpose: Escapes the string with only letters, numbers, spaces and a few special characters (_+-:)
- Returns: String escaped.
Example:
const {escapeString} = require('js-code-utils'); const escaped = escapeString('adsf1234_/asdf..5%@'); // a::dsf12 +- 34_asdf5
nthIndexOf
- Purpose: Find the index of a pattern to match in the passed string at which occurance;
- Returns: Integer
Example:
const {nthIndexOf} = require('js-code-utils'); const string = 'string thing str here is this string'; const pattern = 'str'; const occurance = 2; const index = nthIndexOf(string, pattern, occurance); // 13
replaceAll
- Purpose: Replace all instances of a specified string in a string with a string and returns the updated string.
- Returns: String.
Example:
const {replaceAll} = require('js-code-utils'); const string = 'Here is the string thing'; const whatToReplace = 'ing'; const whatToReplaceWith = 'changed'; const replaced = replaceAll(string, whatToReplace, whatToReplaceWith); // Here is the strchanged thchanged
similarity
- Purpose: Returns the similarity percentage of two strings. Case insensitive.
- Returns: Number.
Example:
const {similarity} = require('js-code-utils'); const sim = similarity('one', 'ones'); // 0.75
toCamelCase
- Purpose: Convert string to camel case.
- Returns: String.
Example:
const {toCamelCase} = require('js-code-utils'); const camelCased = toCamelCase('I want this string camel cased'); // iWantThisStringCamelCased
uppercaseString
- Purpose: Uppercase all words in a string and returns updated string.
- Returns: String.
Example:
const {uppercaseString} = require('js-code-utils'); const upper = uppercaseString('I want this upper cased'); // I Want This Upper Cased
VariableUtils
getType
- Purpose: Determine the type of the passed value.
- Returns: String.
Example:
const {getType} = require('js-code-utils'); const match = getType('This is a string'); // STRING
isArray
- Purpose: Determine if the passed value is an array.
- Returns: Boolean.
Example:
const {isArray} = require('js-code-utils'); const match = isArray([]); // true
isBoolean
- Purpose: Determine if the passed value is a boolean.
- Returns: Boolean.
Example:
const {isBoolean} = require('js-code-utils'); const match = isBoolean(true); // true
isDate
- Purpose: Determine if the passed value is a date.
- Returns: Boolean.
Example:
const {isDate} = require('js-code-utils'); const match = isDate(new Date()); // true
isError
- Purpose: Determine if the passed value is an error instance.
- Returns: Boolean.
Example:
const {isError} = require('js-code-utils'); const match = isError(new Error('this is an error')); // true
isFunction
- Purpose: Determine if the passed value is a function.
- Returns: Boolean.
Example:
const {isFunction} = require('js-code-utils'); const match = isFunction(() => {}); // true
isObject
- Purpose: Determine if the passed value is an object.
- Returns: Boolean.
Example:
const {isObject} = require('js-code-utils'); const match = isObject({}); // true
isNull
- Purpose: Determine if the passed value is null.
- Returns: Boolean.
Example:
const {isNull} = require('js-code-utils'); const match = isNull(null); // true
isNumber
- Purpose: Determine if the passed value is a number.
- Returns: Boolean.
Example:
const {isNumber} = require('js-code-utils'); const match = isNumber(42); // true
isRegExp
- Purpose: Determine if the passed value is a regular expression.
- Returns: Boolean.
Example:
const {isRegExp} = require('js-code-utils'); const match = isRegExp(/test/g); // true
isString
- Purpose: Determine if the passed value is a string.
- Returns: Boolean.
Example:
const {isString} = require('js-code-utils'); const match = isString('string'); // true
isSymbol
- Purpose: Determine if the passed value is a symbol.
- Returns: Boolean.
Example:
const {isSymbol} = require('js-code-utils'); const match = isSymbol(Symbol()); // true
isUndefined
- Purpose: Determine if the passed value is undefined.
- Returns: Boolean.
Example:
const {isUndefined} = require('js-code-utils'); const obj = {test: 'this'}; const match = isUndefined(obj.test2); // true
variableTypes
- Purpose:
- Returns: Object with available variable types
Example:
const {variableTypes} = require('js-code-utils'); console.log(variableTypes.STRING); //STRING
Breaking Changes
v2.0.0
- All functions are at the root level. You no longer have to call let StringUtils = require('js-code-utils').StringUtils; and then StringUtils.uppercaseString('string'). You can just import like so: let codeUtils = require('js-code-utils'); and then codeUtils.uppercaseString('string');
- PrototypeUtils no longer exists. All the functionality for the prototypes has been moved to their own functions rather than modifying the prototypes:
Array:
- asyncForEach
String:
- escapeString
- nthIndexOf
- replaceAll
- toCamelCase
v1.0.1
- moved writeCsvFileToJsonFile to OtherUtils: no longer in ProcessCSV
Updates
v2.2.0
- add checkFieldValueRequirements to other utils
- update readme with all changes
v2.0.0
- moved all functions to top level access
- removed all prototype modification. will not use prototypes anymore.
v1.1.0
- added some useful prototypes for [array].asyncForEach and [string].nthIndexOf and [string].toCamelCase
v1.0.2
- update README.md to include the getType function in VariableUtils as well as that the OtherUtils delay and writeCsvFileToJsonFile return a promise.
v1.0.1
- required csvtojson and fs in OtherUtils (forgot to when moving writeCsvFileToJsonFile to OtherUtils)
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago