{"id":13492858,"url":"https://github.com/BenDMyers/generate-comparators","last_synced_at":"2025-03-28T11:30:55.009Z","repository":{"id":34884669,"uuid":"186203229","full_name":"BenDMyers/generate-comparators","owner":"BenDMyers","description":"🔀 An npm package for creating complex comparators, tersely and beautifully.","archived":false,"fork":false,"pushed_at":"2023-03-03T21:41:54.000Z","size":550,"stargazers_count":18,"open_issues_count":2,"forks_count":0,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-03-18T13:46:44.354Z","etag":null,"topics":["comparator","comparison","hacktoberfest","javascript","npm-package","sorting"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/generate-comparators","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BenDMyers.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2019-05-12T02:44:38.000Z","updated_at":"2023-03-22T22:46:13.000Z","dependencies_parsed_at":"2024-01-16T10:08:41.144Z","dependency_job_id":null,"html_url":"https://github.com/BenDMyers/generate-comparators","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenDMyers%2Fgenerate-comparators","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenDMyers%2Fgenerate-comparators/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenDMyers%2Fgenerate-comparators/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenDMyers%2Fgenerate-comparators/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BenDMyers","download_url":"https://codeload.github.com/BenDMyers/generate-comparators/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246020792,"owners_count":20710822,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["comparator","comparison","hacktoberfest","javascript","npm-package","sorting"],"created_at":"2024-07-31T19:01:09.944Z","updated_at":"2025-03-28T11:30:54.769Z","avatar_url":"https://github.com/BenDMyers.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# `generate-comparators`\n\n**Create complex comparators, tersely and beautifully.**\n\n[![npm package](https://nodei.co/npm/generate-comparators.png?downloads=true\u0026downloadRank=true\u0026stars=true)](https://nodei.co/npm/generate-comparators/)\n\n***\n\n\u003c!-- TOC depthFrom:2 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 --\u003e\n\n- [What Are Comparators, and Why Do I Need This Library?](#what-are-comparators-and-why-do-i-need-this-library)\n- [Getting Started](#getting-started)\n- [Usage](#usage)\n\t- [`comparators(toComparable)`](#comparatorstocomparable)\n\t\t- [`toComparable : function`](#tocomparable-function)\n\t\t- [Example Uses](#example-uses)\n\t- [`composeComparators(...comparators)`](#composecomparatorscomparators)\n\t\t- [Examples](#examples)\n\n\u003c!-- /TOC --\u003e\n\n***\n\n## What Are Comparators, and Why Do I Need This Library?\n\nA *comparator* is a function that looks at two elements and decides which should go before the other in a sort. In practice, they're what you would pass to the array `sort` function–\n\n```js\nmyArray.sort(myComparator);\n```\n\n–to tell `sort` how to determine the elements' order.\n\nA comparator receives two elements, `a` and `b`, and returns\n\n* A negative number, conventionally `-1`, if `a` should go *before* `b`.\n\n* A positive number, conventionally `1`, if `a` should go *after* `b`.\n\n* `0` if the two elements are equivalent.\n\nIn other words, a boilerplate comparator would look like\n\n```js\nfunction(a, b) {\n    if(/* LOGIC DETERMINING THAT `a` GOES BEFORE `b` */) {\n        return -1;\n    }\n    else if(/* LOGIC DETERMINING THAT `a` GOES AFTER `b` */) {\n        return 1;\n    }\n    else {\n        return 0;\n    }\n}\n```\n\nThis boilerplate is not terse, and it doesn't scale well if you need to sort by multiple attributes.\n\n`generate-comparators` lets you define new comparators in just one line and combine them in another.\n\n***\n\n## Getting Started\n\nInstall the package on the terminal using either npm or Yarn:\n\n```bash\n# With npm\nnpm install generate-comparators\n\n# Or with Yarn\nyarn add generate-comparators\n```\n\nImport the package's two functions into your Node project using either `require` or, if you're transpiling ES6, `import`:\n\n```js\n// With `require`\nconst {comparators, composeComparators} = require('generate-comparators');\n\n// Or with `import`\nimport {comparators, composeComparators} from 'generate-comparators';\n```\n\n***\n\n## Usage\n\n### `comparators(toComparable)`\n\nGenerates ascending and descending comparator functions given a function that converts array elements into easily comparable forms.\n\nReturns an object with two properties, `asc` and `desc`.\n\n* `asc : function`: a comparator for sorting an array in ascending order\n\n* `desc : function`: a comparator for sorting an array in descending order\n\n    * **NOTE:** This is not necessarily the same as a reversed ascending order. `sort` sorts an array left-to-right, so when two equivalent elements are compared, the leftmost one will stay to the left.\n\n\u003e **NOTE:** I recommend using the naming convention `byX` for this object, where *X* is the property or attribute the comparators check on. This has the advantage of being both terse and legible.\n\n#### `toComparable : function`\n\n`toComparable` must be a function that takes an element of an array and converts it into a form that can be more easily compared to other elements of the array. For instance, to create a comparator that would sort an array of elements by their lengths, use\n\n```js\n(element) =\u003e element.length\n```\n\nfor `toComparable`.\n\n`toComparable` can be any function that performs any complex logic on the given element, so long as it returns a value in a comparable data type such as `Number`, `String`, or `Date`.\n\n#### Example Uses\n\n* Sorting arrays of primitives using the identity function `element =\u003e element` (default behavior for `array.sort()`):\n\n```js\nconst {comparators} = require('generate-comparators');\n\nconst numbers = [5, 2, 7, -3, 0];\nconst strings = ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog'];\n\nconst byIdentity = comparators(element =\u003e element);\n\n// Ascending\nnumbers.sort(byIdentity.asc); // [-3, 0, 2, 5, 7]\nstrings.sort(byIdentity.asc); // ['brown', 'dog', 'fox', 'jumped', 'lazy', 'over', 'quick', 'the', 'the']\n\n// Descending\nnumbers.sort(byIdentity.desc); // [7, 5, 2, 0, -3]\nstrings.sort(byIdentity.desc); // ['the', 'the', 'quick', 'over', 'lazy', 'jumped', 'fox', 'dog', 'brown']\n```\n\n* Sorting an array of strings by length:\n\n```js\nconst {comparators} = require('generate-comparators');\n\nconst strings = ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog'];\n\nconst byLength = comparators(element =\u003e element.length);\n\n// Ascending\nstrings.sort(byLength.asc); // ['the', 'fox', 'the', 'dog', 'over', 'lazy', 'quick', 'brown', 'jumped']\n\n// Descending\nstrings.sort(byLength.desc); // ['jumped', 'quick', 'brown', 'over', 'lazy', 'the', 'fox', 'the', 'dog']\n```\n\n* Sorting an array of person objects by the number of vowels in their first and last name:\n\n```js\nconst {comparators} = require('generate-comparators');\n\nconst people = [\n    {lastName: 'Lovelace', firstName: 'Ada', birthYear: 1815},\n    {lastName: 'Turing', firstName: 'Alan', birthYear: 1936},\n    {lastName: 'Boole', firstName: 'George', birthYear: 1860},\n    {lastName: 'Babbage', firstName: 'Charles', birthYear: 1930}\n];\n\nconst byVowelsInName = comparators(element =\u003e getVowelCount(element.firstName + element.lastName));\n\n// Ascending\n\n/*  {lastName: 'Turing', firstName: 'Alan', birthYear: 1936},\n *  {lastName: 'Lovelace', firstName: 'Ada', birthYear: 1815},\n *  {lastName: 'Babbage', firstName: 'Charles', birthYear: 1930},\n *  {lastName: 'Boole', firstName: 'George', birthYear: 1860}\n*/\npeople.sort(byVowelsInName.asc);\n\n// Descending\n\n/*  {lastName: 'Boole', firstName: 'George', birthYear: 1860},\n *  {lastName: 'Lovelace', firstName: 'Ada', birthYear: 1815},\n *  {lastName: 'Babbage', firstName: 'Charles', birthYear: 1930},\n *  {lastName: 'Turing', firstName: 'Alan', birthYear: 1936}\n */\npeople.sort(byVowelsInName.desc);\n```\n\n### `composeComparators(...comparators)`\n\nReceives \u003e0 comparators and combines them into new ascending and descending comparators.\n\nThe new comparators will first compare the two elements using `comparators[0]`. If they are equivalent, they will be compared with `comparators[1]` and so forth until all comparators have compared the elements. If the elements are still equivalent, the composed comparator will return `0`. Because the composed comparator iterates over the given comparators from left to right, the position of each comparator matters.\n\nReturns an object with two properties, `asc` and `desc`.\n\n* `asc : function`: a comparator for sorting an array in ascending order, using all given comparators\n\n* `desc : function`: a comparator for sorting an array in descending order, using all given comparators\n\n    * **NOTE:** This is not necessarily the same as a reversed ascending order. `sort` sorts an array left-to-right, so when two equivalent elements are compared, the leftmost one will stay to the left.\n\n#### Examples\n\n* Sorting an array of person objects first by age (descending), then by last name (ascending), then by first name (descending)\n\n```js\nconst {comparators, composeComparators} = require('generate-comparators');\n\nconst people = [\n    {lastName: 'Doe', firstName: 'John', age: 42},\n    {lastName: 'Boole', firstName: 'George', age: 67},\n    {lastName: 'Lovelace', firstName: 'Ada', age: 2},\n    {lastName: 'Doe', firstName: 'Jane', age: 42},\n    {lastName: 'Hamilton', firstName: 'Margaret', age: 100},\n];\n\nconst byAge = comparators(element =\u003e element.age);\nconst byLastName = comparators(element =\u003e element.lastName);\nconst byFirstName = comparators(element =\u003e element.firstName);\nconst composed = composeComparators(byAge.desc, byLastName.asc, byFirstName.desc);\n\n// Ascending\n/* {lastName: 'Hamilton', firstName: 'Margaret', age: 100},\n * {lastName: 'Boole', firstName: 'George', age: 67},\n * {lastName: 'Doe', firstName: 'John', age: 42},\n * {lastName: 'Doe', firstName: 'Jane', age: 42},\n * {lastName: 'Lovelace', firstName: 'Ada', age: 2}\n */\npeople.sort(composed.asc);\n\n// Descending\n/* {lastName: 'Lovelace', firstName: 'Ada', age: 2},\n * {lastName: 'Doe', firstName: 'Jane', age: 42},\n * {lastName: 'Doe', firstName: 'John', age: 42},\n * {lastName: 'Boole', firstName: 'George', age: 67},\n * {lastName: 'Hamilton', firstName: 'Margaret', age: 100}\n */\npeople.sort(composed.desc);\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBenDMyers%2Fgenerate-comparators","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBenDMyers%2Fgenerate-comparators","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBenDMyers%2Fgenerate-comparators/lists"}