Skip to content

angus-c/just

Just

A library of zero-dependency npm modules that do just one thing. A guilt-free alternative to those bulkier utility libraries. Ideal for PWA development or whenever bytes are precious.

Build status

We welcome contributions. Please follow our contribution guidelines.

Try 🍦

A REPL for every utility (powered by RunKit)

Read 📚

ES and CJS modules available for every utility

All packages support ES module or Common JS syntax without requiring transpilation

// esm (node / bundler) import clone from 'just-clone'; // esm (native browser code) import clone from './node_modules/just-clone/index.mjs'; // cjs const clone = require('just-clone'); 

TypeScript

We've now added TypeScript definitions and tests for every Just utility

Browser/Platform Support 💻

Most utilities still work with any platform that supports ES5, but these are the earliest versions guranteed to support every utility. For guidance, any platform that supports spread in array literals will work with Just.

ChromeSafariFirefoxEdgeNodeMobile SafariAndroid Chrome
46816126.0846

The Modules 📦

Collections

source

🍦 Try it

npm install just-diff
yarn add just-diff

Return an object representing the difference between two other objects Pass converter to format as http://jsonpatch.com

import{diff}from'just-diff';constobj1={a: 4,b: 5};constobj2={a: 3,b: 5};constobj3={a: 4,c: 5};diff(obj1,obj2);[{"op": "replace","path": ['a'],"value": 3}]diff(obj2,obj3);[{"op": "remove","path": ['b']},{"op": "replace","path": ['a'],"value": 4}{"op": "add","path": ['c'],"value": 5}]// using converter to generate jsPatch standard pathsimport{diff,jsonPatchPathConverter}from'just-diff'diff(obj1,obj2,jsonPatchPathConverter);[{"op": "replace","path": '/a',"value": 3}]diff(obj2,obj3,jsonPatchPathConverter);[{"op": "remove","path": '/b'},{"op": "replace","path": '/a',"value": 4}{"op": "add","path": '/c',"value": 5}]// arraysconstobj4={a: 4,b: [1,2,3]};constobj5={a: 3,b: [1,2,4]};constobj6={a: 3,b: [1,2,4,5]};diff(obj4,obj5);[{"op": "replace","path": ['a'],"value": 3}{"op": "replace","path": ['b',2],"value": 4}]diff(obj5,obj6);[{"op": "add","path": ['b',3],"value": 5}]// nested pathsconstobj7={a: 4,b: {c: 3}};constobj8={a: 4,b: {c: 4}};constobj9={a: 5,b: {d: 4}};diff(obj7,obj8);[{"op": "replace","path": ['b','c'],"value": 4}]diff(obj8,obj9);[{"op": "replace","path": ['a'],"value": 5}{"op": "remove","path": ['b','c']}{"op": "add","path": ['b','d'],"value": 4}]

source

🍦 Try it

npm install just-diff-apply
yarn add just-diff-apply

Apply a diff object to an object. Pass converter to apply a http://jsonpatch.com standard patch

import{diffApply}from'just-diff-apply';constobj1={a: 3,b: 5};diffApply(obj1,[{"op": "remove","path": ['b']},{"op": "replace","path": ['a'],"value": 4},{"op": "add","path": ['c'],"value": 5}]);obj1;//{a: 4, c: 5}constobj2={a: 3,b: 5};diffApply(obj2,[{"op": "move","from": ['a'],"path": ['c']},]);obj2;//{b: 5, c: 3}// using converter to apply jsPatch standard paths// see http://jsonpatch.comimport{diffApply,jsonPatchPathConverter}from'just-diff-apply'constobj3={a: 3,b: 5};diffApply(obj3,[{"op": "remove","path": '/b'},{"op": "replace","path": '/a',"value": 4}{"op": "add","path": '/c',"value": 5}],jsonPatchPathConverter);obj3;//{a: 4, c: 5}// arrays (array key can be string or numeric)constobj4={a: 4,b: [1,2,3]};diffApply(obj4,[{"op": "replace","path": ['a'],"value": 3}{"op": "replace","path": ['b',2],"value": 4}{"op": "add","path": ['b',3],"value": 9}]);obj4;//{a: 3, b: [1, 2, 4, 9]}// nested pathsconstobj5={a: 4,b: {c: 3}};diffApply(obj5,[{"op": "replace","path": ['a'],"value": 5}{"op": "remove","path": ['b','c']}{"op": "add","path": ['b','d'],"value": 4}]);obj5;//{a: 5, b:{d: 4}}

source

🍦 Try it

npm install just-compare
yarn add just-compare

Compare two collections

importcomparefrom'just-compare';// primitives: value1 === value2// functions: value1.toString == value2.toString// arrays: if length, sequence and values of properties are identical// objects: if length, names and values of properties are identicalcompare([1,[2,3]],[1,[2,3]]);// truecompare([1,[2,3],4],[1,[2,3]]);// falsecompare({a: 2,b: 3},{a: 2,b: 3});// truecompare({a: 2,b: 3},{b: 3,a: 2});// truecompare({a: 2,b: 3,c: 4},{a: 2,b: 3});// falsecompare({a: 2,b: 3},{a: 2,b: 3,c: 4});// falsecompare([1,[2,{a: 4}],4],[1,[2,{a: 4}]]);// falsecompare([1,[2,{a: 4}],4],[1,[2,{a: 4}],4]);// truecompare(NaN,NaN);// true

source

🍦 Try it

npm install just-clone
yarn add just-clone

Deep copies objects, arrays, maps and sets

// Deep copies objects and arrays, doesn't clone functionsimportclonefrom'just-clone';vararr=[1,2,3];varsubObj={aa: 1};varobj={a: 3,b: 5,c: arr,d: subObj};varobjClone=clone(obj);arr.push(4);objClone.d.bb=2;obj;//{a: 3, b: 5, c: [1, 2, 3, 4], d:{aa: 1}}objClone;//{a: 3, b: 5, c: [1, 2, 3], d:{aa: 1, bb: 2}}

source

🍦 Try it

npm install just-pluck-it
yarn add just-pluck-it

Pluck a property from each member of a collection

importpluckfrom'just-pluck-it';pluck([{a:1,b:2},{a:4,b:3},{a:2,b:5}],'a');// [1, 4, 2]pluck({x: {a:1,b:2},y: {a:4,b:3},z: {a:2,b:5}},'a');//{x: 1, y: 4, z: 2}

source

🍦 Try it

npm install just-flush
yarn add just-flush

Returns a copy of an array or object with null/undefined members removed

importflushfrom'just-flush';flush([1,undefined,2,null,3,NaN,0]);// [1, 2, 3, NaN, 0]flush([true,null,false,true,[null],undefined]);// [true, false, true, [null]]flush({a: 2,b: null,c: 4,d: undefined});//{a: 2, c: 4}flush('something');// undefinedflush();// undefined

Objects

source

🍦 Try it

npm install just-extend
yarn add just-extend

Extend an object

importextendfrom'just-extend';varobj={a: 3,b: 5};extend(obj,{a: 4,c: 8});//{a: 4, b: 5, c: 8}obj;//{a: 4, b: 5, c: 8}varobj={a: 3,b: 5};extend({},obj,{a: 4,c: 8});//{a: 4, b: 5, c: 8}obj;//{a: 3, b: 5}vararr=[1,2,3];varobj={a: 3,b: 5};extend(obj,{c: arr});//{a: 3, b: 5, c: [1, 2, 3]}arr.push(4);obj;//{a: 3, b: 5, c: [1, 2, 3, 4]}vararr=[1,2,3];varobj={a: 3,b: 5};extend(true,obj,{c: arr});//{a: 3, b: 5, c: [1, 2, 3]}arr.push(4);obj;//{a: 3, b: 5, c: [1, 2, 3]}extend({a: 4,b: 5});//{a: 4, b: 5}extend({a: 4,b: 5},3);{a: 4,b: 5}extend({a: 4,b: 5},true);{a: 4,b: 5}extend('hello',{a: 4,b: 5});// throwsextend(3,{a: 4,b: 5});// throws

source

🍦 Try it

npm install just-merge
yarn add just-merge

Shallow assign. Like just-extend but without deep copy option.

importmergefrom'just-merge';letobj={a: 3,b: 5};merge(obj,{a: 4,c: 8});//{a: 4, b: 5, c: 8}obj;//{a: 4, b: 5, c: 8}letobj={a: 3,b: 5};merge({},obj,{a: 4,c: 8});//{a: 4, b: 5, c: 8}obj;//{a: 3, b: 5}letarr=[1,2,3];letobj={a: 3,b: 5};merge(obj,{c: arr});//{a: 3, b: 5, c: [1, 2, 3]}arr.push[4];obj;//{a: 3, b: 5, c: [1, 2, 3, 4]}merge({a: 4,b: 5});//{a: 4, b: 5}merge(3,{a: 4,b: 5});// throwsmerge({a: 4,b: 5},3);// throwsmerge({a: 4,b: 5},{b: 4,c: 5},'c');// throws

source

🍦 Try it

npm install just-values
yarn add just-values

Return property values as an array

constvalues=require('just-values');values({a: 4,c: 8});// [4, 8]values({a: {aa: 2},b: {bb: 4}});// [{aa: 2},{bb: 4}]values({});// []values([1,2,3]);// [1, 2, 3]values(function(a,b){returna+b;});// []values(newString('hello'));// ['h', 'e', 'l', 'l', 'o']values(1);// throws exceptionvalues(true);// throws exceptionvalues(undefined);// throws exceptionvalues(null);// throws exception

source

🍦 Try it

npm install just-entries
yarn add just-entries

Return object entries as an array of [key, value] pairs

importentriesfrom'just-entries';// Object:entries({c: 8,a: 4});// [['c', 8], ['a', 4]]entries({b: {bb: 4},a: {aa: 2}});// [['b',{bb: 4}], ['a',{aa: 2}]]entries({});// []// Array:entries([{c: 8},{a: 4}]);// [[0,{c: 8}], [1,{a: 4}]]entries(['À','mauvais','ouvrier','point','de','bon','outil'])// [[0, 'À'], [1, 'mauvais'] ... [6, 'outil']]entries([]);// []

source

🍦 Try it

npm install just-pick
yarn add just-pick

Copy an object but with only the specified keys

importpickfrom'just-pick';varobj={a: 3,b: 5,c: 9};pick(obj,['a','c']);//{a: 3, c: 9}pick(obj,'a','c');//{a: 3, c: 9}pick(obj,['a','b','d']);//{a: 3, b: 5}pick(obj,['a','a']);//{a: 3}

source

🍦 Try it

npm install just-omit
yarn add just-omit

Copy an object but omit the specified keys

importomitfrom'just-omit';varobj={a: 3,b: 5,c: 9};omit(obj,['a','c']);//{b: 5}omit(obj,'a','c');//{b: 5}omit(obj,['a','b','d']);//{c: 9}omit(obj,['a','a']);//{b: 5, c: 9}

source

🍦 Try it

npm install just-is-empty
yarn add just-is-empty

Return true if object has no enumerable key values

importisEmptyfrom'just-is-empty';isEmpty({a: 3,b: 5})// falseisEmpty([1,2])// falseisEmpty(newSet([1,2,2]))// falseisEmpty((newMap()).set('a',2))// falseisEmpty({})// trueisEmpty([])// trueisEmpty(newSet())// trueisEmpty(newMap())// trueisEmpty('abc')// falseisEmpty('')// trueisEmpty(0)// trueisEmpty(1)// trueisEmpty(true)// trueisEmpty(Symbol('abc'));// trueisEmpty(//); // trueisEmpty(newString('abc'));// falseisEmpty(newString(''));// trueisEmpty(newBoolean(true));// trueisEmpty(null)// trueisEmpty(undefined)// true

source

🍦 Try it

npm install just-is-circular
yarn add just-is-circular

Return true if object has a circular reference NOTE: not supported in IE or microsoft edge

importisCircularfrom'just-is-circular';consta={};a.b=a;isCircular(a);// trueconsta={};a.b={c: a};isCircular(a);// trueconsta={};a.b={c: 4};isCircular(a);// falseconsta=[];a.push(a);isCircular(a);// trueisCircular({});// falseisCircular('hi');// falseisCircular(undefined);// false

source

🍦 Try it

npm install just-is-primitive
yarn add just-is-primitive

Determine if a value is a primitive value

importisPrimitivefrom'just-is-primitive';isPrimitive('hi')// trueisPrimitive(3)// trueisPrimitive(true)// trueisPrimitive(false)// trueisPrimitive(null)// trueisPrimitive(undefined)// trueisPrimitive(Symbol())// trueisPrimitive({})// falseisPrimitive([])// falseisPrimitive(function(){})// falseisPrimitive(newDate())// falseisPrimitive(/a/)// false

source

🍦 Try it

npm install just-filter-object
yarn add just-filter-object

Filter an object

importfilterfrom'just-filter';// returns a new object containing those original properties for which the predicate returns truthyfilter({a: 3,b: 5,c: 9},(key,value)=>value<6);//{a: 3, b: 5}filter({a1: 3,b1: 5,a2: 9},(key,value)=>key[0]=='a');//{a1: 3, a2: 9}filter({a: 3,b: 5,c: null},(key,value)=>value);//{a: 3, b: 5}

source

🍦 Try it

npm install just-map-object
yarn add just-map-object

Map an object, passing key and value to predicates

importmapfrom'just-map-object';// DEPRECATED: use just-map-valuesmap({a: 3,b: 5,c: 9},(key,value)=>value+1);//{a: 4, b: 6, c: 10}map({a: 3,b: 5,c: 9},(key,value)=>key);//{a: 'a', b: 'b', c: 'c'}map({a: 3,b: 5,c: 9},(key,value)=>key+value);//{a: 'a3', b: 'b5', c: 'c9'}```

source

🍦 Try it

npm install just-map-values
yarn add just-map-values

Map an object, predicate updates values, receives (value, key, object)

importmapfrom'just-map-values';// predicate updates values, receives (value, key, obj)map({a: 3,b: 5,c: 9},(value)=>value+1);//{a: 4, b: 6, c: 10}map({a: 3,b: 5,c: 9},(value,key)=>value+key);//{a: 3a, b: 5b, c: 9c}map({a: 3,b: 5,c: 9},(value,key,obj)=>obj.b);//{a: 5, b: 5, c: 5}

source

🍦 Try it

npm install just-map-keys
yarn add just-map-keys

Map an object, predicate updates keys, receives (value, key, object)

importmapfrom'just-map-keys';// predicate updates keys, receives (value, key, object)map({a: 'cow',b: 'sheep',c: 'pig'},(value)=>value);//{cow: 'cow', sheep: 'sheep', pig: 'pig'}map([4,5,6],(value,key)=>key+1);//{1: 4, 2: 5, 3: 6}map({a: 3,b: 5,c: 9},(value,key)=>key+value);//{a3: 3, b5: 5, c9: 9}map({a: 3,b: 5,c: 9},(value,key,obj)=>obj.b+value+key);//{'8a': 3, '10b': 5, '14c': 9}

source

🍦 Try it

npm install just-deep-map-values
yarn add just-deep-map-values

Returns an object with values at all depths mapped according to the provided function

importdeepMapValuesfrom'just-deep-map-values';constsquareFn=(number)=>number*number;deepMapValues({a: 1,b: {c: 2,d: {e: 3}}},squareFn);// =>{a: 1, b:{c: 4, d:{e: 9 }}}

source

🍦 Try it

npm install just-reduce-object
yarn add just-reduce-object

Reduce an object

importreducefrom'just-reduce-object';// applies a function against an accumulator and each key-value pairs of the object// to reduce it to a single valuereduce({a: 3,b: 5,c: 9},(acc,key,value,index,keys)=>{acc[value]=key;returnacc;},{});//{3: 'a', 5: 'b', 9: 'c'}reduce({a: 3,b: 5,c: 9},(acc,key,value,index,keys)=>{acc+=value;returnacc;});// 17

source

🍦 Try it

npm install just-safe-get
yarn add just-safe-get

Get value at property, don't throw if parent is undefined

importgetfrom'just-safe-get';constobj={a: {aa: {aaa: 2}},b: 4};get(obj,'a.aa.aaa');// 2get(obj,['a','aa','aaa']);// 2get(obj,'b.bb.bbb');// undefinedget(obj,['b','bb','bbb']);// undefinedget(obj.a,'aa.aaa');// 2get(obj.a,['aa','aaa']);// 2get(obj.b,'bb.bbb');// undefinedget(obj.b,['bb','bbb']);// undefinedget(obj.b,'bb.bbb',5);// 5get(obj.b,['bb','bbb'],true);// trueget(null,'a');// undefinedget(undefined,['a']);// undefinedget(null,'a',42);// 42get(undefined,['a'],42);// 42constobj={a: {}};constsym=Symbol();obj.a[sym]=4;get(obj.a,sym);// 4

source

🍦 Try it

npm install just-safe-set
yarn add just-safe-set

Set value at property, create intermediate properties if necessary

importsetfrom'just-safe-set';constobj1={};set(obj1,'a.aa.aaa',4);// trueobj1;//{a:{aa:{aaa: 4}}}constobj2={};set(obj2,['a','aa','aaa'],4);// trueobj2;//{a:{aa:{aaa: 4}}}constobj3={a: {aa: {aaa: 2}}};set(obj3,'a.aa.aaa',3);// trueobj3;//{a:{aa:{aaa: 3}}}constobj5={a: {}};constsym=Symbol();set(obj5.a,sym,7);// trueobj5;//{a:{Symbol(): 7}}

source

🍦 Try it

npm install just-typeof
yarn add just-typeof

Type inferer

importtypeOffrom'just-typeof';typeOf({});// 'object'typeOf([]);// 'array'typeOf(function(){});// 'function'typeOf(/a/);// 'regexp'typeOf(newDate());// 'date'typeOf(null);// 'null'typeOf(undefined);// 'undefined'typeOf('a');// 'string'typeOf(1);// 'number'typeOf(true);// 'boolean'

source

🍦 Try it

npm install just-flip-object
yarn add just-flip-object

Flip the keys and values

importflipfrom'just-flip-object';// flip the key and valueflip({a: 'x',b: 'y',c: 'z'});//{x: 'a', y: 'b', z: 'c'}flip({a: 1,b: 2,c: 3});//{'1': 'a', '2': 'b', '3': 'c'}flip({a: false,b: true});//{false: 'a', true: 'b'}

source

🍦 Try it

npm install just-has
yarn add just-has

Return a boolen indicating the existence of a deep property, don't throw if parent is undefined

importhasfrom'just-has';constobj={a: {aa: {aaa: 2}},b: 4};has(obj,'a.aa.aaa');// truehas(obj,['a','aa','aaa']);// truehas(obj,'b.bb.bbb');// falsehas(obj,['b','bb','bbb']);// falsehas(obj.a,'aa.aaa');// truehas(obj.a,['aa','aaa']);// truehas(obj.b,'bb.bbb');// falsehas(obj.b,['bb','bbb']);// falsehas(null,'a');// falsehas(undefined,['a']);// falseconstobj={a: {}};constsym=Symbol();obj.a[sym]=4;has(obj.a,sym);// true

Arrays

source

🍦 Try it

npm install just-cartesian-product
yarn add just-cartesian-product

Takes an input of an array of arrays and returns their Cartesian product.

importcartesianProductfrom'just-cartesian-product';cartesianProduct([[1,2],['a','b']]);// [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]cartesianProduct([[1,2],['a','b','c']]);// [[1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, 'b'], [2, 'c']]cartesianProduct([]);// []cartesianProduct();// throws

source

🍦 Try it

npm install just-unique
yarn add just-unique

Dedupes an array

importuniquefrom'just-unique';unique([1,2,3,2,3,4,3,2,1,3]);// [1, 2, 3, 4]vara={a: 3};varb={b: 4};varc={c: 5};unique([a,a,b,c,b]);// [a, b, c]unique([1,'1',2,'2',3,2]);// [1, '1', 2, '2', 3]// declaring sorted array for performanceunique([1,1,'1',2,2,5,'5','5'],true);// [1, '1', 2, 5, '6']// declaring strings array for performanceunique(['a','c','b','c','a'],false,true);// ['a', 'b', 'c']

source

🍦 Try it

npm install just-flatten-it
yarn add just-flatten-it

Return a flattened array

importflattenfrom'just-flatten-it';flatten([[1,[2,3]],[[4,5],6,7,[8,9]]]);// [1, 2, 3, 4, 5, 6, 7, 8, 9]flatten([[1,[2,3]],[[4,5],6,7,[8,9]]],1);// [1, [2, 3], [[4, 5], 6, 7, [8, 9]]]

source

🍦 Try it

npm install just-index
yarn add just-index

Return an object from an array, keyed by the value at the given id

importindexfrom'just-index';index([{id: 'first',val: 1},{id: 'second',val: 2}],'id');//{first:{id: 'first', val: 1}, second:{id: 'second', val: 2}}index([{id: 'first',val: 1},null],'id');//{first:{id: 'first', val: 1}}index([],'id');//{}index([],null);// undefinedindex({},'id');// undefined

source

🍦 Try it

npm install just-insert
yarn add just-insert

Inserts a sub-array into an array starting at the given index. Returns a copy

importinsertfrom'just-insert';insert([1,2,5,6],['a','c','e'],2);// [1, 2, 'a', 'c', 'e', 5, 6]insert([1,2,5,6],'a',2);// [1, 2, 'a', 5, 6]insert([1,2,5,6],['a','c','e'],0);// ['a', 'c', 'e', 1, 2, 5, 6]insert([1,2,5,6],['a','c','e']);// ['a', 'c', 'e', 1, 2, 5, 6]

source

🍦 Try it

npm install just-intersect
yarn add just-intersect

Return the intersect of two arrays

importintersectfrom'just-intersect';intersect([1,2,5,6],[2,3,5,6]);// [2, 5, 6]intersect([1,2,2,4,5],[3,2,2,5,7]);// [2, 5] 

source

🍦 Try it

npm install just-compact
yarn add just-compact

Returns a copy of an array with falsey values removed

importcompactfrom'just-compact';compact([1,null,2,undefined,null,NaN,3,4,false,5]);// [1, 2, 3, 4, 5]compact([1,2,[],4,{}]);// [1, 2, [], 4,{}]compact([]);// []compact({});// throws

source

🍦 Try it

npm install just-last
yarn add just-last

Return the last member of an array

importlastfrom'just-last';last([1,2,3,4,5]);// 5last([{a: 1},{b: 1},{c: 1}]);//{c: 1}last([true,false,[true,false]]);// [true, false]last();// undefinedlast([]);// undefinedlast(null);// undefinedlast(undefined);// undefined

source

🍦 Try it

npm install just-tail
yarn add just-tail

Return all but the first element of an array

importtailfrom'just-tail';tail([1,2,3,4,5]);// [2, 3, 4, 5]tail([{a: 1},{b: 1},{c: 1}]);// [{b: 1},{c: 1}]tail([true,false,[true,false]]);// [false, [true, false]]tail([]);// []tail();// undefinedtail(null);// undefinedtail(undefined);// undefined

source

🍦 Try it

npm install just-random
yarn add just-random

Return a randomly selected element in an array

importrandomfrom'just-random';random([1,2,3]);// one of [1, 2, 3], at random

source

🍦 Try it

npm install just-shuffle
yarn add just-shuffle

Return the elements of an array in random order

importshufflefrom'just-shuffle';shuffle([1,2,3]);// array with original elements randomly sortedshuffle([1,2,3],{shuffleAll: true});// array with original elements randomly sorted and all in new postionsshuffle([]);// []shuffle([1]);// [1]shuffle();// throwsshuffle(undefined);// throwsshuffle(null);// throwsshuffle({});// throws

source

🍦 Try it

npm install just-split
yarn add just-split

Splits array into groups of n items each

importsplitfrom'just-split';split([]);// []split([1,2,3,4,5]);// [[1, 2, 3, 4, 5]]split([1,2,3,4,5,6,7,8,9],3);// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]split([1,2,3,4,5,6,7,8,9],'3');// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]split(['a','b','c','d','e'],2);// [['a', 'b'], ['c', 'd'], ['e']]split([1,2,3,4,5,6,7,8],3);// [[1, 2, 3], [4, 5, 6], [7, 8]]

source

🍦 Try it

npm install just-split-at
yarn add just-split-at

Splits an array into two at a given position

importsplitAtfrom'just-split-at';splitAt([1,2,3,4,5],2);// [[1, 2], [3, 4, 5]]splitAt([{a: 1},{b: 1},{c: 1}],-1);// [[{a: 1},{b: 1}], [{c: 1}]]splitAt([],2);// [[], []]splitAt(null,1);// throwssplitAt(undefined,1);// throws

