Skip to content

juliarose/juliutils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

My personal collection of utility functions.

API

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 YYYY/mm/dd 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

Returns Object<string, any> 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.

valueList

Type: Object<(string | number), boolean>

difference

Gets difference between two arrays.

Parameters

  • arr1 Array<any> First array.
  • arr2 Array<any> Second array.

Returns Array<any> Array with values removed.

partition

Partitions array based on conditions.

Parameters

  • arr Array<T> Array.
  • method function (T): boolean Function to satisfy.

Returns [Array<T>, Array<T>] Partitioned array.

result

Type: [Array<T>, Array<T>]

average

Averages an array of numbers.

Parameters

Returns number Average of all numbers in array.

average

Averages an array of numbers.

Parameters

Returns number Average of all numbers in array.

Meta

  • deprecated: Since version 1.1.4 - Use average instead.

mean

Gets the mean of an array of numbers.

Parameters

Returns number Average of all numbers in array.

median

Gets the median from an array of numbers.

Parameters

Returns (number | undefined) Median of numbers, or undefined if array is empty.

mode

Gets mode from array of numbers.

Parameters

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

groupBy

Groups an array by value from key.

Parameters

Returns Object<string, Array<T>> Object of groups.

indexBy

Indexes an array by value from key.

Parameters

Returns Object<string, T> Indexed object.

flatten

Flattens an array.

Parameters

Returns Array<any> Flattened array.

Type: Array<(Array<any> | any)>

shallowFlatten

Flattens an array (shallow).

Parameters

Returns Array<(Array<any> | any)> Flattened array.

Type: Array<(Array<any> | any)>

compact

Removes all falsy values from an array.

Parameters

  • arr Array<any> Array to compact.

Returns Array<any> Compacted array.

flattenCompact

Flattens and compacts array.

Parameters

  • arr Array<(Array<any> | any)> Array to flatten.
  • deep boolean? Whether to deeply flatten array.

Returns Array<(Array<any> | any)> Flattened and compacted array.

Meta

  • deprecated: Since version 1.1.4 - Use flatten and compact separately.

range

Creates a range of numbers from start to stop, non-inclusive.

Parameters

  • start number Number to start at.
  • end number Number to end 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'.
  • tail any? Any value to use as the tail.

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.
    • transforms.keys function (string, number): any? Function for transforming keys from 'obj'.
    • transforms.values function (any, number): any? Function for transforming values from 'obj'.
  • 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

Type: object

arrToKeys

Creates an object from an array of keys.

Parameters

Examples

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

Returns Object<(string | number), any> 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.

pluralize

Chooses a form based on number.

Parameters

Returns string Form based on value.

basicPlural

Chooses a form based on number.

Parameters

Returns string Form based on value.

Meta

  • deprecated: Since version 1.1.4 - Use pluralize instead.

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<any> 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<any> N number of values taken from array at random.

getLow

Picks a number of items from an array at random.

Faster when picking a lower amount of numbers from array.

Parameters

  • arr Array<any> Array to pick items from.
  • num number Number of items to take.

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

getHigh

Picks a number of items from an array at random.

Faster when picking a larger amount of numbers from array.

Parameters

  • arr Array<any> Array to pick items from.
  • num number Number of items to take.

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

promiseSeries

Executes a series of Promises in a series, where each Promise resolves before the next function is called.

Parameters

  • funcs Array<(function (): Promise<any>)> 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<any>> Promise that resolves with an array containing results from each resolved Promise in series.

concat

Concatenates an array to a list.

Parameters

  • list Array<any> List to concatenate.

Returns function (Array<any>): Array<any> Concatenated list.

promiseConcat

Concatenates resolves from previous functions with resolves from current function.

Parameters

  • func function (): Promise<any> Function that returns a Promise.

Returns function (Array<any>): Promise<any> Function that returns a Promise.

promiseReduce

Reduces an array of functions that return Promises in series.

Parameters

  • accum Promise<any> Accumulator Promise, this will add a value to the accumulator for each function in the series.
  • func function (): Promise<any> Function that returns a Promise.

Returns Promise<Array<any>> Promise that resolves with the result of the last function in the 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 T Value A.
  • b T Value B.

Returns boolean Whether A is equal to B.

getPropNames

Gets a list of property names of an object.

Parameters

Returns Array<string> Property names of object.

sameValues

Checks if all values are the same in both objects.

Parameters

Returns boolean Whether all values are the same in both objects.

isObject

Checks if a value is an object.

Parameters

  • value any Value to check.

Returns boolean Whether the value is an object.

without

Removes elements from an object or array by value.

Parameters

  • item (Object | Array<any>) Item to process.
  • value (any | Array<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<any>) Object or array without the given values.

doesNotMatch

Checks if an element does not match the value.

Parameters

  • element any Element to check.

Returns boolean Whether the element does not match the value.

itemDoesNotHaveKey

Checks if an item does not have a key.

Parameters

Returns boolean Whether the item does not have the key.

recomposeItem

Takes values to remove from 'item' and adds them to a new object.

Parameters

  • newItem Object New object to add values to.
  • key string Key to add to new object.

Returns Object New object with values added.

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<T> Array of anything. If comparing non-numbers, a key should be given.
  • num number Number to be closest to.
  • key (string | function (T, number): number)? 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 11e5
const cities = [
    {
        name: 'New York',
        population: 86e5
    },
    {
        name: 'Tokyo',
        population: 138e5
    },
    {
        name: 'Mumbai',
        population: 124e5
    }
];

closest(cities, 11e5, 'population'); // { name: 'Mumbai', population: 12.4 }

Returns (T | undefined) Closest value in array.

Type: T

Type: number

chainSort

Sorts an array in a chain.

Parameters

  • arr Array<T> Array to sort.
  • funcs Array<(function (T, T): number)> Array of functions.

Examples

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

Returns Array<T> Sorted array.

About

My personal utility function library

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published