diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index c96d536..e4ab092 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -13,11 +13,11 @@ learn how: http://kcd.im/pull-request - `match-sorter` version: - `node` version: -- `npm` (or `yarn`) version: Relevant code or config ```javascript + ``` What you did: diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index fa9abbe..3af53f1 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -31,7 +31,6 @@ merge of your pull request! **Checklist**: - - [ ] Documentation diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..3fb3c34 --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,80 @@ +name: validate +on: + push: + branches: + - '+([0-9])?(.{+([0-9]),x}).x' + - 'master' + - 'next' + - 'next-major' + - 'beta' + - 'alpha' + - '!all-contributors/**' + pull_request: {} +jobs: + main: + # ignore all-contributors PRs + if: ${{ !contains(github.head_ref, 'all-contributors') }} + strategy: + matrix: + node: [10.13, 12, 14, 15] + runs-on: ubuntu-latest + steps: + - name: ⬇️ Checkout repo + uses: actions/checkout@v2 + + - name: ⎔ Setup node + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node }} + + - name: 📥 Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: ▶️ Run validate script + run: npm run validate + + - name: ⬆️ Upload coverage report + uses: codecov/codecov-action@v1 + + release: + needs: main + runs-on: ubuntu-latest + if: + ${{ github.repository == 'kentcdodds/match-sorter' && + contains('refs/heads/master,refs/heads/beta,refs/heads/next,refs/heads/alpha', + github.ref) && github.event_name == 'push' }} + steps: + - name: ⬇️ Checkout repo + uses: actions/checkout@v2 + + - name: ⎔ Setup node + uses: actions/setup-node@v1 + with: + node-version: 14 + + - name: 📥 Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: 🏗 Run build script + run: npm run build + + - name: 🚀 Release + uses: cycjimmy/semantic-release-action@v2 + with: + semantic_version: 17 + branches: | + [ + '+([0-9])?(.{+([0-9]),x}).x', + 'master', + 'next', + 'next-major', + {name: 'beta', prerelease: true}, + {name: 'alpha', prerelease: true} + ] + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.npmrc b/.npmrc index 1e23fdf..214c29d 100644 --- a/.npmrc +++ b/.npmrc @@ -1 +1 @@ -registry=http://registry.npmjs.org +registry=https://registry.npmjs.org/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7a8368c..0000000 --- a/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: node_js -cache: npm -notifications: - email: false -node_js: - - 10 - - 12 - - 14 - - node -install: npm install -script: - - npm run validate - - npx codecov@3 -branches: - only: - - master - - beta - -jobs: - include: - - stage: release - node_js: 14 - script: kcd-scripts travis-release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..47681ae --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances of + any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +me+coc@kentcdodds.com. All complaints will be reviewed and investigated promptly +and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6163592..a791ebb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,9 +8,8 @@ series [How to Contribute to an Open Source Project on GitHub][egghead] ## Project setup 1. Fork and clone the repo -2. `$ npm install` to install dependencies -3. `$ npm run validate` to validate you've got it working -4. Create a branch for your PR +2. Run `npm run setup -s` to install dependencies and run validation +3. Create a branch for your PR with `git checkout -b pr/your-branch-name` > Tip: Keep your `master` branch pointing at the original repository and make > pull requests from branches on your fork. To do this, run: @@ -42,5 +41,6 @@ requests! Thanks! [egghead]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github +[all-contributors]: https://github.com/all-contributors/all-contributors [issues]: https://github.com/kentcdodds/match-sorter/issues diff --git a/LICENSE b/LICENSE index 4c43675..a077a44 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ The MIT License (MIT) -Copyright (c) 2017 Kent C. Dodds +Copyright (c) 2020 Kent C. Dodds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index d79c61a..6a213b6 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,7 @@ [![version][version-badge]][package] [![downloads][downloads-badge]][npmtrends] [![MIT License][license-badge]][license] - - -[![All Contributors](https://img.shields.io/badge/all_contributors-23-orange.svg?style=flat-square)](#contributors-) - +[![All Contributors][all-contributors-badge]](#contributors-) [![PRs Welcome][prs-badge]][prs] [![Code of Conduct][coc-badge]][coc] [![Examples][examples-badge]][examples] @@ -311,7 +308,7 @@ matchSorter(thingsWithDiacritics, 'à', {keepDiacritics: true}) ### baseSort: `function(itemA, itemB): -1 | 0 | 1` -_Default: `(a, b) => String(a.rankedItem).localeCompare(b.rankedItem)`_ +_Default: `(a, b) => String(a.rankedValue).localeCompare(b.rankedValue)`_ By default, match-sorter uses the `String.localeCompare` function to tie-break items that have the same ranking. This results in a stable, alphabetic sort. @@ -460,6 +457,7 @@ Thanks goes to these people ([emoji key][emojis]): + This project follows the [all-contributors][all-contributors] specification. @@ -472,8 +470,8 @@ MIT [npm]: https://www.npmjs.com [node]: https://nodejs.org -[build-badge]: https://img.shields.io/travis/kentcdodds/match-sorter.svg?style=flat-square -[build]: https://travis-ci.org/kentcdodds/match-sorter +[build-badge]: https://img.shields.io/github/workflow/status/kentcdodds/match-sorter/validate?logo=github&style=flat-square +[build]: https://github.com/kentcdodds/match-sorter/actions?query=workflow%3Avalidate [coverage-badge]: https://img.shields.io/codecov/c/github/kentcdodds/match-sorter.svg?style=flat-square [coverage]: https://codecov.io/github/kentcdodds/match-sorter [version-badge]: https://img.shields.io/npm/v/match-sorter.svg?style=flat-square @@ -481,15 +479,19 @@ MIT [downloads-badge]: https://img.shields.io/npm/dm/match-sorter.svg?style=flat-square [npmtrends]: https://www.npmtrends.com/match-sorter [license-badge]: https://img.shields.io/npm/l/match-sorter.svg?style=flat-square -[license]: https://github.com/kentcdodds/match-sorter/blob/master/other/LICENSE +[license]: https://github.com/kentcdodds/match-sorter/blob/master/LICENSE [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square [prs]: http://makeapullrequest.com [coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square -[coc]: https://github.com/kentcdodds/match-sorter/blob/master/other/CODE_OF_CONDUCT.md +[coc]: https://github.com/kentcdodds/match-sorter/blob/master/CODE_OF_CONDUCT.md [examples-badge]: https://img.shields.io/badge/%F0%9F%92%A1-examples-8C8E93.svg?style=flat-square [examples]: https://github.com/kentcdodds/match-sorter/blob/master/other/EXAMPLES.md [emojis]: https://github.com/all-contributors/all-contributors#emoji-key [all-contributors]: https://github.com/all-contributors/all-contributors +[all-contributors-badge]: https://img.shields.io/github/all-contributors/kentcdodds/match-sorter?color=orange&style=flat-square +[bugs]: https://github.com/kentcdodds/match-sorter/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Acreated-desc+label%3Abug +[requests]: https://github.com/kentcdodds/match-sorter/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement +[good-first-issue]: https://github.com/kentcdodds/match-sorter/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement+label%3A%22good+first+issue%22 [genie]: https://github.com/kentcdodds/genie diff --git a/other/CODE_OF_CONDUCT.md b/other/CODE_OF_CONDUCT.md deleted file mode 100644 index 5cf7e48..0000000 --- a/other/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,75 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of -experience, nationality, personal appearance, race, religion, or sexual identity -and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -- Using welcoming and inclusive language -- Being respectful of differing viewpoints and experiences -- Gracefully accepting constructive criticism -- Focusing on what is best for the community -- Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -- The use of sexualized language or imagery and unwelcome sexual attention or - advances -- Trolling, insulting/derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information, such as a physical or electronic - address, without explicit permission -- Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, or to ban temporarily or permanently any -contributor for other behaviors that they deem inappropriate, threatening, -offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at me+coc@kentcdodds.com. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an -incident. Further details of specific enforcement policies may be posted -separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/other/MAINTAINING.md b/other/MAINTAINING.md index 703126d..cade1c2 100644 --- a/other/MAINTAINING.md +++ b/other/MAINTAINING.md @@ -32,9 +32,9 @@ any more of you than that. As a maintainer, you're fine to make your branches on the main repo or on your own fork. Either way is fine. -When we receive a pull request, a travis build is kicked off automatically (see -the `.travis.yml` for what runs in the travis build). We avoid merging anything -that breaks the travis build. +When we receive a pull request, a github action is kicked off automatically (see +the `.github/workflows/validate.yml` for what runs in the action). We avoid +merging anything that breaks the validate action. Please review PRs and focus on the code rather than the individual. You never know when this is someone's first ever PR and we want their experience to be as @@ -49,7 +49,7 @@ to release. See the next section on Releases for more about that. ## Release Our releases are automatic. They happen whenever code lands into `master`. A -travis build gets kicked off and if it's successful, a tool called +github action gets kicked off and if it's successful, a tool called [`semantic-release`](https://github.com/semantic-release/semantic-release) is used to automatically publish a new release to npm as well as a changelog to GitHub. It is only able to determine the version and whether a release is diff --git a/other/USERS.md b/other/USERS.md new file mode 100644 index 0000000..4bc1281 --- /dev/null +++ b/other/USERS.md @@ -0,0 +1,12 @@ +# Users + +If you or your company uses this project, add your name to this list! Eventually +we may have a website to showcase these (wanna build it!?) + +> No users have been added yet! + + diff --git a/package.json b/package.json index 37dd252..a46c87e 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "lint": "kcd-scripts lint", "setup": "npm install && npm run validate -s", "test": "kcd-scripts test", + "typecheck": "kcd-scripts typecheck", "test:update": "npm test -- --updateSnapshot --coverage", "validate": "kcd-scripts validate" }, @@ -25,11 +26,14 @@ "author": "Kent C. Dodds (https://kentcdodds.com)", "license": "MIT", "dependencies": { - "@babel/runtime": "^7.10.5", + "@babel/runtime": "^7.12.5", "remove-accents": "0.4.2" }, "devDependencies": { - "kcd-scripts": "^6.2.4" + "@rollup/plugin-typescript": "^6.1.0", + "@types/jest": "^26.0.15", + "kcd-scripts": "^7.2.0", + "typescript": "^4.1.2" }, "eslintConfig": { "extends": [ diff --git a/src/__tests__/index.js b/src/__tests__/index.ts similarity index 94% rename from src/__tests__/index.js rename to src/__tests__/index.ts index 20cc170..059806f 100644 --- a/src/__tests__/index.js +++ b/src/__tests__/index.ts @@ -1,10 +1,13 @@ -import {matchSorter, rankings} from '../' +import {matchSorter, rankings, MatchSorterOptions} from '../' -const tests = { - 'returns an empty array with a string that is too long': { - input: [['Chakotay', 'Charzard'], 'JonathanJonathan'], - output: [], - }, +type TestCase = { + input: [Array, string, MatchSorterOptions?] + output: Array + only?: boolean + skip?: boolean +} + +const tests: Record = { 'returns an empty array with a string that matches no items': { input: [['Chakotay', 'Charzard'], 'nomatch'], output: [], @@ -130,6 +133,7 @@ const tests = { input: [ [{name: {first: 'baz'}}, {name: {first: 'bat'}}, {name: {first: 'foo'}}], 'ba', + // @ts-expect-error I don't know how to make this typed properly {keys: [item => item.name.first]}, ], output: [{name: {first: 'bat'}}, {name: {first: 'baz'}}], @@ -381,14 +385,19 @@ const tests = { {name: 'Jen_Smith'}, ], 'js', + // @ts-expect-error I don't know how to make this typed properly {keys: [item => item.name.replace(/_/g, ' ')]}, ], output: [{name: 'Jen_Smith'}, {name: 'Janice_Kurtis'}], }, } -Object.keys(tests).forEach(title => { - const {input, output, only, skip} = tests[title] +for (const [ + title, + {input, output, only = false, skip = false}, +] of Object.entries(tests)) { + const testFn = () => expect(matchSorter(...input)).toEqual(output) + if (only) { test.only(title, testFn) } else if (skip) { @@ -396,15 +405,13 @@ Object.keys(tests).forEach(title => { } else { test(title, testFn) } - - function testFn() { - expect(matchSorter(...input)).toEqual(output) - } -}) +} /* eslint jest/valid-title: "off", jest/no-disabled-tests: "off", jest/no-focused-tests: "off", + @typescript-eslint/no-unsafe-call: "off", + @typescript-eslint/no-unsafe-member-access: "off" */ diff --git a/src/index.js b/src/index.ts similarity index 53% rename from src/index.js rename to src/index.ts index d5b7f8d..87cf783 100644 --- a/src/index.js +++ b/src/index.ts @@ -6,6 +6,51 @@ */ import removeAccents from 'remove-accents' +type KeyAttributes = { + threshold?: number + maxRanking: number + minRanking: number +} +interface RankingInfo { + rankedValue: string + rank: number + keyIndex: number + keyThreshold: number | undefined +} + +interface ValueGetterKey { + (item: ItemType): string +} +interface IndexedItem { + item: ItemType + index: number +} +interface RankedItem extends RankingInfo, IndexedItem {} + +interface BaseSorter { + (a: RankedItem, b: RankedItem): number +} + +interface KeyAttributesOptions { + key?: string | ValueGetterKey + threshold?: number + maxRanking?: number + minRanking?: number +} + +type KeyOption = + | KeyAttributesOptions + | ValueGetterKey + | string + +// ItemType = unknown allowed me to make these changes without the need to change the current tests +interface MatchSorterOptions { + keys?: Array> + threshold?: number + baseSort?: BaseSorter + keepDiacritics?: boolean +} + const rankings = { CASE_SENSITIVE_EQUAL: 7, EQUAL: 6, @@ -19,8 +64,8 @@ const rankings = { matchSorter.rankings = rankings -const defaultBaseSortFn = (a, b) => - String(a.rankedItem).localeCompare(b.rankedItem) +const defaultBaseSortFn: BaseSorter = (a, b) => + String(a.rankedValue).localeCompare(String(b.rankedValue)) /** * Takes an array of items and a value and returns a new array with the items that match the given value @@ -29,26 +74,33 @@ const defaultBaseSortFn = (a, b) => * @param {Object} options - Some options to configure the sorter * @return {Array} - the new sorted array */ -function matchSorter(items, value, options = {}) { +function matchSorter( + items: Array, + value: string, + options: MatchSorterOptions = {}, +): Array { const { keys, threshold = rankings.MATCHES, baseSort = defaultBaseSortFn, } = options - const matchedItems = items.reduce(reduceItemsToRanked, []) + const matchedItems = items.reduce>>( + reduceItemsToRanked, + [], + ) return matchedItems - .sort((a, b) => sortRankedItems(a, b, baseSort)) + .sort((a, b) => sortRankedValues(a, b, baseSort)) .map(({item}) => item) - function reduceItemsToRanked(matches, item, index) { - const { - rankedItem, - rank, - keyIndex, - keyThreshold = threshold, - } = getHighestRanking(item, keys, value, options) + function reduceItemsToRanked( + matches: Array>, + item: ItemType, + index: number, + ): Array> { + const rankingInfo = getHighestRanking(item, keys, value, options) + const {rank, keyThreshold = threshold} = rankingInfo if (rank >= keyThreshold) { - matches.push({rankedItem, item, rank, index, keyIndex}) + matches.push({...rankingInfo, item, index}) } return matches } @@ -62,25 +114,37 @@ function matchSorter(items, value, options = {}) { * @param {Object} options - options to control the ranking * @return {{rank: Number, keyIndex: Number, keyThreshold: Number}} - the highest ranking */ -function getHighestRanking(item, keys, value, options) { +function getHighestRanking( + item: ItemType, + keys: Array> | undefined, + value: string, + options: MatchSorterOptions, +): RankingInfo { if (!keys) { + // if keys is not specified, then we assume the item given is ready to be matched + const stringItem = (item as unknown) as string return { // ends up being duplicate of 'item' in matches but consistent - rankedItem: item, - rank: getMatchRanking(item, value, options), + rankedValue: stringItem, + rank: getMatchRanking(stringItem, value, options), keyIndex: -1, keyThreshold: options.threshold, } } - const valuesToRank = getAllValuesToRank(item, keys) - return valuesToRank.reduce( + const valuesToRank = getAllValuesToRank(item, keys) + return valuesToRank.reduce<{ + rankedValue: string + rank: number + keyIndex: number + keyThreshold: number | undefined + }>( ( - {rank, rankedItem, keyIndex, keyThreshold}, + {rank, rankedValue, keyIndex, keyThreshold}, {itemValue, attributes}, i, ) => { - let newRank = getMatchRanking(itemValue, value, options) - let newRankedItem = rankedItem + let newRank = getMatchRanking(itemValue, value, options) + let newRankedValue = rankedValue const {minRanking, maxRanking, threshold} = attributes if (newRank < minRanking && newRank >= rankings.MATCHES) { newRank = minRanking @@ -91,11 +155,16 @@ function getHighestRanking(item, keys, value, options) { rank = newRank keyIndex = i keyThreshold = threshold - newRankedItem = itemValue + newRankedValue = itemValue } - return {rankedItem: newRankedItem, rank, keyIndex, keyThreshold} + return {rankedValue: newRankedValue, rank, keyIndex, keyThreshold} + }, + { + rankedValue: (item as unknown) as string, + rank: rankings.NO_MATCH, + keyIndex: -1, + keyThreshold: options.threshold, }, - {rank: rankings.NO_MATCH, keyIndex: -1, keyThreshold: options.threshold}, ) } @@ -106,10 +175,14 @@ function getHighestRanking(item, keys, value, options) { * @param {Object} options - options for the match (like keepDiacritics for comparison) * @returns {Number} the ranking for how well stringToRank matches testString */ -function getMatchRanking(testString, stringToRank, options) { +function getMatchRanking( + testString: string, + stringToRank: string, + options: MatchSorterOptions, +): number { /* eslint complexity:[2, 12] */ - testString = prepareValueForComparison(testString, options) - stringToRank = prepareValueForComparison(stringToRank, options) + testString = prepareValueForComparison(testString, options) + stringToRank = prepareValueForComparison(stringToRank, options) // too long if (stringToRank.length > testString.length) { @@ -131,17 +204,17 @@ function getMatchRanking(testString, stringToRank, options) { } // starts with - if (testString.indexOf(stringToRank) === 0) { + if (testString.startsWith(stringToRank)) { return rankings.STARTS_WITH } // word starts with - if (testString.indexOf(` ${stringToRank}`) !== -1) { + if (testString.includes(` ${stringToRank}`)) { return rankings.WORD_STARTS_WITH } // contains - if (testString.indexOf(stringToRank) !== -1) { + if (testString.includes(stringToRank)) { return rankings.CONTAINS } else if (stringToRank.length === 1) { // If the only character in the given stringToRank @@ -151,7 +224,7 @@ function getMatchRanking(testString, stringToRank, options) { } // acronym - if (getAcronym(testString).indexOf(stringToRank) !== -1) { + if (getAcronym(testString).includes(stringToRank)) { return rankings.ACRONYM } @@ -166,7 +239,7 @@ function getMatchRanking(testString, stringToRank, options) { * @param {String} string the string for which to produce the acronym * @returns {String} the acronym */ -function getAcronym(string) { +function getAcronym(string: string): string { let acronym = '' const wordsInString = string.split(' ') wordsInString.forEach(wordInString => { @@ -188,10 +261,14 @@ function getAcronym(string) { * @returns {Number} the number between rankings.MATCHES and * rankings.MATCHES + 1 for how well stringToRank matches testString */ -function getClosenessRanking(testString, stringToRank) { +function getClosenessRanking(testString: string, stringToRank: string): number { let matchingInOrderCharCount = 0 let charNumber = 0 - function findMatchingCharacter(matchChar, string, index) { + function findMatchingCharacter( + matchChar: string, + string: string, + index: number, + ) { for (let j = index; j < string.length; j++) { const stringChar = string[j] if (stringChar === matchChar) { @@ -201,7 +278,7 @@ function getClosenessRanking(testString, stringToRank) { } return -1 } - function getRanking(spread) { + function getRanking(spread: number) { const spreadPercentage = 1 / spread const inOrderPercentage = matchingInOrderCharCount / stringToRank.length const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage @@ -231,7 +308,11 @@ function getClosenessRanking(testString, stringToRank) { * @param {Object} b - the second item to sort * @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal */ -function sortRankedItems(a, b, baseSort) { +function sortRankedValues( + a: RankedItem, + b: RankedItem, + baseSort: BaseSorter, +): number { const aFirst = -1 const bFirst = 1 const {rank: aRank, keyIndex: aKeyIndex} = a @@ -255,7 +336,12 @@ function sortRankedItems(a, b, baseSort) { * @param {Object} options - {keepDiacritics: whether to remove diacritics} * @return {String} the prepared value */ -function prepareValueForComparison(value, {keepDiacritics}) { +function prepareValueForComparison( + value: string, + {keepDiacritics}: MatchSorterOptions, +): string { + // value might not actually be a string at this point (we don't get to choose) + // so part of preparing the value for comparison is ensure that it is a string value = `${value}` // toString if (!keepDiacritics) { value = removeAccents(value) @@ -269,65 +355,97 @@ function prepareValueForComparison(value, {keepDiacritics}) { * @param {Object|Function} key - the potentially nested keypath or property callback * @return {Array} - an array containing the value(s) at the nested keypath */ -function getItemValues(item, key) { +function getItemValues( + item: ItemType, + key: KeyOption, +): Array | null { if (typeof key === 'object') { - key = key.key + key = key.key as string } - let value + let value: string | Array | null if (typeof key === 'function') { value = key(item) // eslint-disable-next-line no-negated-condition - } else if (key.indexOf('.') !== -1) { - // handle nested keys - value = key - .split('.') - .reduce( - (itemObj, nestedKey) => (itemObj ? itemObj[nestedKey] : null), - item, - ) } else { - value = item[key] + value = getNestedValue(key, item) } + const values: Array = [] // concat because `value` can be a string or an array // eslint-disable-next-line - return value != null ? [].concat(value) : null + return value != null ? values.concat(value) : null +} + +/** + * Given key: "foo.bar.baz" + * And obj: {foo: {bar: {baz: 'buzz'}}} + * -> 'buzz' + * @param key a dot-separated set of keys + * @param obj the object to get the value from + */ +function getNestedValue( + key: string, + obj: ItemType, +): string | Array | null { + // @ts-expect-error really have no idea how to type this properly... + return key.split('.').reduce((itemObj: object | null, nestedKey: string): + | object + | string + | null => { + // @ts-expect-error lost on this one as well... + return itemObj ? itemObj[nestedKey] : null + }, obj) } /** * Gets all the values for the given keys in the given item and returns an array of those values - * @param {Object} item - the item from which the values will be retrieved - * @param {Array} keys - the keys to use to retrieve the values - * @return {Array} objects with {itemValue, attributes} + * @param item - the item from which the values will be retrieved + * @param keys - the keys to use to retrieve the values + * @return objects with {itemValue, attributes} */ -function getAllValuesToRank(item, keys) { - return keys.reduce((allVals, key) => { - const values = getItemValues(item, key) - if (values) { - values.forEach(itemValue => { - allVals.push({ - itemValue, - attributes: getKeyAttributes(key), +function getAllValuesToRank( + item: ItemType, + keys: Array>, +) { + return keys.reduce>( + (allVals, key) => { + const values = getItemValues(item, key) + if (values) { + values.forEach(itemValue => { + allVals.push({ + itemValue, + attributes: getKeyAttributes(key), + }) }) - }) - } - return allVals - }, []) + } + return allVals + }, + [], + ) } +const defaultKeyAttributes = { + maxRanking: Infinity, + minRanking: -Infinity, +} /** * Gets all the attributes for the given key - * @param {Object|String} key - the key from which the attributes will be retrieved - * @return {Object} object containing the key's attributes + * @param key - the key from which the attributes will be retrieved + * @return object containing the key's attributes */ -function getKeyAttributes(key) { +function getKeyAttributes(key: KeyOption): KeyAttributes { if (typeof key === 'string') { - key = {key} - } - return { - maxRanking: Infinity, - minRanking: -Infinity, - ...key, + return defaultKeyAttributes } + return {...defaultKeyAttributes, ...key} } -export {matchSorter, rankings} +export {matchSorter, rankings, defaultBaseSortFn} + +export type { + MatchSorterOptions, + KeyAttributesOptions, + KeyOption, + KeyAttributes, + RankingInfo, + ValueGetterKey, +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..b41b885 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "./node_modules/kcd-scripts/shared-tsconfig.json" +}