Skip to content

Latest commit

 

History

History
2740 lines (1875 loc) · 59.2 KB

README.md

File metadata and controls

2740 lines (1875 loc) · 59.2 KB

 

 

Documentation

always

Creates a function that always returns a given value

const always = require('1-liners/always');

const T = always(true);
T(); // => true
T(); // => true

const fortyTwo = always(42);
fortyTwo(); // => 42
fortyTwo(); // => 42
SpecSource: val => () => val;

and

Same as a && b.

const and = require('1-liners/and');

and(true, true); // => true
and(false, true); // => false
SpecSource: (x, y) => x && y;

assign

Returns a new object and assigns assign to object.

const assign = require('1-liners/assign');

const yedi = { id: 1, age: 100 };

assign({ name: 'Yoda', age: 900 }, yedi);  // => { id: 1, name: 'Yoda', age:900 }
SpecSource: (assign, object) => ({ ...object, ...assign });

average

Returns the average of all items of an array.

const average = require('1-liners/average');

average([2, 3, 4]);        // => 3
average([]);               // => NaN
SpecSource: (array) => array.reduce((a, b) => (a + b), 0) / array.length;

between

Return number if it’s greater than min and lower than max. Else return min or max respectively.

const between = require('1-liners/between');

between(1, 10, 2.5);  // => 2.5
between(1, 10, -5);   // => 1
between(1, 10, 25);   // => 10
SpecSource: (min, max, number) => (number < min ? min : (number > max ? max : number));

bind

Binds a context to a function. Same as fun.bind(thisArg[, arg1[, arg2[, ...]]])

const bind = require('1-liners/bind');

setTimeout(bind(console, ['Hello'], console.log), 2000); // => 'Hello' (after 2s)
SpecSource: (thisArg, args, fun) => fun.bind(thisArg, ...args);

bitAnd

Same as a & b.

const bitAnd = require('1-liners/bitAnd');

bitAnd(1, 2); // => 0
bitAnd(2, 2); // => 2
SpecSource: (x, y) => x & y;

bitOr

Same as a | b.

const bitOr = require('1-liners/bitOr');

bitOr(0, 1); // => 1
bitOr(1, 1); // => 1
SpecSource: (x, y) => x | y;

butLast

Return a copy of array, without the last item.

import butLast from '1-liners/butLast';

const array = [1, 2, 3];

butLast(array);  // => [1, 2]
array;           // => [1, 2, 3]
SpecSource: (array) => array.slice(0, -1);

by

Same as a / b

const by = require('1-liners/by');

by(6, 2); // => 3
SpecSource: (a, b) => a / b;

castArray

If the provided value is an array returns a copy of it otherwise returns an array containing the original value.

const castArray = require('1-liners/castArray');

castArray([1, 2, 3]);  // => [1, 2, 3]
castArray(1);  				 // => [1]
castArray(null);  	   // => [null]
SpecSource: (value) => Array.isArray(value) ? value.slice(0) : [value];

charAt

Same as 'STR'.charAt(0).

const charAt = require('1-liners/charAt');

charAt(0, 'super') // => s
SpecSource: (index, str) => str.charAt(index);

charCodeAt

Same as 'STR'.charCodeAt(0).

const charCodeAt = require('1-liners/charCodeAt');

charCodeAt(0, 'super') // => 115
SpecSource: (index, str) => str.charCodeAt(index);

codePointAt

Same as 'STR'.codePointAt(0).

const codePointAt = require('1-liners/codePointAt');

codePointAt(0, 'super') // => 115
SpecSource: (index, str) => str.codePointAt(index);

compact

A pure function to make a list compact and remove falsey values

const compact = require('1-liners/compact');

compact([1, 2, false, 45]); // => [1, 2, 45]
SpecSource: arr => arr.filter(a => a === 0 || !!a);

compactObject

A pure function to make a object compact and remove falsey values

const compactObject = require('1-liners/compactObject');

compactObject({value: 'ebvk', fgs: undefined,}); // => {value: 'ebvk'}
SpecSource: (obj) => Object.keys(obj).reduce((acc, a) => Object.assign(acc, !!obj[a] ? {[a]: obj[a]} : {}), {});

compose

Compose a new function from two given functions.

const compose = require('1-liners/compose');

compose(f, g)(1, 2) === f(g(1, 2));
SpecSource: (f, g) => (...args) => f(g(...args));

composeAll

Compose a new function with a given array of functions.

const composeAll = require('1-liners/composeAll');

composeAll([f, g, h])(1, 2) === f(g(h(1, 2)));
SpecSource: (fns) => fns.reduce( (f, g) => (...args) => f(g(...args)) );

concat

Returns a copy of array with values or value appended at the end. Same as array.concat(values) or array.concat(value).

const concat = require('1-liners/concat');

concat(['c', 'd'], ['a', 'b']);  // => ['a', 'b', 'c', 'd']
concat(['c'], ['a', 'b']);       // => ['a', 'b', 'c']
concat('c', ['a', 'b']);         // => ['a', 'b', 'c']
SpecSource: (values, array) => array.concat(values);

converge

Converge two functions into one.

const converge = require('1-liners/converge');

converge(f, g, h)(1, 2) === f(g(1, 2), h(1, 2));
SpecSource: (f, g, h) => (...args) => f(g(...args), h(...args));

curry

Curry a function – split its list of parameters into 2 lists.

import curry from '1-liners/curry';
import reduce from '1-liners/reduce';
import compose from '1-liners/compose';

// You can use reduce and compose to create curry3,4 and so on.
const curry3 = compose(curry, curry);
const curry4 = reduce(compose, [curry, curry, curry]);

const f = (a, b, c, d) => a * b * c * d;
const  = curry(f);  // ~= curry2
const  = curry3(f); // ~= curry3
const  = curry4(f); // ~= curry4

f(1, 2, 3, 4)  === 24

(1)(2, 3, 4) === 24
(1, 2)(3, 4) === 24
(1, 2, 3)(4) === 24

(1)(2)(3, 4) === 24
(1)(2, 3)(4) === 24

(1)(2)(3)(4) === 24
SpecSource: (f) => (...a) => (...b) => f(...a, ...b);

curryRight

Curry a function from the right – split its parameters into 2 lists. Apply the second list of parameters first, without changing the order within the lists.

import curryRight from '1-liners/curryRight';

const g = (a, b, c, d) => a + b * c - d;
g(1, 2, 3, 4);  // => 3

const  = curryRight(g);
(4)(1, 2, 3);  // => 3
(3, 4)(1, 2);  // => 3
(2, 3, 4)(1);  // => 3
SpecSource: (f) => (...a) => (...b) => f(...b, ...a);

dec

Same as a - 1

const dec = require('1-liners/dec');

dec(1); // => 0
SpecSource: (val) => val - 1;

drop

Returns the tail of array after dropping the first n elements. Use this in place of String's .substr(startIndex) and .substring(startIndex)

const drop = require('1-liners/drop');

const array = [1, 2, 3, 4, 5];
const string = 'Hello World';

drop(2, array);  // => [3, 4, 5]
drop(6, string); // => 'World'
SpecSource: (n, array) => array.slice(Math.max(n, 0), Infinity);

endsWith

Same as str.endsWith(searchString).

const endsWith = require('1-liners/endsWith');

endsWith('liners', '1-liners');  // => true
endsWith('stoeffel', 'nope');  // => false
SpecSource: (searchString, str) => str.endsWith(searchString);

endsWithAt

Same as str.endsWith(searchString, position).

const endsWithAt = require('1-liners/endsWithAt');

endsWithAt(8, 'liners', '1-liners/endsWithAt');  // => true
endsWithAt(2, 'stoeffel', 'nope');  // => false
SpecSource: (position, searchString, str) => str.endsWith(searchString, position);

entries

Returns an array of a given object's own enumerable property [key, value] pairs Same as Object.keys(obj).map(key => [key, obj[key]]).

const entries = require('1-liners/entries');

entries({ foo: 'bar', baz: 42 }); // => [ ['foo', 'bar'], ['baz', 42] ]
entries(['foo', 'bar', 'baz']); // => [ [0, 'foo'], [1, 'bar'], [2, 'baz'] ]
entries({ foo: 'bar', [Symbol('baz')]: 42 }); // => [ ['foo', 'bar'] ]
entries('foo'); // => [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]
SpecSource: (obj) => Object.keys(obj).map(key => [key, obj[key]]);

equal

Same as a === b.

const equal = require('1-liners/equal');

equal(true, true); // => true
equal(false, true); // => false
equal(1, true); // => false
SpecSource: (x, y) => x === y;

every

Same as [1,2,3].every(GreaterThan16).

const every = require('1-liners/every');

every(elem => elem > 16, [16,17,18]); // => false
SpecSource: (every, arr) => arr.every(every);

exec

Same as regexObj.exec(str).

const exec = require('1-liners/exec');
const haystack = 'hAyHAYhayneEdLEHayHAy';

exec(haystack, /needle/i);  // => ['neEdLE']
exec(haystack, /n(.+)e/i);  // => ['neEdLE', 'eEdL']
exec(haystack, /needle/);   // => null
SpecSource: (str, regexObj) => regexObj.exec(str);

explode

The opposite of implode.

const explode = require('1-liners/explode');

const sum = (numbers) => numbers.reduce((a, b) => a + b);

explode(sum)(1, 2, 3, 4);  // => 10
SpecSource: (func) => (...args) => func(args);

filter

Same as [1, 2, 3].filter(isOdd).

const filter = require('1-liners/filter');

filter(isOdd, [1, 2, 3]); // => [1, 3]
SpecSource: (filter, arr) => arr.filter(filter);

findKey

A pure function to find key from object, matching a predicate similar to https://lodash.com/docs/4.17.4#findKey or Array.findIndex()

const findKey = require('1-liners/findKey');

const data = { a: 1, b: 2, c: 3 };
findKey((x) => x > 2, data); // => 'c'
SpecSource: (fn, obj) => Object.keys(obj).find(k => fn(obj[k]));

flatMap

Map a function over a collection and flatten the result by one-level.

const flatMap = require('1-liners/flatMap');

flatMap((x) => [x, x], [1, 2, 3]); // => [1, 1, 2, 2, 3, 3]
SpecSource: (fn, array) => [].concat.apply([], array.map(fn));

flip

Flip a function’s arguments.

const flip = require('1-liners/flip');

const f = (a, b) => a / b;

flip(f)(2, 6);        // => 3
flip(flip(f))(6, 2);  // => 3
SpecSource: (f) => (...args) => f(...args.reverse());

fold

Same as array.reduce.

const fold = require('1-liners/fold');

fold(sum, 8, [1, 2, 3]); // => 2
SpecSource: (fold, initial, arr) => arr.reduce(fold, initial);

foldRight

Same as array.reduceRight.

const foldRight = require('1-liners/foldRight');

foldRight(sub, 1, [1, 2, 3]); // => -5
SpecSource: (fold, initial, arr) => arr.reduceRight(fold, initial);

forEach

Same as [1, 2, 3].forEach(Math.sqrt).

const forEach = require('1-liners/forEach');

forEach(i => console.log('Item: ' + i), [9, 25]); // => logs "Item: 9" and "Item: 25"
SpecSource: (forEach, arr) => arr.forEach(forEach);

get

Gets the value at path of object.

const get = require('1-liners/get');

 let obj = { a: { b: 42 } };
 get('a.b', obj); // => 42
SpecSource: (path, obj) => path.split('.').reduce((acc, current) => acc && acc[current], obj);

greaterOrEqual

Same as a >= b.

const greaterOrEqual = require('1-liners/greaterOrEqual');

greaterOrEqual(2, 1); // => true
greaterOrEqual(2, 2); // => true
greaterOrEqual(1, 2); // => false
SpecSource: (x, y) => x >= y;

greaterThan

Same as a > b.

const greaterThan = require('1-liners/greaterThan');

greaterThan(2, 1); // => true
greaterThan(2, 2); // => false
greaterThan(1, 2); // => false
SpecSource: (x, y) => x > y;

hasOwnProperty

Same as obj.hasOwnProperty(prop).

const hasOwnProperty = require('1-liners/hasOwnProperty');

hasOwnProperty('a', {a: 1, b: 2});  // => true
hasOwnProperty('c', {a: 1, b: 2});  // => false
SpecSource: (prop, obj) => obj.hasOwnProperty(prop);

head

Returns the first item of an array.

const head = require('1-liners/head');

head([1, 2, 3]); // => 1
SpecSource: ([head,]) => head;

identity

Returns the value you pass to the function

const identity = require('1-liners/identity');

identity(true); // => true
identity(1); // => 1
identity({ foo: 1 }); // => { foo: 1 }
identity("1-liners"); // => "1-liners"
SpecSource: I => I;

ifThen

Creates a function which calls then if the predicate is true and returns undefined if the predicate is false.

const ifThen = require('1-liners/ifThen');

const words = ifThen((str) => typeof str === 'string', (str) => str.split(' '));

words('Hello ES2015'); // => ['Hello', 'ES2015']
    words(['Hello', 'ES2015']); // => undefined
SpecSource: (predicate, then) => (...args) => predicate(...args) ? then(...args) : undefined;

ifThenElse

Creates a function which calls then if the predicate is true and otherwise if the predicate is false.

const ifThenElse = require('1-liners/ifThenElse');

const eq = (a, b) => a === b;
const add = (a, b) => a + b;
const sub = (a, b) => a - b;

const addIfEq = ifThenElse(eq, add, sub);

addIfEq(1, 1); // => 2
addIfEq(2, 1); // => 1
SpecSource: (predicate, then, otherwise) => (...args) => predicate(...args) ? then(...args) : otherwise(...args);

implode

Collapse a list of arguments into an array of arguments.

const implode = require('1-liners/implode');

const f = (a, b) => a + b;

[
	[1, 2],
	[3, 4],
	[5, 6],
].map(implode(f));  // => [3, 7, 11]
SpecSource: (func) => (args) => func(...args);

inc

Same as a + 1

const inc = require('1-liners/inc');

inc(1); // => 2
SpecSource: (val) => val + 1;

includes

Same as 'Blue Whale'.includes('blue').

const includes = require('1-liners/includes');

includes('blue', 'Blue Whale') // => false
SpecSource: (searchString, str) => str.includes(searchString);

indexOf

Same as 'str'.indexOf('t').

const indexOf = require('1-liners/indexOf');

