Socket
Socket
Sign inDemoInstall

sorting-lib

Package Overview
Dependencies
0
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    sorting-lib

A library that makes sorting easier by introducing `Comparator`


Version published
Weekly downloads
94
increased by108.89%
Maintainers
1
Install size
16.3 kB
Created
Weekly downloads
 

Readme

Source

Sorting Lib

Javascript has no built-in ways to easily handle the comparison between objects. This is why this library exists, it provides an intuitive API to create comparators.

Install by running:

npm i sorting-lib

The project is maintained on Gitlab

Comparing

With you comparing function you can select a key to compare by. Selecting a key happens by either a dot-seperated string or a lambda function.

const array = [
	{ value: 1, object: { subValue: 1 } },
	{ value: 2, object: { subValue: 2 } },
];

array.sort(comparing(item => item.value));
array.sort(comparing(item => item.object.subValue));
array.sort(comparing('value'));
array.sort(comparing('object.subValue'));

Handling Nil

You can choose Nil (null | undefined) values to be either a maximum or a minimum:

const array = [
	{ value: 1 },
	{},
];

array.sort(comparing(item => item.value), NilAs.Max);

Comparator builder

For more complex sorting needs you can combine multiple "simple" comparators into one. An example where this might be useful is sorting names.

type Person = { firstName: string, lastName: string }

const fullNames = [
	{ firstName: 'a', lastName: 'b' },
	{ firstName: 'a', lastName: 'c' },
];

fullNames.sort(
	// Compares `firstName` first, then falls back to `lastName`
	comparatorBuilder<Person>()
		.add(comparing('firstName'))
		.add(comparing('lastName'))
		.build(),
);

Note: as of now typescript's type inference is not strong enough to infer the Person type

Invert

Inverting a comparison:

// Inverts the comparison
comparatorBuilder<SomeType>()
	.add(someComparator)
	.invert()
	.build()

Combining a dynamic array of comparators

declare const arrayOfComparators: Comparator<SomeType>[];

const combinedComparator: Comparator<SomeType> =
	chainComparators(arrayOfComparators);

Keywords

FAQs

Last updated on 14 Nov 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc