Skip to content

Commit fc70cb0

Browse files
feat(iterables): Reverse
Add reverse function for iterables. re #4
1 parent 6a50a1b commit fc70cb0

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/iterables.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,13 @@ export function sortByDescending<T, Key>(a: any, b?: any): any {
305305
return partial ? exec : exec(a)
306306
}
307307

308+
export function* reverse<T>(source: Iterable<T>): Iterable<T> {
309+
const asArray = Array.from(source)
310+
for (let index = asArray.length - 1; index >= 0; index--) {
311+
yield asArray[index]
312+
}
313+
}
314+
308315
export function sumBy<T>(selector: (item: T) => number): (source: Iterable<T>) => number
309316
export function sumBy<T>(source: Iterable<T>, selector: (item: T) => number): number
310317
export function sumBy<T>(a: any, b?: any): any {

test/iterable.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,15 @@ describe('sortByDescending', () => {
560560
})
561561
})
562562

563+
describe('reverse', () => {
564+
test('empty iterable', () => {
565+
expect(Iterables.toArray(Iterables.reverse([]))).toEqual([])
566+
})
567+
test('reversal', () => {
568+
expect(Iterables.toArray(Iterables.reverse([8, 3, 5]))).toEqual([5, 3, 8])
569+
})
570+
})
571+
563572
describe('sumBy', () => {
564573
it('sums ages', () => {
565574
expect(

0 commit comments

Comments
 (0)