indexOf('a', 'hallo') // => 1
SpecSource: (searchValue, str) => str.indexOf(searchValue);

isBetween

Check if the number lies between min and max, inclusive.

const isBetween = require('1-liners/isBetween');

isBetween(1, 10, 2.5);  // => true
isBetween(1, 10, -5);   // => false
isBetween(1, 10, 25);   // => false
SpecSource: (min, max, number) => (min <= number && number <= max);

isBoolean

Same as typeof value === 'boolean'.

const isBoolean = require('1-liners/isBoolean');

isBoolean(false);            // => true
isBoolean(true);             // => true

isBoolean(null);             // => false
isBoolean(/anything else/);  // => false
SpecSource: (value) => typeof value === 'boolean';

isFalse

Same as x === false.

const isFalse = require('1-liners/isFalse');

isFalse(false);  // => true

isFalse('yes');  // => false
isFalse(true);   // => false
isFalse([]);     // => false
isFalse('');     // => false
isFalse(0);      // => false
SpecSource: (x) => x === false;

isFalsy

Same as !.

const isFalsy = require('1-liners/isFalsy');

isFalsy('yes');  // => false
isFalsy(true);   // => false
isFalsy([]);     // => false

isFalsy('');     // => true
isFalsy(0);      // => true
isFalsy(false);  // => true
SpecSource: (x) => !x;

isFunction

Same as typeof value === 'function'.

const isFunction = require('1-liners/isFunction');

isFunction(function() {});        // => true
isFunction(function named() {});  // => true

isFunction('any other value');    // => false
SpecSource: (value) => typeof value === 'function';

isNull

Same as === null.

const isNull = require('1-liners/isNull');

isNull(null);             // => true

isNull(undefined);        // => false
isNull(NaN);              // => false
isNull('anything else');  // => false
SpecSource: (value) => (value === null);

isNumber

Same as typeof value === 'number'. Use Number.isFinite instead if you want to filter out NaN and Infinity.

const isNumber = require('1-liners/isNumber');

isNumber(1);                // => true
isNumber(3.14);             // => true
isNumber(NaN);              // => true
isNumber(Infinity);         // => true

isNumber('3.14');           // => false
isNumber(/anything else/);  // => false
SpecSource: (value) => typeof value === 'number';

isObject

Same as value !== null && typeof value === 'object'.

const isObject = require('1-liners/isObject');

isObject({});               // => true
isObject([]);               // => true
isObject(/anything/);       // => true

isObject(null);             // => false
isObject('anything else');  // => false
SpecSource: (value) => (value !== null && typeof value === 'object');

isPlainObject

Checks if an object inherits directly from null or Object.prototype – like an object literal ({...}) does.

Heads up! This function is not supported on IE 10 and below.

const isPlainObject = require('1-liners/isPlainObject');

isPlainObject({});                   // => true
isPlainObject(Object.create(null));  // => true

isPlainObject(null);                 // => false
isPlainObject([]);                   // => false
isPlainObject(/anything else/);      // => false
SpecSource: (value) => (value && typeof value === 'object' && (value.__proto__ == null || value.__proto__ === Object.prototype));

isPrototypeOf

Check if an object's prototype exists in another object's prototype chain

function Foo(){};
function Bar(){};

Bar.prototype = new Foo();

const foo = new Foo();
const bar = new Bar();

Foo.prototype.isPrototypeOf(bar); // => true
Bar.prototype.isPrototypeOf(foo); // => false
SpecSource: (prototypeObj, obj) => prototypeObj.prototype.isPrototypeOf(obj)

isString

Same as typeof value === 'string'.

const isString = require('1-liners/isString');

isString('');               // => true
isString('anything');       // => true

isString(/anything else/);  // => false
SpecSource: (value) => typeof value === 'string';

isTrue

Same as x === true.

const isTrue = require('1-liners/isTrue');

isTrue(true);   // => true

isTrue('yes');  // => false
isTrue([]);     // => false
isTrue('');     // => false
isTrue(0);      // => false
isTrue(false);  // => false
SpecSource: (x) => x === true;

isTruthy

Same as !!.

const isTruthy = require('1-liners/isTruthy');

isTruthy('yes');  // => true
isTruthy(true);   // => true
isTruthy([]);     // => true

isTruthy('');     // => false
isTruthy(0);      // => false
isTruthy(false);  // => false
SpecSource: (x) => !!x;

isTypeOf

Same as typeof value === TYPE.

const isTypeOf = require('1-liners/isTypeOf');

isTypeOf('boolean', false);            // => true
isTypeOf('boolean', true);             // => true

isTypeOf('boolean', null);             // => false
isTypeOf('boolean', /anything else/);  // => false
SpecSource: (type, value) => typeof value === type;

isUndefined

Returns true if a value or reference is undefined.

const isUndefined = require('1-liners/isUndefined');

isUndefined(undefined);        // => true