source

🍦 Try it

npm install just-order-by
yarn add just-order-by

Produces a new array, sorted in given order

importorderByfrom'just-order-by';orderBy([10,1,5,20,15,35,30,6,8]);// [1, 5, 6, 8, 10, 15, 20, 30, 35]orderBy([{user: 'fabio',details: {city: 'Milan',age: 34}},{user: 'max',details: {city: 'Munich',age: 29}},{user: 'zacarias',details: {city: 'Sao Paulo',age: 44}},{user: 'robert',details: {city: 'Manchester',age: 28}},{user: 'max',details: {city: 'Zurich',age: 38}},],[{property(v){returnv.details.age;},},]);/*[{user: 'robert', age: 28},{user: 'max', age: 29},{user: 'fabio', age: 34},{user: 'klaus', age: 38},{user: 'zacarias', age: 44},]*/orderBy([{user: 'fabio',age: 34},{user: 'max',age: 29},{user: 'zacarias',age: 44},{user: 'robert',age: 28},{user: 'klaus',age: 38},],[{property: 'user',},]);/*[{user: 'fabio', age: 34},{user: 'klaus', age: 38},{user: 'max', age: 29},{user: 'robert', age: 28},{user: 'zacarias', age: 44},]*/orderBy([{user: 'fabio',age: 34},{user: 'max',age: 29},{user: 'zacarias',age: 44},{user: 'moris',age: 28},{user: 'max',age: 38},],[{property: 'user',order: 'desc',},{property(v){returnv.age;},},]);/*[{ user: 'zacarias', age: 44 },{ user: 'moris', age: 28 },{ user: 'max', age: 29 },{ user: 'max', age: 38 },{ user: 'fabio', age: 34 }]*/

source

🍦 Try it

npm install just-sort-by
yarn add just-sort-by

Produces a new array, sorted in ascending order

importsortByfrom'just-sort-by';sortBy([10,1,5,20,15,35,30,6,8]);// [1, 5, 6, 8, 10, 15, 20, 30, 35]sortBy([{user: 'fabio',details: {city: "Milan",age: 34}},{user: 'max',details: {city: "Munich",age: 29}},{user: 'zacarias',details: {city: "Sao Paulo",age: 44}},{user: 'robert',details: {city: "Manchester",age: 28}},{user: 'klaus',details: {city: "Zurich",age: 38}},],function(o){returno.details.age;});/*[{user: 'robert', age: 28},{user: 'max', age: 29},{user: 'fabio', age: 34},{user: 'klaus', age: 38},{user: 'zacarias', age: 44},]*/sortBy([{user: 'fabio',age: 34},{user: 'max',age: 29},{user: 'zacarias',age: 44},{user: 'robert',age: 28},{user: 'klaus',age: 38},],'user');/*[{user: 'fabio', age: 34},{user: 'klaus', age: 38},{user: 'max', age: 29},{user: 'robert', age: 28},{user: 'zacarias', age: 44},]*/

source

🍦 Try it

npm install just-partition
yarn add just-partition

Elements satisfying predicate added to first array, remainder added to second

importpartitionfrom'just-partition';partition([1,5,2,4,3],n=>n>3);// [[5, 4],[1, 2, 3]]partition(['a',2,3,'3'],x=>typeofx=='string');// [['a', '3'],[2, 3]]partition([1,2,3,4],x=>typeofx=='number');// [[1, 2, 3, 4],[]]partition([1,2,3,4],x=>typeofx=='string');// [[], [1, 2, 3, 4]]partition([],n=>n>3);// [[], []]partition({a: 1,b: 2},n=>n>1);// throwspartition(null,n=>n>1);// throwspartition(undefined,n=>n>1);// throws

source

🍦 Try it

npm install just-permutations
yarn add just-permutations

Returns all permutations of the length N of the elements of the given Array

importpermutationsfrom'just-permutations';permutations([1,2,3]);// [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]permutations([]);// []permutations();// throws

source

🍦 Try it

npm install just-range
yarn add just-range

Generate a range array for numbers

importrangefrom'just-range';range(1,5);// [1, 2, 3, 4]range(5);// [0, 1, 2, 3, 4]range(-5);// [0, -1, -2, -3, -4]range(0,20,5)// [0, 5, 10, 15]

source

🍦 Try it

npm install just-remove
yarn add just-remove

Removes one array from another

importremovefrom'just-remove';remove([1,2,3,4,5,6],[1,3,6]);// [2, 4, 5]

source

🍦 Try it

npm install just-union
yarn add just-union

Returns the union of two arrays

importunionfrom'just-union';union([1,2,5,6],[2,3,4,6]);// [1, 2, 5, 6, 3, 4]

source

🍦 Try it

npm install just-zip-it
yarn add just-zip-it

Returns an array of grouped elements, taking n-th element from every given array

importzipfrom'just-zip-it';zip([1,2,3]);// [[1], [2], [3]]zip([1,2,3],['a','b','c']);// [[1, 'a'], [2, 'b'], [3, 'c']]zip([1,2],['a','b'],[true,false]);//[[1, 'a', true], [2, 'b', false]]zip(undefined,{},false,1,'foo');// []zip([1,2],['a','b'],undefined,{},false,1,'foo');// [[1, 'a'], [2, 'b']]zip([1,2,3],['a','b'],[true]);// [[1, 'a', true], [2, 'b', undefined], [3, undefined, undefined]]

source

🍦 Try it

npm install just-group-by
yarn add just-group-by

Return a grouped object from array

importgroupByfrom'just-group-by';groupBy([6.1,4.2,6.3],Math.floor);//{'4': [4.2], '6': [6.1, 6.3] }groupBy([1,2,3,4,5,6,7,8],function(i){returni%2});//{'0': [2, 4, 6, 8], '1': [1, 3, 5, 7] }

Statistics

source

🍦 Try it

npm install just-mean
yarn add just-mean

The mean (average) value in an array

importmeanfrom'just-mean';mean([1,2,3,2,4,1]);// 2.1666666667mean(3,2,1);// 2mean([4]);// 4mean(['3',2]);// throwsmean();// throws

source

🍦 Try it

npm install just-median
yarn add just-median

Return the median value of an array of numbers

importmedianfrom'just-median';median([1,2,3,4,5]);// 3median([3,-1,2]);// 2median([9,14,14,200,15]);// 14median(1,2,4,3);// 2.5median(['3',2,1]);// throwsmedian();// throws

source

🍦 Try it

npm install just-mode
yarn add just-mode

Return the most frequently occuring number(s)

importmodefrom'just-mode';mode([1,2,3,2]);// 2mode(4,4,1,4);// 4mode(100,100,101,101);// [100, 101]mode(4,3,2,1);// [1, 2, 3, 4]mode(['1',2,2,1,2]);// throwsmode(null);// throws

source

🍦 Try it

npm install just-percentile
yarn add just-percentile

Return the value at the given percentile (using linear interpolation)

importpercentilefrom'just-percentile';percentile([1,2,3],0);// 1percentile([1,2,3],0.5);// 2percentile([1,2,3],1);// 3// See https://en.wikipedia.org/wiki/Percentile (linear interpolation method)percentile([15,20,35,40,50],0.05);// 15percentile([15,20,35,40,50],0.3);// 20percentile([15,20,35,40,50],0.4);// 27.5percentile([15,20,35,40,50],0.95);// 50percentile(1,2,3,50);// throwspercentile(['1',2,3],50);// throwspercentile([],50);// throws

source

🍦 Try it

npm install just-variance
yarn add just-variance

Return the standard deviation of an array or numeric argument list

importvariancefrom'just-variance';variance([1,2,3,2,4,1]);// 1.3666666667variance(3,2,1);// 1variance([100,100,100.1,100]);// 0.0025variance(1,2,3,4,5,-6);// 15.5variance([4]);// throwsvariance(['3',2]);// throwsvariance(NaN,NaN);// throwsvariance();// throws

source

🍦 Try it

npm install just-standard-deviation
yarn add just-standard-deviation

Return the standard deviation of an array or numeric argument list

importstandardDeviationfrom"just-standard-deviation";standardDeviation([1,2,3,2,4,1]);// 1.16904519standardDeviation(3,2,1);// 1standardDeviation([100,100,100.1,100]);// 0.05standardDeviation(1,2,3,4,5,-6);// 3.9370039standardDeviation([4]);// throwsstandardDeviation(["3",2]);// throwsstandardDeviation(NaN,NaN);// throwsstandardDeviation();// throws

source

🍦 Try it

npm install just-skewness
yarn add just-skewness

Return the skewness of an array or numeric argument list using Pearson's second skewness coefficient

importskewnessfrom"just-skewness";// Using Pearson's second skewness coefficientskewness(3,2,1);// 0skewness([1,2,3,2,4,1]);// 0.4276994613841504skewness(1,2,3,4,5,-6);// -0.762000762001143skewness([1,2,3,4,9]);// 0.7705935588815224skewness([4]);// throwsskewness(["3",2]);// throwsskewness(NaN,NaN);// throwsskewness();// throws

Strings

source

🍦 Try it

npm install just-template
yarn add just-template

Interpolate a string with variables

importtemplatefrom'just-template';vardata={a: {aa: {aaa: 'apple',bbb: 'pear'},bb: 'orange'},b: 'plum'};template('2{{a.aa.aaa}}s, a{{a.aa.bbb}}, 3{{a.bb}}s and a{{b}}. Yes 1{{a.aa.bbb}}.',data);// '2 apples, a pear, 3 oranges and a plum. Yes 1 pear.'

source

🍦 Try it

npm install just-truncate
yarn add just-truncate

Truncate a string with a custom suffix

truncate('when shall we three meet again',9);// 'when s...'truncate('when shall we three meet again',10,' (etc)');// 'when (etc)'truncate('when shall we',15,);// 'when shall we'truncate('when shall we',15,'(more)');// 'when shall we'truncate('when shall we',10,' (etc etc etc)');// ' (etc etc etc)'

source

🍦 Try it

npm install just-prune
yarn add just-prune

Prune a string with whole words and a custom suffix

prune('when shall we three meet again',7);// 'when...'prune('when shall we three meet again',7,' (more)';// 'when (more)'prune('when shall we',15,);// 'when shall we'prune('when shall we',15,' (etc)');// 'when shall we'prune('when shall we',7,' (more)');// ' (more)'

source

🍦 Try it

npm install just-squash
yarn add just-squash

Remove all spaces from a string, optionally remove escape sequences too

squash('the cat sat on the mat');// 'thecatsatonthemat'squash(' the cat sat on the mat ');// 'thecatsatonthemat'squash('\tthe cat\n sat \fon \vthe \rmat ');// '\tthecat\nsat\fon\vthe\rmat'squash('\tthe cat\n sat \fon \vthe \rmat ',true);// 'thecatsatonthemat'squash(`the catsat on the mat`,true);// thecatsatonthemat

source

🍦 Try it

npm install just-left-pad
yarn add just-left-pad

Add characters to the left of a string such that its total length is n

importleftPadfrom'just-left-pad';leftPad('hello',9);// ' hello'leftPad('hello',3);// 'hello'leftPad('hello',9,'.');// '....hello'leftPad('hello',9,'..');// '....hello'leftPad('hello',10,'ab');// 'bababhello'leftPad('hello',9,'\uD83D\uDC04');// '🐄🐄🐄🐄hello'leftPad('hello',10,'\uD83D\uDC11\uD83D\uDC04'),// '🐄🐑🐄🐑🐄hello'leftPad('hello',7,'🐄'),// '🐄🐄hello'leftPad(null,7);// throwsleftPad([],4,'*');// throwsleftPad('hello',4,true);// throwsleftPad('hello',-4,true);// throws leftPad('hello',2.3,true);// throws 

source

🍦 Try it

npm install just-right-pad
yarn add just-right-pad

Add characters to the right of a string such that its total length is n

importrightPadfrom'just-right-pad';rightPad('hello',9);// 'hello 'rightPad('hello',3);// 'hello'rightPad('hello',9,'.');// 'hello....'rightPad('hello',9,'..');// 'hello....'rightPad('hello',10,'ab');// 'helloababa'rightPad('hello',9,'\uD83D\uDC04');// 'hello🐄🐄🐄🐄'rightPad('hello',10,'\uD83D\uDC11\uD83D\uDC04'),// 'hello🐑🐄🐑🐄🐑'rightPad('hello',7,'🐄'),// 'hello🐄🐄'rightPad(null,7);// throwsrightPad([],4,'*');// throwsrightPad('hello',4,true);// throwsrightPad('hello',-4,true);// throws rightPad('hello',2.3,true);// throws 

