Pure Utilities

Library with helper methods.

Installation

npm install pure-utilities

Array


average  (array)

Returns the average of the array elements.

average(100, 200)
<= 150

comma  (array, number)

Returns a string created by joining array elements with comma and optional spaces.

comma([1, 2, 3], 2)
<= "1, 2, 3"

compact  (array, strict)

Returns an array with truthy values.

compact([0, 1, false, null, 2, "", 3])
<= [1,2,3]
compact([0, 1, null, 2, undefined, 3], false)
<= [0,1,2,3]

difference  (array, arrays)

Returns an array containing elements that do not occur in other arrays.

difference([1, 2, 3, 4, 5, 100], [100, 2, 3, 10, 31])
<= [1,4,5]

drop  (array, digit)

Removes elements of the array.

drop([1, 2, 3], 2)
<= [3]

duplicates  (array)

Returns an array containing repeated elements.

duplicates([1, 1, 2, 3, 5, 5])
<= [1,5]

eigth  (array)

Returns the eigth element of the array.

eigth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 8

fifth  (array)

Returns the fifth element of the array.

fifth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 5

first  (array)

Returns the first element of the array.

first([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 1

fourth  (array)

Returns the fourth element of the array.

fourth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 4

Returns the first element of the array.

head([1, 2, 3, 4, 5, 6])
<= 1

identifier  (array)

Returns a new unique identifier based on passed in identifiers.

identifier(["a"])
<= "b"

intersection  (arrays)

Returns an array containing elements common to all arrays that have been passed to the function.

intersection([1, 2, 3, 4, 5, 100], [100, 2, 3, 10, 31])
<= [2,3,100]

last  (array)

Returns the last element of the array.

last([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 10

median  (array)

Returns the median of the array elements.

median([6, 4, 2, 4, 4])
<= 4

ninth  (array)

Returns the ninth element of the array.

ninth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 9

nth  (array, position)

Returns the element located at the passed position. When position is negative it searches from the end of the array.

nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)
<= 3

partition  (array, predicate)

Returns an array of elements split into two groups, the first of which contains elements predicate returns truthy for, the second of which contains elements predicate returns falsey for. The predicate has one argument.

partition([{ user: "barney", active: false }, { user: "fred", active: true }, { user: "pebbles", active: false }], item => item.active)
<= [[{"user":"fred","active":true}],[{"user":"barney","active":false},{"user":"pebbles","active":false}]]

pluck  (array)

Returns a list of property values from an array of objects.

pluck([{ foo: "bar"}, { name: "baz"}], "name")
<= ["baz"]

rotate  (array, digit)

Rotates the elements on the array. When second parameter is negative, shifting starts from the end of the array.

rotate([1, 2, 3], 2)
<= [3,1,2]

sample  ()

Returns random element of the array.

sample([[1, 2, 3]])
<= 2

second  (array)

Returns the second element of the array.

second([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 2

seventh  (array)

Returns the seventh element of the array.

seventh([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 7

sixth  (array)

Returns the sixth element of the array.

sixth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 6

slice  (array, start, end)

Extracts a fragment of the array.

slice([1, 2, 3, 4,5, 6], 3, 5)
<= [4,5]

sum  (array)

Returns the sum of the array elements.

sum([3, 10, 2])
<= 15

symdifference  (arrays)

Returns an array of elements that are not part of intersection.

symdifference([1, 3, 4, 6, 7, 9], [3, 5, 6, 7, 8, 9])
<= [1,4,5,8]

take  (array, digit)

Takes elements from the array based on the second parameter, starting from the beginning of the array.

take([1, 2, 3, 4, 5, 6], 2)
<= [1,2]

tenth  (array)

Returns the tenth element of the array.

tenth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 10

third  (array)

Returns the third element of the array.

third([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
<= 3

union  (arrays)

Returns an array of unique values.

union([2], [1, 2])
<= [2,1]

unique  (array)

Returns an array with unique elements.

unique([1, 1, 2, 10, 2, 33])
<= [1,2,10,33]

Collection


append  (collection, indefinite, amount, of, arguments)

Adds arguments at the end of the collecion.

append("foo", "bar")
<= "foobar"
append([1, 2, 3], 4, 5, 6)
<= [1,2,3,4,5,6]

flatten  (collection)

Flattens n-dimensional array or n-depth object to a single depth array or object.

flatten([1, [2], [ [3, [ 4, [5] ] ] ] ])
<= [1,2,3,4,5]
flatten({"titles":{"index":"Buxus - Plants, seedlings, producer"}})
<= {"titles.index":"Buxus - Plants, seedlings, producer"}

occurences  (collection, string)

Returns the count of occurences of the string in the collection or string.

occurences(["foo", "foo", "bar"], "foo")
<= 2
occurences("foo foo bar", "foo")
<= 2

prepend  (collection, indefinite, amount, of, arguments)

Adds arguments at the beginning of the collection.

prepend("foo", "bar")
<= "barfoo"
prepend([1, 2, 3], 4, 5, 6)
<= [4,5,6,1,2,3]

reverse  (collection)

Reverses the elements of the collection.

reverse([1, 2, 3, 4])
<= [4,3,2,1]
reverse("foo")
<= "oof"

size  (collection)

Returns the size of the collection.

size(1, 2, 3, 4, 5)
<= 5
size({ a: 1, b: 2 })
<= 2

unflatten  (collection)

Converts properties of the object, which contain in the name dots(.), to multi-depth object.

unflatten({"errors.404.title":"Page not found"})
<= {"errors":{"404":{"title":"Page not found"}}}

Date


day  (date)

Returns the day of the month (from 1 to 31) of the passed date.

day(new Date(2018, 4, 28)
<= 28

format  (date, format)

Formats the date. First argument can be a Date object or a date string. By default date is parsed to the YYYY-MM-DD format.

format(new Date("2013/06/13"))
<= "13-06-2013"
format(new Date(2018, 4, 23), "MM")
<= "05"
format(new Date(2018, 4, 23), "DD/MM/YYYY")
<= "23/05/2018"
format(new Date("2013/06/09"))
<= "09-06-2013"

hours  (date)

Returns the hours of the day (from 0 to 23) of the passed date.

hours(new Date(2018, 4, 28, 10))
<= 10

isostring  (value)

Returns a string in simplified extended ISO format.

isostring("1460303444338")
<= "2016-04-10T15:50:44.338Z"

minutes  (date)

Returns the minutes of the hour (from 0 to 59) of the passed date.

minutes(new Date(2018, 4, 28, 10, 11))
<= 11

month  (date)

Returns the month (from 0 to 11) of the passed date.

month(new Date(2018, 4, 28))
<= 4

prettydate  (date, localization)

Returns a string, that contains: the name of weekday, day of the month (from 1 to 31), name of the month, and year (four digits for dates between year 1000 and 9999). Localization can be "en-En" or "pl-Pl", in other case function throws error. By default localization equals "en-En".

prettydate(new Date(2043, 9, 25))
<= "Sunday, 25th of October 2043"
prettydate(new Date(2018, 2, 21)
<= "Wednesday, 21st of March 2018"
prettydate(new Date(2018, 2, 21)
<= "środa, 21 marca 2018"

seconds  (date)

Returns the seconds of the minute (from 0 to 59) of the passed date.

seconds(new Date(2018, 4, 28, 10, 11, 12))
<= 12

timestamp  (date, pattern)

Returns a formatted date, based on the passed pattern.

timestamp(new Date(2018, 4, 28), "YYYY")
<= "2018"
timestamp(new Date(2018, 4, 28), "YYYY/MM")
<= "2018/05"
timestamp(new Date(2018, 4, 28), "YYYY/MM/DD")
<= "2018/05/28"

weekday  (date)

Returns the day of the week (from 0 to 6) of the specified date.

weekday(new Date(2017, 1, 11))
<= 6

year  (date)

Returns the year of the passed date.

year(new Date (2018, 4, 2))
<= 2018

Json


prettify  (value, indent)

Converts a value to JSON string. When the passed value is not a string, returns the value.

prettify({"foo":"bar"})
<= "{\n \"foo\": \"bar\"\n}"

Math


abs  (number)

Returns the absolute value of the number.

abs(-1)
<= 1

acos  (number)

Returns the arccosine of the number, in radians.

acos(0.5)
<= 1.0471975511965979

acosh  (number)

Returns the hyperbolic arccosine of the number, in radians.

acosh(2)
<= 1.3169578969248166

add  (number1, number2)

Adds two parameters.

add(10, 5)
<= 15

asin  (number)

Returns the arcsine of the number, in radians.

asin(1)
<= 1.5707963267948966

asinh  (number)

Returns the hyperbolic arcsine of the number.

asinh(1)
<= 0.881373587019543

atan  (number)

Returns the hyperbolic arctangent of the number.

atan(1)
<= 0.7853981633974483

atan2  (number1, number2)

Returns the arctangent of the quotient of its arguments.

atan2(5, 5)
<= 0.7853981633974483

atanh  (number)

Returns the hyperbolic arctangent of the number.

atanh(0.5)
<= 0.5493061443340548

cbrt  (number)

Returns the cubic root of the number.

cbrt(1)
<= 1

ceil  (number)

Returns the number, rounded upwards to the nearest integer.

ceil(100.2)
<= 101

clamp  (number, min, max)

Returns the highest possible value from range min to max of the number.

clamp(25, 20, 30)
<= 25
clamp(30, 20, 30)
<= 30

cos  (number)

Returns the cosine of the number (number is in radians).

cos(1)
<= 0.5403023058681398

cosh  (number)

Returns the hyperbolic cosine of the number.

cosh(0)
<= 1

cube  (number)

Returns the third power of the number.

cube(-4)
<= -64

decrement  (number)

Decrements the number.

decrement(1)
<= 0

degrees  (number, precision)

Converts radians to degrees and rounds received result by default precision equals 2.

degrees(5)
<= 286.48

divide  (number1, number2)

Divides two parameters.

divide(10, 5)
<= 2

exp  (number)

Returns the value of E^number, where E is Euler's number.

exp(0)
<= 1

factorial  (number)

Returns factorial of the number.

factorial(5)
<= 120

feet  (number, precision, decimal)

Converts inches to feets. By default precision equals 2. When decimal flag is set to false, returns result with prim (′) symbol.

feet(1)
<= 0.08

fixed  (number, digit)

Formats the number using fixed-point notation. By default digit equals 0.

fixed(25.32)
<= "25"

float  (number)

Parses the number to the float.

float("4.25")
<= 4.25

floor  (number)

Returns the number, rounded downwards to the nearest integer.

floor(300.91)
<= 300

inches  (number, precision, decimal)

Converts feets to inches. By default precision equals 2. When decimal flag is set to false, returns result with bis (″) symbol.

inches(1)
<= 12

increment  (number)

Increments the number.

increment(1)
<= 2

int  (number)

Parses the number to the integer.

int("4.25")
<= 4

log  (number)

Returns the natural logarithm (base E) of the number.

log(2, 8)
<= 0.6931471805599453

max  (numbers)

Returns the number with the highest value.

max([2,5,1])
<= 5

mean  (array)

Computes the mean of the values in array.

mean([1,2,3,4])
<= 2.5

min  (numbers)

Returns the number with the lowest value.

min([2,5,1])
<= 1

modulo  (number1, number2)

Divides two parameters and returns the remainder.

modulo(7, 2)
<= 1

monetize  (number, options)

Formats the number to currency format options is an object that accepts the following parameters: - digits: Number of digits after comma. By default equals 2. - separator: Separator separating the decimal part. By default equals ','. - symbol: The symbol of currency. By default equals 'zł'. - ending: Boolean flag, that specifies position of currency symbol. By default set to true. - space: Boolean flag, that specifies if space should exist before currency symbol. By default set to true. - hyphen: The symbol between groups of integer part. By default set to empty space. - size: The number of integers, that should be grouped. By default set to 3.

monetize(100)
<= "100,00 zł"
monetize(100.5, {"symbol":"€","separator":"."})
<= "100.50 €"

multiply  (number1, number2)

Multiplies two parametrs.

multiply(10, 5)
<= 50

percentage  (number)

Converts the number to percentage format.

percentage(0.25)
<= "25%"

pow  (number1, number2)

Returns the value of first parameter to the power of the second parameter.

pow(2, 5)
<= 32

radians  (number, precision)

Converts degrees to radians and rounds received result by default precision equals 2.

radians(12)
<= 0.21

random  ()

Returns a floating-point, pseudo-random number in the range 0–1.

random()
<= 0.42571295990318103

round  (number)

Rounds the number, to the nearest integer.

round(20.49)
<= 20

sin  (number)

Returns the sine of the number.

sin(2)
<= 0.9092974268256817

sinh  (number)

Returns the hyperbolic sine of the number.

sinh(1)
<= 1.1752011936438014

sqrt  (number)

Returns the square root of the number.

sqrt(4)
<= 2

square  (number)

Returns square of the number.

square(5)
<= 25

subtract  (number1, number2)

Subtracts two parameters.

subtract(10, 5)
<= 5

tan  (number)

Returns the tangent of the number.

tan(1)
<= 1.5574077246549023

tanh  (number)

Returns the hyperbolic tangent of the number.

tanh(-1)
<= -0.7615941559557649

trunc  (number)

Returns the integer part of the number.

trunc(42.84)
<= 42

Object


clone  (object)

Creates shallow copy of the passed object (objects are clone as reference).

clone({"a":0,"b":{"c":0}})
<= {"a":0,"b":{"c":0}}

deepclone  (object)

Creates deep copy of the passed object (objects are clone as value).

deepclone({"a":0,"b":{"c":0}})
<= {"a":0,"b":{"c":0}}

dig  (object, string)

Returns the value of any object property, which the name has been passed in the string.

dig({"foo":{"bar":"baz"}}, "foo.bar")
<= "baz"

keys  (object)

Returns an array of a given object's property names.

keys({"foo":"bar","baz":[1,2,3]})
<= ["foo","baz"]

merge  (object, sources)

Merges properties of sources into the destination object.

merge({"foo":{"a":1,"b":1,"c":1},"baz":{"b":2,"c":2}})
<= {"foo":{"a":1,"b":1,"c":1},"baz":{"b":2,"c":2}}
merge({"foo":{"a":1,"b":1,"c":1},"baz":{"b":2,"c":2},"bar":{"c":3}})
<= {"foo":{"a":1,"b":1,"c":1},"baz":{"b":2,"c":2},"bar":{"c":3}}

pat  (object, string, value)

Overrides the value of any object property, which the name has been passed in the string with the value.

pat({"foo":"bar"}, "foo", "baz")
<= {"foo":"baz"}

recsort  (object)

Sorts keys of an object.

recsort({"b":2,"a":1})
<= {"a":1,"b":2}

rename  (object, keys)

Changes names of the object properties to responds values from the keys object.

rename({"created_at":"2000-01-01"}, {"created_at":"createdAt"})
<= {"createdAt":"2000-01-01"}

values  (object)

Returns an array of a given object's own enumerable property values.

values({"foo":"bar","baz":[1,2,3]})
<= ["bar",[1,2,3]]

String


bytes  (string)

Converts string with specific unit to bytes.

bytes("400KB")
<= 409600

camelize  (string, lowercased)

Converts string to camelcase notation. Second parameter sets the first letter to lowercase or uppercase.

camelize("foo_bar")
<= "fooBar"
camelize("FooBar")
<= "fooBar"

capitalize  (string)

Converts first letter of the string to uppercase.

capitalize("foo")
<= "Foo"
capitalize("foo bar and baz")
<= "Foo bar and baz"

celsius  (string)

Converts temperature in Fahrenheit and Kelvin notation to Celsius degree. When passed string is a number, appends °C to the string.

celsius("25")
<= "25°C"
celsius("0°F")
<= "-18°C"
celsius("0K")
<= "-273°C"

chomp  (string, pattern)

Removes from the end of the string passed pattern.

chomp("foo bar", "ar")
<= "foo b"

chop  (string)

Returns string with last character removed. If the string ends with line ending characters then both will be removed.

chop("foo bar baz")
<= "foo bar ba"

classify  (string)

Creates a class name based on the string.

classify("cars")
<= "Car"

constantize  (string)

Converts string to constant notation.

constantize("foo")
<= "FOO"

crop  (string, length, append)

Truncates string at full words. Adds ... if the string is longer than the second parameter.

crop("foo bar baz ban bar", 10)
<= "foo bar..."

dasherize  (string)

Replaces _ with -.

dasherize("foo_bar__baz")
<= "foo-bar--baz"

dot  (string)

Returns string with dot at the end.

dot("foo bar")
<= "foo bar."

fahrenheit  (string)

Converts temperature in Celsius and Kelvin notation to Fahrenheit degree. When passed string is a number, appends °F to the string.

fahrenheit("50")
<= "50°F"
fahrenheit("30°C")
<= "86°F"

htmlstrip  (string)

Removes HTML tags from the string. Warning: do not use it as a security mechanism.

htmlstrip("<div>foo</div>")
<= "foo"
htmlstrip("Hello <b><i>world!</i></b>")
<= "Hello world!"

humanize  (string, capitalize = true)

Replaces _ with singlespaces. When capitalize is truthy, converts first char of the string to uppercase.

humanize("foo bar")
<= "Foo bar"
humanize("foo_bar")
<= "Foo bar"

hyphenate  (string)

Replaces spaces with hyphens, splits camelcase text, remove non-word chars and converts string to lowercase.

hyphenate("%# lorem ipsum ? $ dolor")
<= "lorem-ipsum-dolor"
hyphenate("loremIpsum")
<= "lorem-ipsum"

index  (string, pattern, start = 0)

Returns index of searched pattern.

index("hello", "e")
<= 1
index("hello", "lo")
<= 3

initials  (string, separator = "")

Returns initials separated by the separator.

initials("Foo Bar")
<= "FB"
initials("Foo Barin-Bar", ".")
<= "F.B.B"

kelvin  (string)

Converts temperature in Celsius and Fahrenheit notation to Kelvin scale. When passed string is a number, appends K to the string.

kelvin("100")
<= "100K"
kelvin("26°C")
<= "299K"

lowercase  (string)

Lowercases the string.

lowercase("Foo BAR and baZ")
<= "foo bar and baz"

lowerfirst  (string)

Converts first letter of the string to lowercase.

lowerfirst("Foo bar baz")
<= "foo bar baz"

ltrim  (string, characters = " ")

Removes white space characters or other specified in parameter characters from the beginning of the string.

ltrim(" foo")
<= "foo"

pad  (string, pad, left = true)

Returns string with added pad from left side or right side.

pad("hello world", 5)
<= " hello world"
pad("Hello world", 5, false)
<= "Hello world "
pad("hello world", "** ")
<= "** hello world"

pluralize  (string)

Returns plural form of the string.

pluralize("car")
<= "cars"
pluralize("dress")
<= "dresses"
pluralize("wife")
<= "wives"

quote  (string, lang = "en")

Puts the string inside quotations marks.

quote("foo bar baz")
<= "\"foo bar baz\""
quote("foo bar baz", "pl")
<= "„foo bar baz”"

repeat  (string, count)

Repeats the string n times.

repeat("foo", 2)
<= "foofoo"

replace  (string, pattern, replace)

Replaces searched pattern by the last parameter.

replace("foo bar baz ban", "baz", "qux")
<= "foo bar qux ban"

rtrim  (string, characters = " ")

Removes white space characters or other specified in parameter characters from the end of the string.

rtrim("foo ")
<= "foo"

singlespace  (string)

Replaces in the string multiple spaces to single spaces.

singlespace("foo bar baz")
<= "foo bar baz"

singularize  (string, appendix = "")

Returns singular form of the string.

singularize("cars")
<= "car"
singularize("watches")
<= "watch"
singularize("shelves", "f")
<= "shelf"

slugify  (string, separator = "-")

Converts string to lower case, remove non-word chars and replace spaces with the separator.

slugify("LoremIpsum dolor special chars")
<= "loremipsum-dolor-special-chars"

split  (string, separator = "")

Splits string into an array by separating the string into substrings.

split("foo,bar,bazz", ",")
<= ["foo","bar","bazz"]

squeeze  (string, pattern = "a-zA-Z")

Replaces multiple occurances of the same characters to the one character.

squeeze("yellow moon")
<= "yelow mon"

strip  (string, pattern)

Removes the passed pattern from the string.

strip(" foo ")
<= "foo"
strip("foo bar baz ban", ["o","r","a"])
<= "f b bz bn"

summarize  (string, length = 100)

Adds three dots at the end of the string, when the string is longer than the passed length.

summarize("foo bar baz ban", 10)
<= "foo bar baz ban..."

swapcase  (string)

Replaces in string lowercased letters to uppercase and uppercased letters to lowercase.

swapcase("foo")
<= "FOO"
swapcase("fOo Bar BAZ")
<= "FoO bAR baz"

tail  (string, length = 30, ending = "...")

Truncates the tail of a given string.

tail("Once upon a time in a world far far away", 15)
<= "...far far away"

titleize  (string)

Converts to 'uppercase' first letter of each word in string.

titleize("foo bar")
<= "Foo Bar"

trim  (string)

Removes whitespace from the start and the end of the string.

trim(" foo ")
<= "foo"

truncate  (string, length = 30, ending = "...")

Truncates a given string if it longer than the passed length and replaces last chars of new string with the passed ending.

truncate("Once upon a time in a world far far away")
<= "Once upon a time in a world..."
truncate("Once upon a time in a world far far away", 15)
<= "Once upon a ..."

uid  (length = 32)

Returns an unique identifier.

uid(10)
<= "Q8KwPDYgI0"

underscore  (string)

Returns new string with words separated by _. All letters are lowercased.

underscore("fooBar")
<= "foo_bar"

unescape  (string)

Converts the HTML entities to their corresponding characters.

unescape("&amp;")
<= "&"

unquote  (string)

Removes "" or „” from the string.

unquote("„foo bar baz”")
<= "foo bar baz"
unquote("\"foo bar baz\"")
<= "foo bar baz"

unwrap  (string, first, last = first)

Removes characters from the start and end of the string based on the passed values.

unwrap("\"foo bar baz ban\"", "\"")
<= "foo bar baz ban"
unwrap("„foo bar baz”", "„", "”")
<= "foo bar baz"

uppercase  (string)

Converts string to uppercase.

uppercase("foo")
<= "FOO"

whitespacestrip  (string)

Removes whitespaces from the string.

whitespacestrip(" f o o")
<= "foo"

wrap  (string, first, last = first)

Wraps string between the first and last parameters.

wrap("foo bar baz ban", "„", "”")
<= "„foo bar baz ban”"