isUndefined(null);             // => false
isUndefined(false);            // => false
isUndefined(NaN);              // => false
isUndefined('anything else');  // => false
SpecSource: (value) => (value === void 0);

isUnknown

Same as == null.

const isUnknown = require('1-liners/isUnknown');

isUnknown(null);             // => true
isUnknown(undefined);        // => true

isUnknown(false);            // => false
isUnknown('');               // => false
isUnknown(NaN);              // => false
isUnknown(/anything else/);  // => false
SpecSource: (value) => (value == null);

join

Same as [1, 'liners'].join('-')

const join = require('1-liners/join');

join('-', [1, 'liners']); // => '1-liners'
SpecSource: (superglue, arr) => arr.join(superglue);

keyBy

Creates an object composed of keys generated from the results of running each element of collection thru iteratee.

const keyBy = require('1-liners/keyBy');
const array = [{id: 1, name: 'One'}, {id: 2, name: 'Two'}];
const dict = keyBy(array, o => o.id); // => {1: {id: 1, name: 'One'}, 2: {id: 2, name: 'Two'} }
SpecSource: (array, iteratee) => array.reduce((result, item) => (result[iteratee(item)] = item, result), {});

keys

Same as Object.keys(obj).

const keys = require('1-liners/keys');

keys({ 100: 'a', 2: 'b', 7: 'c' }); // => ['2', '7', '100']
keys([1, 2, 3]); // => [0, 1, 2]
SpecSource: (obj) => Object.keys(obj);

last

Returns the last item of array.

const last = require('1-liners/last');

last([1, 2, 3]);  // => 3
SpecSource: (array) => array[array.length - 1];

lastIndexOf

Same as 'wow'.lastIndexOf('w').

const lastIndexOf = require('1-liners/lastIndexOf');

lastIndexOf('f', 'waffle') // => 3
SpecSource: (searchValue, str) => str.lastIndexOf(searchValue);

length

Returns the length of an array.

const length = require('1-liners/length');

length([0, 1, 2]); // => 3
SpecSource: (arr) => arr.length;

lessOrEqual

Same as a <= b.

const lessOrEqual = require('1-liners/lessOrEqual');

lessOrEqual(1, 2); // => true
lessOrEqual(1, 1); // => true
lessOrEqual(2, 1); // => false
SpecSource: (x, y) => x <= y;

lessThan

Same as a < b.

const lessThan = require('1-liners/lessThan');

lessThan(1, 2); // => true
lessThan(1, 1); // => false
lessThan(2, 1); // => false
SpecSource: (x, y) => x < y;

localeCompare

Same as 'A'.localeCompare('B').

const localeCompare = require('1-liners/localeCompare');

localeCompare('B', 'A') // => -1
SpecSource: (compareString, str) => str.localeCompare(compareString);

looseEqual

Same as a == b.

const looseEqual = require('1-liners/looseEqual');

looseEqual(true, true); // => true
looseEqual(false, true); // => false
looseEqual(1, true); // => true
SpecSource: (x, y) => x == y;

map

Same as [1, 2, 3].map(Math.sqrt).

const map = require('1-liners/map');

map(Math.sqrt, [9, 25]); // => [3, 5]
SpecSource: (map, arr) => arr.map(map);

match

Same as haystack.match(needle).

const match = require('1-liners/match');

match(/\d+/g, 'Items: 3,2'); // => ["3", "2"]
SpecSource: (needle, haystack) => haystack.match(needle);

max

Same as Math.max – but with a stable number of arguments.

const max = require('1-liners/max');

max(3, 6);  // => 6

[3, 6, 9].reduce(max);       // => 9
[3, 6, 9].reduce(Math.max);  // => NaN
SpecSource: (a, b) => ((a > b) ? a : b);

method

Same as object[method](...args)

const method = require('1-liners/method');

const object = {
	base: 1,
	add(number) { return this.base + number; },
};

method('add', object)(5);  // => 6
SpecSource: (method, object) => (...args) => object[method](...args);

min

Same as Math.min – but with a stable number of arguments.

const min = require('1-liners/min');

min(3, 6);  // => 3

[3, 6, 1].reduce(min);       // => 1
[3, 6, 1].reduce(Math.min);  // => NaN
SpecSource: (a, b) => ((a > b) ? b : a);

minus

Same as a - b

const minus = require('1-liners/minus');

minus(3, 2); // => 1
SpecSource: (a, b) => a - b;

nand

Same as !(a && b).

const nand = require('1-liners/nand');

nand(0, 0); // => true
nand(1, 1); // => false
SpecSource: (x, y) => !(x && y);

noop

Same as function(){}.

const noop = require('1-liners/noop');

window.console = {
		log: noop,
		error: noop,
		warn: noop,
		table: noop
};
SpecSource: () => {};

nor

Same as !(a || b).

const nor = require('1-liners/nor');