source

🍦 Try it

npm install just-camel-case
yarn add just-camel-case

Convert a string to camel case

importcamelCasefrom'just-camel-case';camelCase('the quick brown fox');// 'theQuickBrownFox'camelCase('the_quick_brown_fox');// 'theQuickBrownFox'camelCase('the-quick-brown-fox');// 'theQuickBrownFox'camelCase('theQuickBrownFox');// 'theQuickBrownFox'camelCase('thequickbrownfox');// 'thequickbrownfox'camelCase('the - quick * brown# fox');// 'theQuickBrownFox'camelCase('behold theQuickBrownFox');// 'beholdTheQuickBrownFox'camelCase('Behold theQuickBrownFox');// 'beholdTheQuickBrownFox'// all caps words are camel-casedcamelCase('The quick brown FOX'),'theQuickBrownFox');// all caps substrings >= 4 chars are camel-casedcamelCase('theQUickBrownFox');// 'theQUickBrownFox'camelCase('theQUIckBrownFox');// 'theQUIckBrownFox'camelCase('theQUICKBrownFox');// 'theQuickBrownFox'

source

🍦 Try it

npm install just-kebab-case
yarn add just-kebab-case

Convert a string to kebab case

importkebabCasefrom'just-kebab-case';kebabCase('the quick brown fox');// 'the-quick-brown-fox'kebabCase('the-quick-brown-fox');// 'the-quick-brown-fox'kebabCase('the_quick_brown_fox');// 'the-quick-brown-fox'kebabCase('theQuickBrownFox');// 'the-quick-brown-fox'kebabCase('theQuickBrown Fox');// 'the-quick-brown-fox'kebabCase('thequickbrownfox');// 'thequickbrownfox'kebabCase('the - quick * brown# fox');// 'the-quick-brown-fox'kebabCase('theQUICKBrownFox');// 'the-q-u-i-c-k-brown-fox'

source

🍦 Try it

npm install just-snake-case
yarn add just-snake-case

Convert a string to snake case

importsnakeCasefrom'just-snake-case';snakeCase('the quick brown fox');// 'the_quick_brown_fox'snakeCase('the-quick-brown-fox');// 'the_quick_brown_fox'snakeCase('the_quick_brown_fox');// 'the_quick_brown_fox'snakeCase('theQuickBrownFox');// 'the_quick_brown_fox'snakeCase('thequickbrownfox');// 'thequickbrownfox'snakeCase('the - quick * brown# fox');// 'the_quick_brown_fox'snakeCase('theQUICKBrownFox');// 'the_q_u_i_c_k_brown_fox'

source

🍦 Try it

npm install just-pascal-case
yarn add just-pascal-case

Convert a string to pascal case

importpascalCasefrom'just-pascal-case';pascalCase('the quick brown fox');// 'TheQuickBrownFox'pascalCase('the_quick_brown_fox');// 'TheQuickBrownFox'pascalCase('the-quick-brown-fox');// 'TheQuickBrownFox'pascalCase('theQuickBrownFox');// 'TheQuickBrownFox'pascalCase('thequickbrownfox');// 'Thequickbrownfox'pascalCase('the - quick * brown# fox');// 'TheQuickBrownFox'pascalCase('theQUICKBrownFox');// 'TheQUICKBrownFox'

source

🍦 Try it

npm install just-capitalize
yarn add just-capitalize

Capitalize the first character of a string

importcapitalizefrom'just-capitalize';/* capitalize('capitals'); // 'Capitals' capitalize('Capitals'); // 'Capitals' capitalize('many words'); // 'Many words' capitalize('!exclaim'); // '!exclaim'*/

source

🍦 Try it

npm install just-replace-all
yarn add just-replace-all

Replace all occurrences of a string within a string with another string

importreplaceAllfrom'just-replace-all';/* replaceAll('hello, world', 'l', 'q'); // 'heqqo, worqd' replaceAll('hello, world', 'l', 'qq'); // 'heqqqqo, worqqd' replaceAll('hello, world', 'll', 'q'); // 'heqo, world' replaceAll('hello, world', '', 'q'); // 'hello, world' replaceAll('hello, world', 'l', ''); // 'heo, word' replaceAll('hello, world', null, 'q'); // 'hello, world' replaceAll('hello, world', 'l'); // throw replaceAll('hello, world'); // throw replaceAll(); // throw replaceAll(null, 'l', 'q'); // throw replaceAll('hello, world', null, 'q'); // throw replaceAll('hello, world', 'l', null); // throw*/

Numbers

source

🍦 Try it

npm install just-clamp
yarn add just-clamp

Restrict a number within a range

importclampfrom'just-clamp';varn=5;clamp(1,n,12);// 5clamp(3,n,1);// 3clamp(8,n,9);// 8clamp(0,n,0);// 0varn=-5;clamp(1,n,12);// 1clamp(-7,n,-8);// -7clamp(NaN,n,8);// NaNclamp(3,n,NaN);// NaN clamp(3,NaN,8);// NaN clamp(undefined,n,8);// throwsclamp(3,n,'h');// throws clamp(3,false,8);// throws 

source

🍦 Try it

npm install just-is-prime
yarn add just-is-prime

Check if number is prime

importisPrimefrom 'just-is-prime; /* isPrime(1); // false isPrime(2); // true isPrime(17); // true isPrime(10); // false isPrime(); // throws isPrime(null); // throws isPrime("js"); // throws isPrime({}); // throws isPrime(function(){}); // throws isPrime([]); // throws*/

source

🍦 Try it

npm install just-modulo
yarn add just-modulo

Modulo of a number and a divisor

importmodulofrom'just-modulo';modulo(7,5);// 2modulo(17,23);// 17modulo(16.2,3.8);// 1modulo(5.8,3.4);//2.4modulo(4,0);// 4modulo(-7,5);// 3modulo(-2,15);// 13modulo(-5.8,3.4);// 1modulo(12,-1);// NaNmodulo(-3,-8);// NaNmodulo(12,'apple');// NaNmodulo('bee',9);// NaNmodulo(null,undefined);// NaN

source

🍦 Try it

npm install just-random-integer
yarn add just-random-integer

Produces a random integer within a given range

importrandomfrom'just-random-integer';random();// Returns either 0 or 1random(5);// Returns a random integer between 0 and 5 (inclusively)random(3,10);// Returns a random integer between 3 and 10 (inclusively)random(-5.8,10.4);// Returns a random integer between -5 and 10 (inclusively)

Functions

source

🍦 Try it

npm install just-compose
yarn add just-compose

Return a function composed of 2 or more functions

importcomposefrom'just-compose';constsqRootBiggest=compose(Math.max,Math.sqrt,Math.trunc);sqRootBiggest(10,5);// 3sqRootBiggest(7,0,16);// 4

source

🍦 Try it

npm install just-curry-it
yarn add just-curry-it

Return a curried function

importcurryfrom'just-curry-it';functionadd(a,b,c){returna+b+c;}curry(add)(1)(2)(3);// 6curry(add)(1)(2)(2);// 5curry(add)(2)(4,3);// 9functionadd(...args){returnargs.reduce((sum,n)=>sum+n,0)}varcurryAdd4=curry(add,4)curryAdd4(1)(2,3)(4);// 10functionconverter(ratio,input){return(input*ratio).toFixed(1);}constcurriedConverter=curry(converter)constmilesToKm=curriedConverter(1.62);milesToKm(35);// 56.7milesToKm(10);// 16.2

source

🍦 Try it

npm install just-demethodize
yarn add just-demethodize

Turn a method into a standalone function; the first arg becomes this

importdemethodizefrom'just-demethodize';consttrimFn=demethodize(''.trim);['hello ',' goodbye','hello again'].map(trimFn);// ['hello', 'goodbye', 'hello again']

source

🍦 Try it

npm install just-flip
yarn add just-flip

Flip first two arguments of a function

importflipfrom'just-flip';flip(console.log)(1,2,3)// 2, 1, 3importmapfrom'just-map-object';importpartialfrom'just-partial';constnumbers={x: 5,y: 10};constflippedMap=flip(map);constdouble=partial(flippedMap,(undefined,number)=>number*2);double(numbers)//{x: 10, y: 20];

source

🍦 Try it

npm install just-partial-it
yarn add just-partial-it

Return a partial function

importpartialfrom'just-partial-it';constcubedRoot=partial(Math.pow,_,1/3);cubedRoot(64);// 4constgetRoot=partial(Math.pow,64);getRoot(1/2);// 8

source

🍦 Try it

npm install just-pipe
yarn add just-pipe

Pass a value through a pipeline of functions

importpipefrom 'just-pipe pipe(3,a=>a+1,b=>b*2)// 8pipe('John Smith',a=>a.split(' '),b=>b.reverse(),c=>c[0])// 'Smith'

source

🍦 Try it

npm install just-debounce-it
yarn add just-debounce-it

Return a debounced function

importdebouncefrom"just-debounce-it";constfn1=debounce(()=>console.log("Hello"),500);fn1();fn1();fn1();// 500ms later logs 'hello' onceconstfn2=debounce(()=>console.log("Hello"),500,true);fn2();// logs hello immediatelyfn2();fn2();// 500ms later logs 'hello' onceconstfn3=debounce(()=>console.log("Hello"),500);fn3();fn3();fn3();fn3.cancel();// function cancelled before 'hello' is loggedconstfn4=debounce(()=>console.log("Hello"),500);fn4();fn4();fn4();fn4.flush();// immediately invoke the debounced function

source

🍦 Try it

npm install just-memoize
yarn add just-memoize

An implementation of the memoize technique

importmemoizefrom'just-memoize';constsumByOne=memoize(function(value){returnvalue+1;});sumByOne(10);// Returns value returned by the functionsumByOne(10);// Cache hit!sumByOne(20);// Returns value returned by the functionsumByOne(20);// Cache hit!// Custom cache key (key defaults to JSON stringified arguments)varsum=memoize(function(a,b){returna+b;},function(a,b){return`${a}-${b}`;});sum(10,10);// Returns value returned by the functionsum(10,20);// Returns value returned by the functionsum(10,20);// Cache hit!

source

🍦 Try it

npm install just-memoize-last
yarn add just-memoize-last

A memoize implementation that only caches the most recent evaluation

constmemoizeLast=require('just-memoize-last')constcompare=require('just-compare')constmaxValue=memoizeLast(function(arr){returnMath.max(...arr)},function(a,b){returncompare(a,b)});maxValue([1,2,3])// 3maxValue([1,2,3])// cache hit!maxValue([1,3,4])// 4maxValue([1,2,3])// 3

source

🍦 Try it

npm install just-random
yarn add just-random

Return a randomly selected element in an array

importrandomfrom'just-random';random([1,2,3]);// one of [1, 2, 3], at random

source

🍦 Try it

npm install just-throttle
yarn add just-throttle

Return a throttled function

importthrottlefrom'just-throttle';// no matter how many times the function is called, only invoke once within the given interval// options: // `leading`: invoke before interval// `trailing`: invoke afer intervalconstfn1=throttle(()=>console.log('hello'),500,{leading: true});setInterval(fn1,400);// logs 'hello' immediately and then every 500msconstfn2=throttle(()=>console.log('hello'),500,{trailing: true});setInterval(fn2,400);// logs 'hello' after 500ms and then every 500msconstfn3=throttle(()=>console.log('hello'),500,{leading: true,trailing: true});// forces trailing to falseconstfn4=throttle(()=>console.log('hello'),500,{leading: false});fn4();fn4();fn4();fn4.cancel();// function cancelled before 'hello' is loggedconstfn5=throttle(()=>console.log("Hello"),500);fn5();fn5();fn5();fn5.flush();// immediately invoke the throttled function

source

🍦 Try it

npm install just-once
yarn add just-once

Create a function that can only be invoked once

importoncefrom'just-once';constfn=once(()=>console.log('hello'));fn();// logs 'hello'fn();// does nothing

Testing

Run all tests as a single test suite with

npm run test

Cross browser tests (via saucelabs) are in the sauce branch

Contribute!

https://github.com/angus-c/just/blob/master/CONTRIBUTING.md

About

A library of dependency-free JavaScript utilities that do just one thing.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Contributors 92