juliutils
TypeScript icon, indicating that this package has built-in type declarations

1.1.3 • Public • Published

My personal collection of utility functions.

API

Table of Contents

juliutils

General purpose utility functions.

yes

Interprets whether a string means yes or not.

Parameters

Examples

yes('yes');
// true
yes('yup');
// true
yes('no');
// false

Returns Boolean No?

no

Interprets whether a string means no or not.

Parameters

Examples

no('no');
// true
no('nope');
// true
no('yes');
// false

Returns Boolean Yes?

withinNDaysOf

Checks whether two dates are within N days of each other.

Parameters

  • date1 Date First date.
  • date2 Date Second date.
  • days Number Number of days. (optional, default 1)

Returns Boolean Whether the two dates are within N days of each other.

printDate

Prints a date as a string in mm/dd/YYYY format.

Parameters

  • date Date Date to print.
  • separator String Separator used between dates. (optional, default '/')

Returns String String of date.

printCSVDate

Prints a date for a CSV file in YYYY/mm/dd format.

Parameters

  • date Date Date to print.

Returns String String of date to be inserted into a CSV cell.

omitEmpty

Omits keys with values that are empty from object.

Parameters

  • obj Object Object to omit values from.

Returns Object Object with null, undefined, or empty string values omitted.

uniq

Gets unique values from array.

Parameters

Returns Array Array with unique values.

Meta

  • since: 1.0.5 - The filter parameter was added.

difference

Gets difference between two arrays.

Parameters

  • arr1 Array First array.
  • arr2 Array Second array.

Returns Array Array with values removed.

partition

Partitions array based on conditions.

Parameters

Returns Array Partitioned array.

mode

Returns mode from array of numbers.

Parameters

  • numbers Array Array of numbers.

Returns (Number | undefined) Mode of numbers, or undefined if array is empty.

groupBy

Groups an array by value from key.

Parameters

Returns Object Object of groups.

indexBy

Indexes an array by value from key.

Parameters

Returns Object Indexed object.

arrAverage

Averages an array of values.

Parameters

  • numbers
  • values Array Array of values.

Returns Number Average of all values in array.

flatten

Flattens an array.

Parameters

  • arr Array Array to flatten.
  • deep Boolean? Recursive flatten?

Returns Array Flattened array.

compact

Removes all falsy values from an array.

Parameters

  • arr Array Array to compact.

Returns Array Compacted array.

flattenCompact

Flattens and compacts array.

Parameters

  • arr Array Array to flatten and compact.
  • deep Boolean? Whether the array should be flattened recursively.

Returns Array Flattened and compacted array.

range

Creates a range of numbers from start to stop, not including the stop value.

Parameters

  • start Number Number to start at.
  • stop Number Number to stop at.

Examples

range(1, 3);
// [1, 2]

Returns Array Array of numbers in range.

randomString

Create a random string.

Parameters

  • length Number Length of string. (optional, default 10)

Returns String Random string.

pickKeys

Picks keys from an object.

Parameters

  • obj Object Object to pick values from.
  • keys ...(string | Array<string>) Keys to pick. Keys can also be contained within an array.

Returns Object Object with picked keys.

createTree

Creates a tree within an object.

Modifies the original object.

Parameters

  • obj Object Object to build tree on.
  • tree Array Tree to build on 'obj'.
  • ender any? Any value to use as the end value.

Examples

createTree({}, ['fruit', 'color'], 'red');
// { fruit: { color: 'red' } }

Returns Object The same object passed as 'obj'.

transformObj

Recursively transforms key/values in object, including array values.

Also can act as a basic deep clone method.

Parameters

  • obj Object Object to transform.
  • transforms Object Object containing transformation functions. (optional, default {})
  • level Number Level of recursion, passed as the 2nd argument to a transform function. (optional, default 0)

Examples

transformObj({
    apple: 'Green',
    orange: 'Orange',
    cherry: {
        color: 'Red'
    }
}, {
    keys: (key, level) => {
        return level === 0 ? `fruit_${key}` : key;
    },
    values: (value) => {
        return value.toUpperCase();
    }
});
// { fruit_apple: 'GREEN', fruit_orange: 'ORANGE', fruit_cherry: { color: 'RED' } }

Returns Object Transformed object.

clone

Recursively clones an object's values.

This works for simple objects containing simple types like strings, number, and dates. Complex objects containing state may have issues..

Parameters

Returns Object Cloned object.

Meta

  • since: 1.0.7 - method clones more than just primitive values

arrToKeys

Creates an object from an array of keys.