nor(0, 0); // => true
nor(1, 0); // => false
SpecSource: (x, y) => !(x || y);

normalize

Same as 'STR'.normalize().

const normalize = require('1-liners/normalize');

normalize('NFD', '\u1E9B\u0323') // => ẛ̣
SpecSource: (form, str) => str.normalize(form);

not

Same as !a.

const not = require('1-liners/not');

not(true); // => false
not(false); // => true
SpecSource: (a) => !a;

nth

Returns the nth item of an array.

const nth = require('1-liners/nth');

nth(1, [1, 2, 3]); // => 2
SpecSource: (n, arr) => arr[n];

omit

Creates a copy of the object without the given props.

const omit = require('1-liners/omit');

const object = {foo: 1, bar: 2, baz: 3};

omit(['foo', 'baz'], object);  // => {bar: 2}
SpecSource: (props, obj) => props.reduce((newObj, val) => (({ [val]: dropped, ...rest }) => rest)(newObj), obj);

once

Creates a function that is restricted to invoking passed function once.

const once = require('1-liners/once');
let count = 0;
let countOnce = once(() => ++count);
countOnce(); // => 1, (count = 1)
countOnce(); // => 1, (count = 1)
SpecSource: (fn) => ((first = true) => () => first ? (first = !first, fn = fn()) : fn)();

or

Same as a || b.

const or = require('1-liners/or');

or(true, true); // => true
or(false, true); // => true
or(false, false); // => false
SpecSource: (a, b) => a || b;

partial

Partially apply a function.

const partial = require('1-liners/partial');

const add = (a, b, c) => a + b + c;

 const fivePlus = (add, 2, 3);

 fivePlus(4) === 9
SpecSource: (f, ...args) => (...moreArgs) => f(...args, ...moreArgs);

partition

Creates 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 is invoked with one argument: (value).

const partition = require('1-liners/partition');

const [even, odd] = partition([1, 2, 3, 4], n => n % 2 === 0); // => even: [2, 4], odd: [1, 3]
SpecSource: (array, predicate) => array.reduce((result, item) => (result[Number(!predicate(item))].push(item), result), [[], []]);

pick

Copies only specified properties from an object into a new object.

const pick = require('1-liners/pick');

const object = {foo: 1, bar: 2, baz: 3};

pick(['foo', 'baz'], object);  // => {foo: 1, baz: 3}
SpecSource: (properties, object) => Object.assign({}, ...properties.map(key => ({[key]: object[key]})));

pipe

Pipe arguments through functions.

const pipe = require('1-liners/pipe');

pipe(f, g)(1, 2) === g(f(1, 2));
SpecSource: (f, g) => (...args) => g(f(...args));

pipeAll

Pipe arguments through an array of functions.

const pipeAll = require('1-liners/pipeAll');

pipeAll([f, g, h])(1, 2) === h(g(f(1, 2)));
SpecSource: (fns) => fns.reduceRight( (f, g) => (...args) => f(g(...args)) );

plus

Same as a + b.

const plus = require('1-liners/plus');

plus(2, 8);      // => 10
plus('a', 'b');  // => 'ab'
SpecSource: (a, b) => a + b;

product

Returns the product of all items of an array.

const product = require('1-liners/product');

product([2, 3, 4]);        // => 24
product([]);               // => 1
SpecSource: (array) => array.reduce((a, b) => (a * b), 1);

property

Same as object[property]

const property = require('1-liners/property');

const object = {foo: 1};

property('foo', object);  // => 1
SpecSource: (property, object) => object[property];

propertyIsEnumerable

Returns a Boolean indicating whether the specified property is enumerable.

const FOO = {
 'bar' : 'bar'
}
FOO.propertyIsEnumerable('bar') // => true
FOO.propertyIsEnumerable('length') // => false
SpecSource: (obj, property) => obj.propertyIsEnumerable(property)

push

Same as push but immutable.

const push = require('1-liners/push');

push(4, [1, 2, 3]); // => [1, 2, 3, 4]
SpecSource: (element, arr) => [...arr, element];

put

Same as Object.assign({}, obj, {[key]: val})

const put = require('1-liners/put');

const object = {id: 1};

put('name', 'stoeffel', object);  // => { id: 1, name: 'stoeffel' }
SpecSource: (key, val, obj) => Object.assign({}, obj, {[key]: val});

range

A pure function to generate a range of numbers from start(including) to end(excluding)

const range = require('1-liners/range');

range(1, 5); // => [1, 2, 3, 4, 5]
SpecSource: (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);

reduce

Same as [1, 2, 3].reduce(sum).

const reduce = require('1-liners/reduce');

reduce(sum, [1, 2, 3]); // => 6
SpecSource: (func, arr) => arr.reduce(func);

reduceRight

Same as [1, 2, 3].reduceRight(sub).

const reduceRight = require('1-liners/reduceRight');

reduceRight(sub, [1, 2, 3]); // => -4
SpecSource: (reduce, arr) => arr.reduceRight(reduce);

repeat

Same as 'STR'.repeat(1).

const repeat = require('1-liners/repeat');

repeat(1, 'super') // => super
SpecSource: (times, str) => str.repeat(times);

replace

Same as haystack.replace(needle, replace).

const replace = require('1-liners/replace');

replace(/\d+/g, sub => `"${sub}"`, 'Items: 3,2'); // => Items: "3","2"
replace(':', '=', 'Items: 3,2'); // => Items= 3,2
SpecSource: (needle, replace, haystack) => haystack.replace(needle, replace);

search

Same as 'STR'.search(regexp).

const search = require('1-liners/search');

search(/s/, 'super') // => 0
SpecSource: (regexp, str) => str.search(regexp);

shallowClone

Copy all properties of an object into a new plain object.

import shallowClone from '1-liners/shallowClone';

const source = {
	value: 'value',
	reference: /reference/,
};
const target = shallowClone(source);

target === source                      // => false
target.value === source.value          // => true
target.reference === source.reference  // => true
SpecSource: (object) => Object.assign({}, object);

shave

Shave ensures that a function is called with n arguments.

const shave = require('1-liners/shave');

map(parseInt, [0, 1.1, 2.2]); // => [0, NaN, NaN]
map(shave(1, parseInt), [0, 1.1, 2.2]); // => [0, 1, 2]
SpecSource: (shave, f) => (...args) => f(...(args.slice(0, shave)));

signum

Returns the sign of a number. 1 if n is positive, -1 if n is negative and 0 if n is 0. Otherwise returns NaN.

const signum = require('1-liners/signum');

signum(-5);         // => -1
signum(-Infinity);  // => -1

signum(10);         // => 1
signum(Infinity);   // => 1

signum(0);          // => 0
signum(-0);         // => 0
SpecSource: (n) => (n === 0 ? 0 : (n > 0 ? 1 : (n < 0 ? -1 : NaN)));

slice

Same as '1-liners'.slice(2,4) or [1,2,3,4].slice(1,3) Use in place of '1-liners'.substring(2,6)

const slice = require('1-liners/slice');

slice(2, 6, '1-liners'); // => 'line'
slice(1, 3, [1,2,3,4]); // => [2,3]
SpecSource: (startIndex, endIndex, arg) => arg.slice(Math.max(startIndex, 0), endIndex);

some

Same as [1,2,3].some(GreaterThan16)

const some = require('1-liners/some');

some(elem => elem > 16, [16,17,18]); // => true
SpecSource: (some, arr) => arr.some(some);

split

Same as '1-liners'.split('-')

const split = require('1-liners/split');

split('-', '1-liners'); // => [1, 'liners']
SpecSource: (split, str) => str.split(split);

startsWith

Same as str.startsWith(searchString).

const startsWith = require('1-liners/startsWith');

startsWith('1', '1-liners');  // => true
startsWith('stoeffel', 'nope');  // => false
SpecSource: (searchString, str) => str.startsWith(searchString);

startsWithAt

Same as str.startsWith(searchString, position).

const startsWithAt = require('1-liners/startsWithAt');

startsWithAt(2, 'liners', '1-liners/startsWithAt');  // => true
startsWithAt(2, 'stoeffel', 'nope');  // => false
SpecSource: (position, searchString, str) => str.startsWith(searchString, position);

sum

Sums all items of an array.

const sum = require('1-liners/sum');

sum([1, 2, 3]);        // => 6
sum([]);               // => 0
SpecSource: (array) => array.reduce((a, b) => (a + b), 0);

tail

Returns the tail of an array

const tail = require('1-liners/tail');

tail([1, 2, 3]); // => [2, 3]
SpecSource: ([,...tail]) => tail;

take

Take n items of an array. Same as arr.slice(0, n).

const take = require('1-liners/take');

take(2, [1, 2, 3]); // => [1, 2]
SpecSource: (take, arr) => arr.slice(0, take);

takeUntil

Take items of an array until they fulfill a predicate.

const takeUntil = require('1-liners/takeUntil');

takeUntil(i => i % 2 === 1, [2, 4, 6, 8, 7, 8, 8]); // => [2, 4, 6, 8]
SpecSource: (pred, arr) => arr.reduce((newArr, i) => { if (pred(i)) arr.length = 0; else newArr.push(i); return newArr; }, []);

takeWhile

Take items of an array while they fulfill a predicate.

const takeWhile = require('1-liners/takeWhile');

takeWhile(i => i % 2 === 0, [2, 4, 6, 8, 7, 8, 8]); // => [2, 4, 6, 8]
SpecSource: (pred, arr) => arr.reduce((newArr, i) => { if (!pred(i)) arr.length = 0; else newArr.push(i); return newArr; }, []);

test

Same as regexObj.test(str).

const test = require('1-liners/test');
const haystack = 'hAyHAYhayneEdLEHayHAy';

