npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

juliutils

v1.1.3

Published

My personal collection of utility functions.

Downloads

3

Readme

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

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

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.