Skip to content

Commit

Permalink
revert: Revert implicit conversion in orderBy
Browse files Browse the repository at this point in the history
Revert "feat(orderBy): add handling one is a string and the other is a number case (#365)"

This reverts commit 4af0662.
  • Loading branch information
raon0211 committed Aug 10, 2024
1 parent 982aabe commit c1962f9
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 154 deletions.
48 changes: 0 additions & 48 deletions src/array/_internal/compareValues.spec.ts

This file was deleted.

46 changes: 0 additions & 46 deletions src/array/_internal/compareValues.ts

This file was deleted.

57 changes: 0 additions & 57 deletions src/array/orderBy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,61 +73,4 @@ describe('orderBy', () => {
{ user: 'fred', age: 48 },
]);
});

it('should order object has mixed value that is string and number', () => {
const actual1 = orderBy(
[
{ id: 1, value: 'a' },
{ id: 2, value: 2 },
{ id: 12, value: 1 },
{ id: 5, value: 'b' },
{ id: 4, value: 2 },
{ id: 43, value: 'c' },
{ id: 24, value: 3 },
{ id: 3, value: '3a' },
{ id: 6, value: '2a' },
{ id: 7, value: '1cs' },
],
['value', 'id'],
['asc', 'asc']
);
const expected1 = [
{ id: 12, value: 1 },
{ id: 7, value: '1cs' },
{ id: 2, value: 2 },
{ id: 4, value: 2 },
{ id: 6, value: '2a' },
{ id: 24, value: 3 },
{ id: 3, value: '3a' },
{ id: 1, value: 'a' },
{ id: 5, value: 'b' },
{ id: 43, value: 'c' },
];

const actual2 = orderBy(
[
{ id: 1, value: 'apple' },
{ id: 2, value: 'banana' },
{ id: 3, value: 'cherry' },
{ id: 4, value: 10 },
{ id: 5, value: 5 },
{ id: 6, value: 'banana' },
{ id: 7, value: 20 },
],
['value', 'id'],
['asc', 'asc']
);
const expected2 = [
{ id: 5, value: 5 },
{ id: 4, value: 10 },
{ id: 7, value: 20 },
{ id: 1, value: 'apple' },
{ id: 2, value: 'banana' },
{ id: 6, value: 'banana' },
{ id: 3, value: 'cherry' },
];

expect(actual1).toEqual(expected1);
expect(actual2).toEqual(expected2);
});
});
13 changes: 10 additions & 3 deletions src/array/orderBy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { compareValues } from './_internal/compareValues';

type Order = 'asc' | 'desc';

/**
Expand Down Expand Up @@ -34,14 +32,23 @@ type Order = 'asc' | 'desc';
* // ]
*/
export function orderBy<T>(collection: T[], keys: Array<keyof T>, orders: Order[]): T[] {
const compareValues = (a: T[keyof T], b: T[keyof T], order: Order) => {
if (a < b) {
return order === 'asc' ? -1 : 1;
}
if (a > b) {
return order === 'asc' ? 1 : -1;
}
return 0;
};

const effectiveOrders = keys.map((_, index) => orders[index] || orders[orders.length - 1]);

return collection.slice().sort((a, b) => {
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const order = effectiveOrders[i];
const result = compareValues(a[key], b[key], order);

if (result !== 0) {
return result;
}
Expand Down

0 comments on commit c1962f9

Please sign in to comment.