@codingame/thenby

中文文档
1.0.0发布于 2024/09/27Apache-2.0TypeScriptES Module零依赖近 30 天下载 2031

Micro library for sorting arrays using the firstBy().thenBy().thenBy() syntax

原始使用文档
文档目录10 节
  1. Sort by property names
  2. Sort by unary functions
  3. Extra options
  4. Sort descending
  5. Case insensitive sorting
  6. Custom compare function
  7. Internationalization: Using javascripts native Intl.Collator
  8. A word on performance
  9. Installing
  10. Install using npm or yarn

thenBy.js usage

NPM Version NPM Downloads

thenBy is a javascript micro library that helps sorting arrays on multiple keys. It allows you to use the native Array::sort() method of javascript, but pass in multiple functions to sort that are composed with firstBy().thenBy().thenBy() style.

Example:

// first by length of name, then by population, then by ID
data.sort(
    firstBy(function (v1, v2) { return v1.name.length - v2.name.length; })
    .thenBy(function (v1, v2) { return v1.population - v2.population; })
    .thenBy(function (v1, v2) { return v1.id - v2.id; })
);

thenBy also offers some nice shortcuts that make the most common ways of sorting even easier and more readable.

Sort by property names

Javascript sorting relies heavily on passing discriminator functions that return -1, 0 or 1 for a pair of items. While this is very flexible, often you want to sort on the value of a simple property. As a convenience, thenBy.js builds the appropriate compare function for you if you pass in a property name (instead of a function). The example above would then look like this:

// first by length of name, then by population, then by ID
data.sort(
    firstBy(function (v1, v2) { return v1.name.length - v2.name.length; })
    .thenBy("population")
    .thenBy("id")
);

If an element doesn't have the property defined, it will sort like the empty string (""). Typically, this will be at the top.

Sort by unary functions

You can also pass a function that takes a single item and returns its sorting key. This turns the above expression into:

// first by length of name, then by population, then by ID
data.sort(
    firstBy(function (v) { return v.name.length; })
    .thenBy("population")
    .thenBy("id")
);

Note that javascript contains a number of standard functions that can be passed in here as well. The Number() function will make your sorting sort on numeric values instead of lexical values:

var values = ["2", "20", "03", "-2", "0", 200, "2"];
var sorted = values.sort(firstBy(Number));

Extra options

Sort descending

thenBy.js allows you to pass in a second parameter for direction. If you pass in 'desc' or -1, the sorting will be reversed. So:

// first by length of name descending, then by population descending, then by ID ascending
data.sort(
    firstBy(function (v1, v2) { return v1.name.length - v2.name.length; }, -1)
    .thenBy("population", "desc")
    .thenBy("id")
);

Case insensitive sorting

(as of v1.2.0) All of the shortcut methods allow you to sort case insensitive as well. The second parameter expects an options object (if it is a number, it is interpreted as direction as above). The ignoreCase property can be set to true, like this:

// first by name, case insensitive, then by population
data.sort(
    firstBy("name", {ignoreCase:true})
    .thenBy("population")
);

If you want to use both descending and ignoreCase, you have to use the options syntax for direction as well:

// sort by name, case insensitive and descending
data.sort(firstBy("name", {ignoreCase:true, direction:"desc"}));

Custom compare function

If you have more specific wishes for the exact sort order, but still want to use the convenience of unary functions or sorting on property names, you can pass in you own compare function in the options. Here we use a compare function that known about the relative values of playing cards::

const cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
var cardCompare = (c1, c2) =>{
    return cards.indexOf(c1) - cards.indexOf(c2);
}
var handOfCards =  [
        { id: 7, suit:"c", card:"A" },
        { id: 8, suit:"d", card:"10" },
        // etc
    ];
handOfCards.sort(firstBy("card", {cmp: cardCompare, direction: "desc"}));

You can use the cmp function together with direction, but not with ignoreCase (for obvious reasons).

Internationalization: Using javascripts native Intl.Collator

One of the more interesting custom compare functions you may want to pass in is the native compare function that is exposed by Intl.Collator. This compare function knows about the different sorting rules in different cultures. Many browsers have these implemented, but in NodeJS, the API is implemented, but only for the English culture. You would use it with thenBy like this:

// in German, ä sorts with a
var germanCompare = new Intl.Collator('de').compare;
// in Swedish, ä sorts after z
var swedishCompare = new Intl.Collator('sv').compare;
data.sort(
    firstBy("name", {cmp: swedishCompare})
);

Check the details on using Intl.Collator.

A word on performance

thenBy constructs a comparer function for you. It does this by combining the functions you pass in with a number of small utility functions that perform tasks like "reverting", "combining the current sort order with the previous one", etc. Also, these operations try to work correctly, no matter what content is in the sorted array. There are two steps here that cost time: constructing the über-function and running it. The construction time should always be negligible. The run time however can be slower than when you carefully handcraft the compare function. Still, normally you shouldn't worry about this, but if you're sorting very large sets, it could matter. For example, there is some overhead in making several small functions call each other instead of creating one piece of code. Also, if you know your data well, and know that a specific field is always present and is always a number, you could code a significantly faster compare function then thenBy's results. The unit tests contain an extreme example.

If you use thenBy to combine multiple compare functions into one (where each function expects two parameters), the difference is small. Using unary functions adds some overhead, using direction:desc adds some, using only a property name adds a little, but will check for missing values, which could be optimized. Ignoring case will slow down, but not more so than when handcoded.

Installing

Install using npm or yarn

npm install @codingame/thenby

or

yarn add @codingame/thenby

then in your app:

var firstBy = require('@codingame/thenby');

or in TypeScript/ES6:

import { firstBy } from "@codingame/thenby";

版本与发布记录

@codingame/thenby 共发布 1 个版本,首次发布于 2024/09/27;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.0latest2024/09/272 年前

关于 @codingame/thenby 的常见问题

@codingame/thenby 是什么?

Micro library for sorting arrays using the firstBy().thenBy().thenBy() syntax

如何安装 @codingame/thenby?

在项目目录运行 npm install @codingame/thenby,或使用 pnpm add / yarn add / bun add。

@codingame/thenby 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@codingame/thenby 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@codingame/thenby 可以商用吗?

@codingame/thenby 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@codingame/thenby 的下载量有多少?

根据 npm 官方下载统计,@codingame/thenby 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,031 次,日均约 68 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@codingame/thenby 还在维护吗?

最新版本 1.0.0 发布于 2024/09/27(2 年前);至今共发布 1 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/09/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。