test(haystack, /needle/);   // => false
test(haystack, /needle/i);  // => true
SpecSource: (str, regexObj) => regexObj.test(str);

times

Same as a * b

const times = require('1-liners/times');

times(3, 2); // => 6
SpecSource: (a, b) => a * b;

toLowerCase

Same as 'STR'.toLowerCase().

const toLowerCase = require('1-liners/toLowerCase');

toLowerCase('HALLO') // => 'hallo'
SpecSource: (str) => str.toLowerCase();

toType

typeOf is a function that return the true type of a variable.

import toType from '1-liners/toType';

 toType({a: 4}); //"object"
 toType([1, 2, 3]); //"array"
 (function() {console.log(toType(arguments))})(); //arguments
 toType(new ReferenceError); //"error"
 toType(new Date); //"date"
 toType(/a-z/); //"regexp"
 toType(Math); //"math"
 toType(JSON); //"json"
 toType(new Number(4)); //"number"
 toType(new String("abc")); //"string"
 toType(new Boolean(true)); //"boolean"
SpecSource: (obj) => ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();

toUpperCase

Same as 'str'.toUpperCase().

const toUpperCase = require('1-liners/toUpperCase');

toUpperCase('hallo') // => 'HALLO'
SpecSource: (str) => str.toUpperCase();

trim

Same as 'STR'.trim().

const trim = require('1-liners/trim');

trim('  super  ') // => super
SpecSource: (str) => str.trim();

truncate

Truncate string when longer than maxLength and add the Unicode Character horizontal ellipsis keeping the total within maxLength.

const truncate = require('1-liners/truncate');

truncate('super', 5) // => super
truncate('super', 4) // => sup…
SpecSource: (str, maxLength) => str.length > maxLength ? `${str.substr(0, maxLength - 1)}…` : str

uncurry

Uncurry a function – collapse 2 lists of parameters into one.

import uncurry from '1-liners/uncurry';

const f = (a) => (b) => a + b;
const  = uncurry(f);
(1, 2);  // => 3

const g = (a) => (b, c) => a + b + c
const  = uncurry(g);
(1, 2, 3);  // => 6
SpecSource: (f) => (a, ...rest) => f(a)(...rest);

uncurry3

Uncurry a function – collapse 3 lists of parameters into one.

import uncurry3 from '1-liners/uncurry3';

const f = (a) => (b) => (c) => a + b + c;
const  = uncurry3(f);
(1, 2, 3);  // => 6

const g = (a) => (b) => (c, d) => a + b + c + d;
const  = uncurry3(g);
(1, 2, 3, 4);  // => 10
SpecSource: (f) => (a, b, ...rest) => f(a)(b)(...rest);

unfold

Builds a list from a seed value.

const unfold = require('1-liners/unfold');

const fn = n => n < 20 ?  [n, n + 1] : false;
unfold(fn, 10); // => [10,11,12,13,14,15,16,17,18,19]

// range in terms of unfold
const range = (from, to) => unfold((seed) => seed < to ? [seed, seed + 1] : false, from);
range(1, 10); // => [1,2,3,4,5,6,7,8,9]
SpecSource: function unfold (fn, seed, acc = [], next = fn(seed)) { return next ? unfold(fn, next[1], [...acc, next[0]]) : acc }

uniq

Creates a duplicate-free version of an array.

const uniq = require('1-liners/uniq');

uniq([1, 2, 2]); // => [1, 2]
SpecSource: (array) => array.filter((value, index, self) => index === self.findIndex(other => other === value));

uniqBy

Remove duplicates from an array of objects by invoking iteratee for each object.

const get = require('1-liners/uniqBy');

let array = [{ id: 1 }, { id: 2 }, { id: 1 }];
uniqBy(array, o => o.id); // => [{ id: 1 }, { id: 2 }]
SpecSource: (array, iteratee) => array.filter((value, index, self) => index === self.findIndex(other => iteratee(other) === iteratee(value)));

values

Get all values of an object Same as Object.keys(obj).map(i => obj[i]).

const values = require('1-liners/values');

values({ 100: 'a', 2: 'b', 7: 'c' }); // => ['a', 'b', 'c']
values(['a', 'b', 'c']); // => ['a', 'b', 'c']
SpecSource: (obj) => Object.keys(obj).map(i => obj[i]);

xor

Same as (x && !y) || (!x && y)

const xor = require('1-liners/xor');

xor(0, 1); // => 1
xor(1, 1); // => 0
SpecSource: (x, y) => (x && !y) || (!x && y)

zip

Creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.

const zip = require('1-liners/zip');
zip(['a', 'b'], [1, 2], [true, false]) // => [['a', 1, true], ['b', 2, false]]
SpecSource: (...arrays) => Array.from({ length: Math.max(...arrays.map(a => a.length)) }).map((_, i) => arrays.map(a => a[i]));