Skip to content

Commit

Permalink
[New] named-order : apply pr review that order options has caseInse…
Browse files Browse the repository at this point in the history
…nsitive, lowercaseFirst, uppercaseFirst values
  • Loading branch information
ronparkdev committed Sep 18, 2022
1 parent 74df892 commit 41b5888
Showing 1 changed file with 24 additions and 17 deletions.
41 changes: 24 additions & 17 deletions src/rules/named-order.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,12 @@ import docsUrl from '../docsUrl';

function getOptions(context) {
const {
caseInsensitive = false,
order = 'asc',
order = 'caseInsensitive',
commonjs = true,
esmodule = true,
} = context.options[0] || {};

return {
caseInsensitive,
order,
commonjs,
esmodule,
Expand Down Expand Up @@ -45,26 +43,39 @@ function compareString(left, right) {
return 0;
}

function makeDeepSorter(options, sortFieldKeyPath) {
const orderMultiplier = options.order === 'desc' ? -1 : 1;
function getCaseFlippedStr(str) {
return Array.from(str)
.map(char => {
if (char >= 'a' && char <= 'z') {
return char.toUpperCase();
} else if (char >= 'A' && char <= 'Z') {
return char.toLowerCase();
}
return char;
})
.join('');
}

function makeDeepSorter(options, sortFieldKeyPath) {
const sortFieldKeys = sortFieldKeyPath.split('.');

function getNormalizedValue(rootValue) {
const value = sortFieldKeys.reduce((value, key) => value[key], rootValue);
const value = String(sortFieldKeys.reduce((value, key) => value[key], rootValue));

return options.caseInsensitive
? String(value).toLowerCase()
: String(value);
switch (options.order) {
case 'caseInsensitive': return value.toLowerCase();
case 'lowercaseFirst': return getCaseFlippedStr(value);
case 'uppercaseFirst': return value;
default: return ''; // Invalid order option
}
}

return function sorter(left, right) {
const leftValue = getNormalizedValue(left);
const rightValue = getNormalizedValue(right);

const order = compareString(leftValue, rightValue);

return order * orderMultiplier;
return order;
};
}

Expand All @@ -84,13 +95,9 @@ module.exports = {
{
type: 'object',
properties: {
caseInsensitive: {
type: 'boolean',
default: false,
},
order: {
enum: ['asc', 'desc'],
default: 'asc',
enum: ['caseInsensitive', 'lowercaseFirst', 'uppercaseFirst'],
default: 'caseInsensitive',
},
commonjs: {
type: 'boolean',
Expand Down

0 comments on commit 41b5888

Please sign in to comment.