Skip to content

Instantly share code, notes, and snippets.

@tlareg
Created December 23, 2022 22:38
Show Gist options
  • Save tlareg/2545382d688a777e3bbaae4914758a33 to your computer and use it in GitHub Desktop.
Save tlareg/2545382d688a777e3bbaae4914758a33 to your computer and use it in GitHub Desktop.
streams
type Stream<T> =
| {
value: T;
getNext: () => Stream<T>;
}
| undefined;
type CreateStreamArgs<T> = {
value: T;
next: (x: T) => T;
endCond: (x: T) => boolean;
};
const createStream = <T>({
value,
...fns
}: CreateStreamArgs<T>): Stream<T> => ({
value,
getNext: () => {
if (fns.endCond(value)) {
return;
}
return createStream({ value: fns.next(value), ...fns });
},
});
let integersUpToTenStream = createStream<number>({
value: 0,
next: (x) => x + 1,
endCond: (x) => x >= 10,
});
while ((integersUpToTenStream = integersUpToTenStream?.getNext())) {
console.log(integersUpToTenStream.value);
}
type MutableStream<T> = {
getValue: () => T;
getNext: () => T | undefined;
};
type CreateMutableStreamArgs<T> = {
value: T;
endCond: (x: T) => boolean;
next: (x: T, cache: T[]) => T;
cacheLength?: number;
};
const createMutableStream = <T>({
value,
endCond,
next,
cacheLength = 1,
}: CreateMutableStreamArgs<T>): MutableStream<T> => {
let _value = value;
let cache = new Array(cacheLength);
cache.push(_value);
return {
getValue: () => _value,
getNext: () => {
if (endCond(_value)) {
return;
}
_value = next(_value, cache);
cache.push(_value);
cache = cache.slice(Math.max(cache.length - cacheLength, 0));
return _value;
},
};
};
const integersUpToTenMutableStream = createMutableStream<number>({
value: 0,
next: (x) => x + 1,
endCond: (x) => x >= 10,
});
while (integersUpToTenMutableStream.getNext()) {
console.log(integersUpToTenMutableStream.getValue());
}
const fibonacciStream = createMutableStream<number>({
value: 0,
next: (x, cache) =>
x === 0
? 1
: cache[cache.length - 1] + cache[cache.length - 2],
endCond: (x) => x > 150,
cacheLength: 2,
});
while (fibonacciStream.getNext()) {
console.log(fibonacciStream.getValue());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment