Implementation of the most useful and fun JavaScript functions (ES6).
This repo do not pretend to be another functional programming (FP) library as Lodash, Underscore or Ramda. These libraries work very fine and are well tested. They also have a very strong community behind them working for a long time. I recommend that you use them!
- add
- adjust
- all
- always
- and
- any
- append
- arity
- assoc
- assocPath
- camelCase
- capitalize
- chunk
- clean
- compose
- concat
- contains
- curry
- debounce
- defer
- delay
- difference
- dissoc
- dissocPath
- divide
- drop
- evolve
- falsy
- filterObject
- has
- hasIn
- isArray
- isEven
- isEmpty
- isFunction
- isInteger
- isNil
- isNumber
- isObject
- isRegExp
- isString
- mapObject
- match
- max
- mean
- median
- memoize
- merge
- min
- modulo
- multiply
- negate
- none
- not
- nth
- omit
- or
- pairs
- path
- pathOr
- percent
- pick
- pipe
- pluck
- prop
- propOr
- randomBetween
- reject
- remove
- repeat
- replace
- reverse
- sort
- sortBy
- square
- subtract
- sum
- take
- throttle
- times
- truncate
- uniq
- uniqBy
- update
- when
Please review the documentation.
Adds two values.
add(2, 4) // 6
add(5, 5) // 10
add('5', 5) // 10
add('5', '5') // 10
curry(add)(2)(4) // 6
const add2 = curry(add, 2)
add2(4) // 6
const add2 = n => add(2, n)
add2(4) // 6
Applies a function to the value that is in the specified index and returns a new array with the index element replaced by the result of the function.
adjust(squared, 1, [1, 2, 3]) // [1, 4, 3]
Returns true
if all elements of the list match with the predicate, false
otherwise.
const list = [0, 1, 2, 3]
const list2 = [11, 12, 13, 14]
const bigger10 = n => n > 10
all(bigger10, list) // false
all(bigger10, list2) // true
Returns a function that always returns the given value.
Ramda docs says:
Note that for non-primitives the value returned is a reference to the original value.
This function is known as const
, constant
, or K
(for K combinator) in
other languages and libraries.
const t = always('lol')
t() // "lol"
Returns true
if both arguments are true
; false
otherwise.
and(true, true) // true
and(true, false) // false
and(false, false) // false
and(false, false) // false
Returns true
if at least one of elements of the list match the predicate,
false
otherwise.
const list = [0, 1, 2, 3]
const list2 = [11, 2, 3, 14]
const bigger10 = n => n > 10
any(bigger10, list) // false
any(bigger10, list2) // true
Returns a new list containing the contents of the given list, followed by the given element.
append('code', ['read', 'write']) // ['read', 'write', 'code']
append('code', []) // ['code']
append(['code'], ['read', 'write']) // ['read', 'write', ['code']]
Returns the number of arguments accepted by the given function fn
.
const foo = (a, b, c) => a + b + c
const bar = (a, {}) => { a: a }
arity(foo) // 3
arity(bar) // 2
Returns a copy of an object, setting or overriding the specified property with the given value.
Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
assoc('c', 3, { a: 1, b: 2 }) // { a: 1, b: 2, c: 3 }
assoc('b', 23, { a: 1, b: 2 }) // { a: 1, b: 23 }
assoc('unit_price', 'β¬', product) // { "brand": "Brand goes here!", ..., "unit_price": "β¬", "width": 965 }
Returns a clone of an object, setting or overriding the nodes required to create the given path, and placing the specific value at the tail end of that path.
Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
const ob = { a: { b: { c: 0 } } }
const updated = assocPath(['a', 'b', 'c'], 1, ob)
console.log(updated) // { a: { b: { c: 1 } } }
assocPath(['a', 'b', 'c'], 1, ob) // { a: { b: { c: 1 } } }
assocPath(['a', 'b'], 1, { a: 5 }) // { a: { b: { c: 1 } } }
Converts string
to camel case style.
See camel case.
let baz = 'foo bar'
let camel = camelCase(baz)
console.log(camel) // "fooBar"
camelCase('foo bar') // "fooBar"
camelCase('FOO BAR') // "fooBar"
camelCase('x nN foo bar') // "xNnFooBar"
camelCase('!--foo-ΒΏ?-bar--121-**%') // "fooBar121"
Converts the String parameter to lowercase and his first char to uppercase.
capitalize('lorem ipsum dolor sit amet') // "Lorem ipsum dolor sit amet"
capitalize('LOREM IPSUM DOLOR SIT AMET') // "Lorem ipsum dolor sit amet"
Creates an array
of elements split into groups the length of size
.
If array
can't be split evenly, the final chunk will be the remaining
elements.
chunk(1, ['a', 'b', 'c', 'd']) // [["a"], ["b"], ["c"], ["d"]]
chunk(2, ['a', 'b', 'c', 'd']) // [["a" ,"b"], ["c", "d"]]
chunk(3, ['a', 'b', 'c', 'd']) // [["a", "b", "c"], ["d"]]
Creates an array with all falsy
values removed.
See falsy.
const arr = [0, 1, false, null, undefined, 2, '', 3, '4', NaN]
const cln = clean(arr) // [1, 2, 3, "4"]
Returns a function that is the composition of a list of functions, each consuming the return value of the function that follows.
Note that this is exactly the same as pipe but with the functions in opposite order.
const classyGreeting = (firstName, lastName) => "THE NAME'S " + lastName + ", " + firstName + " " + lastName
const yellGreeting = compose(camelCase, classyGreeting)
yellGreeting('JAMES', 'BOND') // "theNameSBondJamesBond"
Returns the result of concatenating the given lists or strings.
concat('ABC', 'DEF') // "ABCDEF"
concat([1, 2, 3], [4, 5, 6]) // [1, 2, 3, 4, 5, 6]
concat('', '') // ""
concat([], []) // []
concat({}, '123') // TypeError: [object Object] does not have a method named "concat"
Returns true
if the specified value is equal to at least one element of the
given list, false
otherwise.
contains(3, [1, 2, 3]) // true
contains(4, [1, 2, 3]) // false
contains(4, [1, 2, 3, 4]) // true
Returns a curried equivalent of the provided function.
const add5 = curry(add, 5)
add5(2) // 7
add5(100) // 105
// NOTE: In this example curry don't make sense with ES6
const add5 = x => add(5, x)
add5(100) // 105
Limits the rate at which a function can fire.
const debouncedResize = debounce((event) => {
console.log('resized')
}, 1000)
window.addEventListener('resize', debouncedResize)
window.addEventListener('resize', debounce(() => console.log('resizing'), 1000, { inmediate: true }))
Defer a function, scheduling it to run after the current call stack hascleared.
defer(text => console.log(text), 'Deferred')
Invokes fn
after wait
milliseconds. Any additional arguments are
provided to fn
when it's invoked.
delay(text => console.log(text), 1000, 'Text to log after 1000ms')
delay(text => console.log(text), 3000, 'Text to log after 3000ms')
Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. Objects and Arrays are compared in terms of value equality, not reference equality.
difference([1,2,3,4], [7,6,5,4,3]) // [1, 2]
difference([7,6,5,4,3], [1,2,3,4]) // [7, 6, 5]
Returns a new object that does not contain a prop
property.
dissoc('b', { a: 1, b: 2 }) // { a: 1 }
dissoc('price', product) // { "brand": "Brand goes here!", ..., "width": 965 }
Returns a copy of the object by omitting the property of the specified path.
const obj = { a: { b: { c: { d: 100 } } } }
dissocPath(['a', 'b', 'c', 'd'], obj) // { a: { b: { c: {} } } }
Divide two numbers.
divide(10, 2) // 5
divide(100, 2) // 50
divide(1000, 2) // 500
divide(6, 4) // 1.5
Returns a new array without the n
elements of the given list
or string.
const arr = ['foo', 'bar', 'baz']
drop(1, arr) // ["bar", "baz"]
drop(2, arr) // ["baz"]
drop(3, arr) // []
Returns a new object according to the transformation functions.
const product = {
"id": 66443,
"image": "aceb.png",
"width": 965,
"height": 1040,
"description": "Description goes here!",
"categories": ["4114", "4232"],
"brand": "Brand goes here!",
"price": 9.99,
"allergens": {
"a": 'Allergen A',
"b": 'Allergen B'
}
}
const renameCategory = a => `000_${ a }`
const discount20 = t => '20% off!! ' + t
const restoreRetina = h => h * 2
const applyDiscount20 = p => p - percent(p, 20)
const renameAllergen = t => `- ${ t }`
const transformations = {
description: discount20,
title: discount20,
categories: [renameCategory, renameCategory],
height: restoreRetina,
price: applyDiscount20,
allergens: {
a: renameAllergen,
b:renameAllergen
}
}
evolve(transformations, product)
// {
// "allergens": Object {
// "a": "- Allergen A",
// "b": "- Allergen B"
// },
// "brand": "Brand goes here!",
// "categories": Object {
// "0": "000_4114",
// "1": "000_4232"
// },
// "description": "20% off!! Description goes here!",
// "height": 2080,
// "id": 66443,
// "image": "aceb.png",
// "price": 7.992,
// "width": 965
// }
function Person () {
this.name = 'Person'
this.age = 36
this.height = 196
}
Person.prototype.setName = function (name) {
return this.name = name
}
Person.prototype.greet = function (name) {
return `Hi! I'm ${ this.name }. An instance of ${ Person }`
}
const rename = n => 'Edgar'
const grow = a => a + 1
const transformations2 = {
name: rename,
age: grow
}
const person = new Person()
person.setName('Bob')
const newPerson = evolve(transformations2, person)
console.log(newPerson)
// {
// "age": 37,
// "height": 196,
// "name": "Edgar"
// }
console.log(person.name) // Bob
Returns if a value is falsy or not.
Falsy values:
- false
- 0 (zero)
- "" (empty string)
- null
- undefined
- NaN (a special Number value meaning Not-a-Number!)
falsy(false) // true
falsy(0) // true
falsy('') // true
falsy(null) // true
falsy(undefined) // true
falsy(NaN) // true
falsy(1) // false
Iterates over properties of an object obj
returning an array of all
elements fn
(predicate) returns truthy for.
Note that the predicate is invoked with three arguments: value
, key
, object
.
const object = { 'a': 5, 'b': 8, 'c': 10 }
filterObject((n) => !(n % 5), object) // [5, 10]
Returns whether or not an object has an own property with the specified name. A shortcut for Object.hasOwnProperty.
Note that this method is similar as hasIn
with plain Objects, but he can't
access to the prototype properties of the Function objects.
const product = {
"id": 66443,
"image": "aceb.png",
"width": 965,
"height": 1040,
"description": "Description goes here!",
"categories": ["4114","4232"],
"brand": "Brand goes here!",
"price": 9.99,
"sub": {
"a": 1000,
"b": 2000
}
}
has('price', product) // true
has('description', product) // true
has('sub', product) // true
has('b', product.sub) // true
const hasSubB = prod => has('b', prod.sub)
hasSubB(product) // true
Returns whether or not an object or its prototype chain has a property with the specified name.
Note that this method is similar as has
with plain Objects, but he can
access to the prototype properties of the Function objects.
function Rect (width, height) {
this.width = width
this.height = height
}
Rect.prototype.area = function () {
return this.width * this.height
}
const square = new Rect(2, 2)
hasIn('width', square) // true
hasIn('area', square) // true
hasIn('name', square) // false
class Circle {
constructor (r) {
this.rad = r
}
get diameter () { return this.rad * 2 }
}
const circle = new Circle(20)
hasIn('rad', circle) // true
hasIn('diameter', circle) // true
hasIn('name', circle) // false
Check if the parameter is an Array or not.
isArray([]) // true
isArray([1, 'yep', {a: 1, b: 2}]) // true
isArray(true) // false
isArray(false) // false
isArray(NaN) // false
isArray({}) // false
Check if a number is a multiple of 2.
isEven(1) // false
isEven(2) // true
isEven(120) // true
isEven(113) // false
Check if the parameter is a Function or not.
isFunction(curry) // true
isFunction(() => {}) // true
isFunction(function () { return true }) // true
isFunction(true) // false
isFunction(false) // false
isFunction(NaN) // false
isFunction({}) // false
isFunction([]) // false
isFunction(123) // false
Check if the parameter is an Integer or not.
isInteger(1) // true
isInteger(123) // true
isInteger(1.23) // false
isInteger('') // false
isInteger('123') // false
isInteger(true) // false
isInteger(false) // false
isInteger(NaN) // false
isInteger([]) // false
isInteger(() => {}) // false
Checks if value
is null
or undefined
.
isNil(null) // true
isNil(undefined) // true
isNil(NaN) // false
isNil(0) // false
Check if the parameter is a Number or not.
isNumber(1) // true
isNumber(123) // true
isNumber('123') // false
isNumber(true) // false
isNumber(false) // false
isNumber(NaN) // true NOTE: this is normal?!
isNumber({}) // false
isNumber([]) // false
isNumber(() => {}) // false
Check if the parameter is an Object or not.
isObject({}) // true
isObject(1) // false
isObject(123) // false
isObject('123') // false
isObject(true) // false
isObject(false) // false
isObject(NaN) // false
isObject([]) // false
isObject(() => {}) // false
Check if the parameter is a String or not.
isString('') // true
isString('hello') // true
isString('123') // true
isString(1) // false
isString(123) // false
isString(true) // false
isString(false) // false
isString(NaN) // false
isString([]) // false
isString(() => {}) // false
Returns the results of applying the fn
to each element of the object
.
In contrast to Array.map
it returns an object
.
const prependKeyAndDouble = (num, key, obj) => key + (num * 2)
const values = { x: 1, y: 2, z: 3 }
mapObject(prependKeyAndDouble, values) // { x: 'x2', y: 'y4', z: 'z6' }
Tests a regular expression against a String.
Note this method is similar to R.match
https://github.com/ramda/ramda/blob/master/src/match.js
match(/([a-z]a)/g, 'bananas') // ['ba', 'na', 'na']
match(/a/, 'b') // []
match(/a/, null) //=> TypeError: null does not have a method named "match"
Returns the larger argument.
max(8765, 1224) // 8765
max('a', 'b'); // 'b'
Returns the mean of the given list of numbers.
mean([2, 7, 9]) // 6
mean([]) // NaN
Returns the median of the given list of numbers.
median([2, 9, 7]) // 7
median([7, 2, 10, 9]) // 8
median([1, 1, 2, 2]) // 1.5
median([]) // NaN
Simple memoize function that takes in a function and returns a memoized function.
const factorial = memoize((x) => {
if (x === 0) {
return 1
} else {
return x * factorial(x - 1)
}
})
factorial(5) // calculate 5, 4, 3, 2, 1, 0 => 120
factorial(6) // calculate 6 and fetch from cache 5 => 720
Create a new object with the properties of the first object merged with the properties of the second object.
Note If a key exists in both objects, the value from the second object will be used.
merge({ 'name': 'fred', 'age': 32 }, { 'employment': developer })
// { "age": 32, "employment": "developer", "name": "fred" }
merge({ 'name': 'sue', 'age': 31 }, { 'employment': 'developer', 'age': 28 })
// { "age": 28, "employment": "developer", "name": "sue" }
const resetX = o => merge(o, {x: 0})
resetX({x: 5, y: 2}) // { "x": 0, "y": 2 }
Returns the smaller argument.
min(8765, 1224) // 1224
min('a', 'b'); // 'a'
Divides the first parameter by the second and returns the remainder.
modulo(17, 3) // 2
modulo(-17, 3); // -2 JavaScript behavior
modulo(17, -3); // 2
Multiplies two numbers. Equivalent to a * b
.
multiply(2, 5) // 10
const double = n => multiply(n, 2)
const triple = n => multiply(n, 3)
double(3) // 6
triple(3) // 9
Creates a function that negates the result of the predicate func
.
const list = [1, 2, 3, 4, 5, 6]
list.filter(negate(isEven)) // [1, 3, 5]
Returns true
if no elements of the list match the predicate, false
otherwise.
const list = [0, 1, 2, 3]
const list2 = [11, 12, 13, 14]
const bigger10 = n => n > 10
none(bigger10, list) // true
none(bigger10, list2) // false
Returns the !
of its argument. It will return true
when passed falsy
value and false
when passed a truly one.
not(true) // false
not(false) // true
not(0) // true
not(1) // false
Returns the nth element of the given list or String. If n
is negative the
element at list[length - negate(i)]
is returned.
const list = ['foo', 'bar', 'baz', 'fooz']
nth(1, list) // "bar"
nth(-1, list) // "fooz"
nth(-99, list) // `undefined`
nth(2, 'abc') // "c"
nth(3, 'abc') // ""
Returns a new object omitting the keys specified.
const product = {
"id": 66443,
"image": "aceb.png",
"width": 965,
"height": 1040,
"description": "Description goes here!",
"categories": ["4114", "4232"],
"brand": "Brand goes here!",
"price": 9.99,
"allergens": {
"a": 'Allergen A',
"b": 'Allergen B'
}
}
omit(['id', 'price', 'brand'], product)
// {
// "allergens": Object {
// "a": "Allergen A",
// "b": "Allergen B"
// },
// "categories": ["4114", "4232"],
// "description": "Description goes here!",
// "height": 1040,
// "image": "aceb.png",
// "width": 965
// }
Returns true
if one or both of its arguments are true
. Returns false
if both arguments are false
.
or(true, true) // true
or(true, false) // true
or(false, false) // true
or(false, false) // false
Convert an object into a list of [key, value]
pairs.
const values = { x: 1, y: 2, z: 3 }
pairs(values) // [["x", 1], ["y", 2], ["z", 3]
Retrieve the value at a given path.
const product = {
"id": 66443,
"image": "aceb.png",
"width": 965,
"height": 1040,
"description": "Description goes here!",
"categories": ["4114","4232"],
"brand": "Brand goes here!",
"price": 9.99,
"sub": {
"a": 1000,
"b": 2000,
"under": {
"a": 10000000,
"b": 20000000,
"superunder": {
"a": 100000000000000,
"b": 200000000000000
}
}
}
}
path(['a', 'b'], { a: { b: 2 } }) // 2
path(['sub', 'under', 'superunder', 'b'], product) // 200000000000000
Calculate the percentage %
of a value. The firs parameter is the value and the
second parameter is the percentage to calculate.
percent(100, 50) // 50
percent(30, 20) // 6
percent(9.99, 10) // 0.9990000000000001
const percent50 = value => percent(value, 50)
percent50(100) // 50
Reads an array with multiple properties from an object and returns a partial copy of an object with just those properties specified. If the key does not exist, the property is ignored.
pick(['a', 'd'], { a: 1, b: 2, c: 3, d: 4 }) // { a: 1, d: 4 }
pick(['a', 'e', 'f'], { a: 1, b: 2, c: 3, d: 4 }) // { a: 1 }
pick(['user'], { user: 'Bob', id: 2, age: 36 }) // { user: "Bob" }
Performs left-to-right
function composition. Takes a list of one or more
functions and returns a new function.
The new function takes the same number of arguments as the first function it is given. It then, pipes those arguments through each function in the list. It applies the first function to the arguments, passes its result to the second function and so on.
The result of the last function is the result of the pipe call.
Note that this is exactly the same as compose but with the functions in opposite order.
const inc = n => n + 1
const dbl = n => n * 2
const sqr = n => n * n
const operate = pipe(inc, dbl, sqr)
operate(2) // 36
operate(5) // 144
operate(1) // 16
// NOTE: same example but with `compose` produces different value.
const operateCompose = compose(inc, dbl, sqr)
operateCompose(1) // 3
Returns a new list by plucking the same named property off all objects in the list supplied.
pluck('a', [{a: 1}, {a: 2}]) // [1, 2]
pluck(0, [[1, 2], [3, 4]]) // [1, 3]
pluck('val', {a: {val: 3}, b: {val: 5}}) // [3, 5]
Returns the value of the property to check for or undefined
.
NOTE: With a Function
and ES6 Class
objects the behavior is similar.
const product = {
"id": 66443,
"image": "aceb.png",
"width": 965,
"height": 1040,
"description": "Description goes here!",
"categories": ["4114","4232"],
"brand": "Brand goes here!",
"price": 9.99,
"sub": {
"a": 1000,
"b": 2000
}
}
prop('price', product) // 9.99
prop('description', product) // "Description goes here!"
etProp('sub', product) // Object { "a": 1000, "b": 2000 }
prop('b', prop('sub', product)) // 2000
const getPrice = prod => prop('price', prod)
getPrice(product) // 9.99
const getSubB = prod => prop('b', prod.sub)
getSubB(product) // 2000
If the given object has an own property with the specified name, returns the value of that property. Otherwise returns the provided default value.
propOr('The default property value.', 'unit_price', product) // "The default property value."
propOr('The default property value.', 'price', product) // 9.99
Returns a random number in a specified range (min and max inclusive).
randomBetween(100, 0) // 54
randomBetween(100, 0) // 81
randomBetween(100, 0) // 29
randomBetween(-20, 100) // 59
randomBetween(-100, 100) // -18
The opposite of filter
this method returns the elements of list
that fn
does not return truthy for.
const obj = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
const arr = [1, 2, 3, 4]
reject(obj, isEven) // [1, 3]
reject(arr, isEven) // [1, 3]
const users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false }
]
reject(users, ({ active }) => active) // [{ 'user': 'fred', 'active': false }]
Removes the sub-list of list
starting at index start
and containing
count
elements.
Note that this is a copy of the list. It does not modify the original.
const list = [1, 2, 3, 4, 5, 6, 7, 8]
remove(2, 5, list) // [1, 2, 8]
remove(1, 1, list) // [1, 3, 4, 5, 6, 7, 8]
Returns a fixed list of size n
containing a specified identical value.
const obj = {}
const repObjs = n => repeat(obj, n)
repObjs(3) // [{}, {}, {}]
repeat('str', 6) // ['str', 'str', 'str', 'str', 'str', 'str']
Replace a substring or regex match in a string with a replacement.
replace('foo', 'bar', 'foo foo foo') // "bar foo foo"
replace(/foo/, 'bar', 'foo foo foo') // "bar foo foo"
replace(/foo/g, 'bar', 'foo foo foo') // "bar bar bar"
Returns a new list or string with the elements or characters in reverse order.
reverse([1, 2, 3, 4]) // [4, 3, 2, 1]
reverse('abcde') // "edcba"
Returns a copy of the list, sorted according to the comparator function.
Note that this is a copy of the list. It does not modify the original.
const min = (a, b) => a > b
const max = (a, b) => a < b
sort(min, [4, 2, 7, 5,])
sort(min, [100, 1024, 768, 960])
sort(min, [3.1, 1.4, 1, 1.7])
sort(max, [4, 2, 7, 5])
sort(max, [100, 1024, 768, 960])
Multiply a number n
by itself.
square(2) // 4
square(8) // 64
square(16) // 256
Subtracts its second argument from its first argument.
subtract(10, 5) // 5
subtract(10, 5, 1) // 4
subtract('10', 5) // 5
subtract(2, '3', 4) // -5
subtract('5', '5') // 10
subtract('aa', 3) // NaN
// NOTE: I need think on implemet placeholder Symbol or like to solve this.
const subtract2 = curry(subtract, 2)
subtract2(100) // -98
-subtract2(100) // 98
const subtract2 = x => subtract(2, x)
Adds together all the elements of a list.
sum([1]) // 1
sum([1, 1]) // 2
sum([1, 2, 4]) // 7
sum(['1', 2, 4]) // 7
sum(['1', '2', '4']) // 7
const sum10 = list => sum([...list, 10])
sum10([1, 2, 4]) // 17
Returns a new array with the first n
elements of the given list
or string.
const arr = ['foo', 'bar', 'baz']
take(1, arr) // ["foo"]
take(2, arr) // ["foo", "bar"]
take(3, arr) // ['foo', 'bar', 'baz']
take(4, arr) // ['foo', 'bar', 'baz']
Adds together all the elements of a list.
window.addEventListener('resize', throttle(() => console.log('resizing') , 2000, { inmediate: true }))
Returns an Array containing the results of call an input function n
times.
Note that fn
is passed one argument: the current value of n
.
const family = [
{ 'name': 'pilar', 'age': 20 },
{ 'name': 'alberto', 'age': 3 },
{ 'name': 'edgar', 'age': 30 }
]
const foo = n => family[n].name
const baz = n => n
times(foo, family.length) // ['pilar', 'alberto', 'edgar']
times(baz, 100)) // [0, 1, 2, ..., 99]
Truncate a long strings to max num of characters and add ellipsis to the end.
truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 12) // "Lorem ipsum..."
truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 12, ' ππ»') // "Lorem ipsum ππ»"
Returns a new list containing only one copy of each element in the original list.
uniq([1, 2, 1, 4, 1, 3]) // [1, 2, 4, 3]
uniq(['a', 'b', 'c', 'a', 'd']) // ["a", "b", "c", "d"]
Returns a new list containing one copy of each unique element in the original
list filtered by prop
parameter.
Note that if the supplied function produces the same value on two items, prefers the first item.
const people = [
{ 'id': 1, 'name': 'edgar' },
{ 'id': 1, 'name': 'pilar' },
{ 'id': 1, 'name': 'pilar' },
{ 'id': 2, 'name': 'ivan' },
{ 'id': 2, 'name': 'inma' }
]
*
uniqBy('id', people) // [{ 'id': 1, 'name': 'edgar' }, { 'id': 2, 'name': 'ivan'}]
uniqBy('name', people) // [{ 'id': 1, 'name': 'edgar' }, { 'id': 1, 'name': 'pilar' }, { 'id': 2, 'name': 'ivan'}, { 'id': 2, 'name': 'inma'}]
uniqBy((o) => o.id, people) // [{ 'id': 1, 'name': 'edgar' }, { 'id': 2, 'name': 'ivan'}]
Returns a copy of the array with the element at the provided index replaced with the given value.
Note that is the result to apply always
method with the new value
as argument of the first parameter for the adjust
method.
update(1, 'new', [1, 2, 3]) // [1, "new", 3]
Tests the final argument by passing it to the given predicate function.
If the predicate is true, the function will return the result of calling
the when
function with the same argument. If the predicate is false,
the argument is returned.
const truncate10 = str => truncate(str, 10)
const isLarge = n => n.length > 10
const truncateIf = text => when(isLarge, truncate10, text)
truncateIf('0123456789Aeasd') // "0123456789..."
- Add tests.