Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created February 20, 2017 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/9f05e1faed51758adbd54ccd4b72f674 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/9f05e1faed51758adbd54ccd4b72f674 to your computer and use it in GitHub Desktop.
'use strict';
import { IIterable, IIterator } from '../iterable.interfaces';
import { Iterable } from '../iterable';
import { Iterator } from '../iterator';
export class FinallyIterator<T> extends Iterator<T> {
private _it: IIterator<T>;
private _fn: () => void;
private _called: boolean;
constructor(it: IIterator<T>, fn: () => void) {
super();
this._it = it;
this._fn = fn;
this._called = false;
}
next() {
let next;
try {
next = this._it.next();
} catch(e) {
next = this._it.next();
}
if (next.done && !this._called) {
this._called = true;
this._fn();
}
return next;
}
}
export class FinallyIterable<T> extends Iterable<T> {
private _source: IIterable<T>;
private _fn: () => void;
constructor(source: IIterable<T>, fn: () => void) {
super();
this._source = source;
this._fn = fn;
}
[Symbol.iterator]() {
return new FinallyIterator<T>(this._source[Symbol.iterator](), this._fn);
}
}
export function _finally<T>(
source: IIterable<T>,
fn: () => void): Iterable<T> {
return new FinallyIterable<T>(source, fn);
}
const f = function* () { throw new Error(42); }
Ix.Iterable.from(f())
.finally(() => console.log('done'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment