mauss
Version:
practical functions and reusable configurations
51 lines (50 loc) • 1.54 kB
JavaScript
import { wildcard } from './index.js';
/**
* A higher-order function that accepts an array of strings and returns a comparator function that sorts the strings in the order they appear in the array.
*/
export function arrange(weights) {
const m = {};
weights.forEach((v, i) => (m[v] = i));
return (x, y) => m[x] - m[y];
}
/**
* A higher-order function that accepts a string as an identifier and an optional comparator function, it breaks up the identifier described by the dot (`.`) character and returns a curried function that accepts `(x, y)` with an object defined by the identifier.
*
* The optional comparator can be used when you have an existing custom sort function, e.g. in combination with `arrange` to sort a set of string.
*
* @example
*
* ```javascript
* const posts = [
* { date: { month: 'March' } },
* { date: { month: 'June' } },
* { date: { month: 'May' } },
* { date: { month: 'April' } },
* { date: { month: 'January' } },
* { date: { month: 'June' } },
* { date: { month: 'February' } },
* ];
*
* const months = [
* 'January',
* 'February',
* 'March',
* 'April',
* 'May',
* 'June',
* 'July',
* 'August',
* 'September',
* 'October',
* 'November',
* 'December',
* ];
*
* posts.sort(drill('date.month', arrange(months)));
* ```
*/
export function drill(identifier, comparator = wildcard) {
const trail = identifier.split('.');
const drill = (o) => trail.reduce((ret, prop) => ret[prop], o);
return (x, y) => comparator(drill(x), drill(y));
}