jonschlinkert / sort-object-arrays

Recursively sort the array values in an object.
MIT License
5 stars 0 forks source link

the compare function assumes the function to return will be comparing only strings #1

Open Jamie-BitFlight opened 11 months ago

Jamie-BitFlight commented 11 months ago

Hi @jonschlinkert,

When try to run the tool verb on my project, i get an error caused by this library.

Logs:

❯ npm run verb

> github-action-readme-generator@1.7.2 verb
> verb

[09:37:28] starting verb
[09:37:29] ✔ running tasks: [ 'readme' ]
/github-action-readme-generator/node_modules/sort-object-arrays/index.js:44
    return a.localeCompare(b);
             ^

TypeError: a.localeCompare is not a function
    at /github-action-readme-generator/node_modules/sort-object-arrays/index.js:44:14
    at Array.sort (<anonymous>)
    at sortArrays (/github-action-readme-generator/node_modules/sort-object-arrays/index.js:27:13)
    at Function.sortArrays (/github-action-readme-generator/node_modules/sort-object-arrays/index.js:24:21)
    at Schema.sortArrays (/github-action-readme-generator/node_modules/map-schema/index.js:376:18)
    at Schema.normalize (/github-action-readme-generator/node_modules/map-schema/index.js:531:17)
    at Config.expand (/github-action-readme-generator/node_modules/expand-pkg/index.js:103:22)
    at Verb.plugin (/github-action-readme-generator/node_modules/generate-data/generator.js:39:19)
    at Verb.use (/github-action-readme-generator/node_modules/base-plugins/index.js:95:18)
    at Verb.plugin (/github-action-readme-generator/node_modules/verb-repo-data/index.js:17:7)

Node.js v20.7.0

it is fixed by updating the compare() function to be type aware. https://github.com/jonschlinkert/sort-object-arrays/blob/91022280a22ba6cfbba5b99acb2238b583deeb63/index.js#L39

/**
 * Default comparison function to use for sorting
 */

function compare(fn) {
  if (typeof fn === 'function') {
    return fn;
  }
  return function(a, b) {
    return typeof a === 'string' ? a.localeCompare(b) : String(a).localeCompare(b);
  };
}

Logs after change:

❯ npm run verb

> github-action-readme-generator@1.7.2 verb
> verb

[09:45:37] starting verb
[09:45:38] ✔ running tasks: [ 'readme' ]
[09:45:38] starting verb.readme 
[09:45:38] starting verb.readme:default task 
[09:45:38] starting verb.readme:readme task 
[09:45:39] finished verb.readme:readme task 528ms
[09:45:39] finished verb.readme:default task 565ms
[09:45:39] finished verb.readme ✔ 569ms
Jamie-BitFlight commented 11 months ago

You could even look to archive this repo, and switch to https://www.npmjs.com/package/sort-objects-array which is being maintained and chases the same objective.