TinyBase logoTinyBase

defaultSorter

The defaultSorter function is provided as a convenience to sort keys alphanumerically, and can be provided to the sliceIdSorter and rowIdSorter parameters of the setIndexDefinition method in the indexes module, for example.

defaultSorter(
  sortKey1: SortKey,
  sortKey2: SortKey,
): number
TypeDescription
sortKey1SortKey

The first item of the pair to compare.

sortKey2SortKey

The second item of the pair to compare.

returnsnumber

A number indicating how to sort the pair.

Examples

This example creates an Indexes object.

import {createIndexes, createStore} from 'tinybase';

const store = createStore();
const indexes = createIndexes(store);
console.log(indexes.getIndexIds());
// -> []

This example creates a Store, creates an Indexes object, and defines an Index based on the first letter of the pets' names. The Slice Ids (and Row Ids within them) are alphabetically sorted using the defaultSorter function.

import {createIndexes, createStore, defaultSorter} from 'tinybase';

const store = createStore().setTable('pets', {
  fido: {species: 'dog'},
  felix: {species: 'cat'},
  cujo: {species: 'dog'},
});

const indexes = createIndexes(store);
indexes.setIndexDefinition(
  'byFirst', //              indexId
  'pets', //                 tableId
  (_, rowId) => rowId[0], // each Row's Slice Id
  (_, rowId) => rowId, //    each Row's sort key
  defaultSorter, //          sort Slice Ids
  defaultSorter, //          sort Row Ids by sort key
);

console.log(indexes.getSliceIds('byFirst'));
// -> ['c', 'f']
console.log(indexes.getSliceRowIds('byFirst', 'f'));
// -> ['felix', 'fido']

Since

v1.0.0