Parameters

  • keys Array Array of keys.
  • value any? Value to assign to each key.

Examples

arrToKeys(['a', 'b'], 0);
// { a: 0, b: 0 }

Returns Object Object with keys mapped from array.

isNumber

Checks if a value is a number or not.

Parameters

  • value any Value to test.

Returns Boolean Whether the value is a number or not.

truncate

Truncates a string with option to add trail at end.

Parameters

  • str String String.
  • length Number Length to trim to.
  • trail String Trailing characters. (optional, default '')

Returns String Truncated string.

basicPlural

Chooses a form based on number.

Parameters

Returns String Form based on value.

valuesAsKeys

Assigns values of object as keys.

Parameters

Examples

valuesAsKeys({ a: 'apple' });
// { a: 'apple', 'apple': 'a' }

Returns Object Object with values mapped as keys.

escapeCSV

Escapes a cell value in CSV.

Parameters

Returns String Escaped string.

escapeRegExp

Escapes a string in RegExp.

Parameters

Returns String Escaped string.

escapeHTML

Escapes text to use as strings in HTML format.

Parameters

Returns String Escaped text.

takeNRandom

Picks a number of items from an array at random.

Parameters

  • arr Array Array to pick items from.
  • num Number Number of items to take.

Examples

takeNRandom([1, 2, 3, 4, 5], 3);
// [3, 5, 2]

Returns Array N number of values taken from array at random.

promiseSeries

Executes a series of Promises in sequence.

Parameters

  • funcs Array An array of functions where each function returns a Promise.

Examples

const urls = ['/url1', '/url2', '/url3'];
promiseSeries(urls.map(url => () => $.ajax(url)))
    .then(response => console.log(response));

Returns Promise<Array> Promise that resolves with an array containing results from each resolved Promise in series.

delayPromise

Delays a promise.

Parameters

  • time Number Time in ms to delay.
  • value any? Value to pass to resolve.

Returns Promise Promise that resolves after the given delay.

Meta

  • since: 1.0.1 - The time parameter comes first.

sleep

Sleeps for a set amount of time.

Parameters

  • time number? Time in ms to delay.

Returns Promise Promise that resolves after the given delay.

deepEqual

Checks if A is equal to B.

Parameters

  • a any Value A.
  • b any Value B.

Returns Boolean Whether A is equal to B.

without

Removes elements from an object or array by value.

Parameters

  • item (Object | Array) Item to process.
  • value (any) Value or array of values to remove from item.

Examples

without({ name: 'cat', color: 'orange' }, ['orange']);
// { name: 'cat' }
without(['cat', 'orange'], ['orange']);
// ['cat']
// or using just a string
without(['cat', 'orange'], 'orange');
// ['cat']

Returns (Object | Array) Object or array without the given values.

shorten

Shortens a sentence-like string without cutting off the final word.

Parameters

  • str String String to shorten.
  • maxLength Number Max length of string.
  • seperator (String | Regexp) Word seperator. If a RegExp is given, words will be seperated by a space. (optional, default ' ')

Examples

shorten('that cat is fat', 8);
// 'that cat'
// custom seperator
shorten('123x456x789', 8, 'x');
// '123x456'

Returns String Shortened string.

roundN

Rounds number to N decimal places.

Parameters

  • value Number Value to round.
  • places Number Places to round to.

Examples

roundN(4.344, 1)
// 4.3

Returns Number Rounded number.

closest

Gets the closest value to a given number in the array.

Parameters

  • arr Array Array of anything. If comparing non-numbers, a key should be given.
  • num Number Number to be closest to.
  • key (String | function) Key or method to extract value from each item.

Examples

// gets the closest value in array to 6
closest([1, 5, 9], 6);
// 5
// gets the city with the closest population to 11m
closest([
    {
        name: 'New York',
        population: 8.6
    },
    {
        name: 'Tokyo',
        population: 13.8
    },
    {
        name: 'Mumbai',
        population: 12.4
    }
], 11, 'population');
// { name: 'Mumbai', population: 12.4 }

Returns any Closest value in array.

chainSort

Sorts an array in a chain.

Parameters

Examples

chainSort([1, 5, 9, 4, 2], [
    (a, b) => {
        return a - b;
    }
]);
// [1, 2, 4, 5, 9]

Returns Array Sorted array.

Readme

Keywords

none

Package Sidebar

Install

npm i juliutils

Weekly Downloads

1

Version

1.1.3

License

MIT

Unpacked Size

63.1 kB

Total Files

6

Last publish

Collaborators

  • juliarose