Skip to content

Commit a75d87f

Browse files
feat(iterables): Sort by - descending
Add version of sort which reverses output. re #4
1 parent 5c3cf58 commit a75d87f

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/iterables.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,26 @@ export function sortBy<T, Key>(a: any, b?: any): any {
285285
return partial ? exec : exec(a)
286286
}
287287

288+
export function sortByDescending<T, Key>(
289+
selector: (item: T) => Key
290+
): (source: Iterable<T>) => Iterable<T>
291+
export function sortByDescending<T, Key>(
292+
source: Iterable<T>,
293+
selector: (item: T) => Key
294+
): Iterable<T>
295+
export function sortByDescending<T, Key>(a: any, b?: any): any {
296+
const partial = typeof a === 'function'
297+
const selector: (item: T) => Key = partial ? a : b
298+
function exec(source: Iterable<T>): Iterable<T> {
299+
const copy = Array.from(source)
300+
copy.sort((a: T, b: T) => {
301+
return selector(a) > selector(b) ? -1 : 1
302+
})
303+
return copy
304+
}
305+
return partial ? exec : exec(a)
306+
}
307+
288308
export function sumBy<T>(selector: (item: T) => number): (source: Iterable<T>) => number
289309
export function sumBy<T>(source: Iterable<T>, selector: (item: T) => number): number
290310
export function sumBy<T>(a: any, b?: any): any {

test/iterable.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,36 @@ describe('sortBy', () => {
530530
})
531531
})
532532

533+
describe('sortByDescending', () => {
534+
test('piped', () => {
535+
expect(
536+
pipe(
537+
(function*() {
538+
yield { name: 'amy', age: 21 }
539+
yield { name: 'bob', age: 2 }
540+
yield { name: 'cat', age: 18 }
541+
})()
542+
)
543+
.then(Iterables.sortByDescending(x => x.age))
544+
.then(Iterables.toArray).result
545+
).toEqual([{ name: 'amy', age: 21 }, { name: 'cat', age: 18 }, { name: 'bob', age: 2 }])
546+
})
547+
test('invoke', () => {
548+
expect(
549+
Iterables.toArray(
550+
Iterables.sortByDescending(
551+
(function*() {
552+
yield { name: 'amy', age: 21 }
553+
yield { name: 'bob', age: 2 }
554+
yield { name: 'cat', age: 18 }
555+
})(),
556+
x => x.age
557+
)
558+
)
559+
).toEqual([{ name: 'amy', age: 21 }, { name: 'cat', age: 18 }, { name: 'bob', age: 2 }])
560+
})
561+
})
562+
533563
describe('sumBy', () => {
534564
it('sums ages', () => {
535565
expect(

0 commit comments

Comments
 (0)