4

The example "Datatable with Sortable Column" (from the lightning-datatable documentation) includes this code where a primer parameter is declared and used in the sortBy function:

sortBy(field, reverse, primer) {
    const key = primer
        ? function (x) {
              return primer(x[field]);
          }
        : function (x) {
              return x[field];
          };

    return function (a, b) {
        a = key(a);
        b = key(b);
        return reverse * ((a > b) - (b > a));
    };
}

onHandleSort(event) {
    const { fieldName: sortedBy, sortDirection } = event.detail;
    const cloneData = [...this.data];

    cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1));
    this.data = cloneData;
    this.sortDirection = sortDirection;
    this.sortedBy = sortedBy;
}

In a quick test, it is always undefined. What is its purpose, when is it populated and where is it documented?

1 Answer 1

5

primer is just a function that does something to "prime" the data. For example, you might use it to make all the values lowercase, or uppercase, or round to the second significant digit, or whatever else you might want to do.

Examples:

// sort by uppercase letters, works for anything that can be coerced to a string
const uppercase = (x) => (x+'').toUpperCase();
this.sortBy(this.sortField, this.sortOrder, uppercase);

// Sort non-empty values
const truthy = (x) => (!!x);
this.sortBy(this.sortField, this.sortOrder, truthy);

// sort numbers in lexicographical order
const toString = (x) => x+'';
this.sortBy(this.sortField, this.sortOrder, toString);

It's useful to have this capability in many different sort algorithms, but the documentation doesn't actively use it, as you've observed.

1
  • Got it; thanks!
    – Keith C
    Nov 13, 2021 at 16:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .