New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

better-sort

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

better-sort

Syntactic sugar wrapper over JS sort function with better readability

  • 1.1.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Syntactic sugar wrapper over JS sort function with better readability

Zero-dependency minimal package (two functions) to provide better-readable (albeit more verbose) wrapper over JS default Array.sort(). Fully typed.

Prevents errors when interchanging signs in the native Array.sort() function like this:

foo.sort((a, b) => (a.date.isBefore(b.date) ? -1 : 1)) - at the first glance, is this sorted in ASC or DESC order??

Usage:

import { sortAsc } from "./src/index";

const array = [3, 1, 4, 1, 5, 9, 2, 6];

const sortedArray = sortAsc({
  array,
  firstIsGreater: (a, b) => a > b, // Compare function that returns boolean
});

console.log(sortedArray); // [1, 1, 2, 3, 4, 5, 6, 9]

console.log(array); // [3, 1, 4, 1, 5, 9, 2, 6] - keeps the original array intact

You can provide areEqual function parameter to ensure stability of the sorting function. Otherwise it sorts equal elements in non-deterministic order.

import { sortAsc } from "./src/index";

// The sortAsc function is a stable sort when `areEqual` is provided, meaning that it preserves the original input order of elements that are equal.

const inputArray = [
  { name: "John", age: 25 },
  { name: "Alice", age: 30 },
  { name: "Bob", age: 20 },
  { name: "Mike", age: 25 },
];

const sortedArray = sortAsc({
  array: inputArray,
  firstIsGreater: (a, b) => a > b,
  areEqual: (a, b) => a === b,
});

console.log(sortedArray); // [{ name: "Bob", age: 20 }, { name: "John", age: 25 }, { name: "Mike", age: 25 }, { name: "Alice", age: 30 }] - keeps equal elements in order they appear in input

Keywords

FAQs

Package last updated on 12 Feb 2024

Did you know?

Socket

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc