Array Timsort
The `array-timsort` package provides a JavaScript implementation of Python's highly optimized Timsort algorithm for stable array sorting. It is currently at version 1.0.3, with an apparent maintenance-only release cadence based on its last commit over two years ago. Unlike the `timsort` package it was forked from, `array-timsort` returns an array representing the original indices of elements after sorting, rather than `undefined`. Timsort is an adaptive, stable sorting algorithm that leverages existing order in data, achieving O(n) performance on partially sorted arrays and O(n log n) worst-case time complexity, with O(n) memory usage. Benchmarks suggest it can significantly outperform `Array.prototype.sort()` in Node.js for specific data distributions, such as descending arrays or those with many duplicates, while potentially being slower on certain random distributions.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use `require()` in an ES module (`"type": "module"` in `package.json`) environment without proper setup.fixEither convert your project to use ES modules exclusively, configure your build process to transpile/bundle CJS modules, or use dynamic `import()` within an async context if you must load CJS. -
TypeError: (0 , array_timsort_1.sort) is not a function
cause Incorrect ES module import syntax being used for a CommonJS package. This typically occurs in TypeScript or ESM-aware environments when trying `import { sort } from 'array-timsort';` and the module isn't correctly resolved as CJS.fixFor TypeScript/ESM, ensure your `tsconfig.json` (`moduleResolution`) and build setup correctly handle CommonJS interop. Alternatively, use `import * as Timsort from 'array-timsort'; const { sort } = Timsort;` or revert to `const { sort } = require('array-timsort');` in a CJS context.
Warnings
- gotcha Unlike the original `timsort` package it forks, `array-timsort` returns an array of original indices after sorting (e.g., `[2, 1, 0, 4]` for `[1, 2, 3, 5]`), while `timsort` returns `undefined`. This changes the expected return value for many users.
- gotcha Performance is highly dependent on data distribution and array size. Benchmarks indicate that `array-timsort` can be slower than native `Array.prototype.sort()` for certain types of random arrays (e.g., lengths 100, 1000) in specific Node.js versions, despite being significantly faster on others.
- gotcha The package is designed for CommonJS environments and uses `require()`. Direct ES module `import` statements (e.g., `import { sort } from 'array-timsort'`) may fail in pure ESM contexts or build tools without explicit CJS interoperability.
Install
-
npm install array-timsort -
yarn add array-timsort -
pnpm add array-timsort
Imports
- sort (named destructuring)
import { sort } from 'array-timsort'const { sort } = require('array-timsort') - sort (property access)
const sort = require('array-timsort'); sort(array);const timsortModule = require('array-timsort'); timsortModule.sort(array); - sort (incorrect path)
const sort = require('array-timsort/index').sort;const { sort } = require('array-timsort')
Quickstart
const { sort } = require('array-timsort');
// Example 1: Sorting a basic numerical array in ascending order
// The Timsort algorithm is adaptive and stable, making it efficient
// for partially sorted data while maintaining element order for equal values.
const numbers = [30, 10, 20, 5, 15, 25, 40, 35, 45, 0];
console.log('Original numbers:', numbers.slice()); // Log a copy to show original state
// Define a numerical comparison function
function numberCompare(a, b) {
return a - b;
}
// Perform the sort using the custom comparator
// The `sort` function modifies the array in-place and returns
// an array of original indices mapping to their new positions.
const originalIndicesMap = sort(numbers, numberCompare);
console.log('Sorted numbers:', numbers);
console.log('Original indices map:', originalIndicesMap);
// Example 2: Sorting a specific subrange of an array
const mixedArray = ['apple', 'zebra', 'banana', 'grape', 'fig', 'date', 'elderberry'];
console.log('\nOriginal mixed array:', mixedArray.slice());
// Sort elements from index 2 ('banana') up to (but not including) index 6 ('elderberry') alphabetically
sort(mixedArray, 2, 6);
console.log('Mixed array with subrange sorted:', mixedArray);