Skip to content

Instantly share code, notes, and snippets.

@fronterior
Last active June 6, 2022 12:54
Show Gist options
  • Save fronterior/64ed3b029de44dcaef9afecd2c12f30b to your computer and use it in GitHub Desktop.
Save fronterior/64ed3b029de44dcaef9afecd2c12f30b to your computer and use it in GitHub Desktop.
export function* dfs<T>(root: T) {
const stack: T[] = [root];
let target: T|undefined;
while (target = stack.shift()) {
const cb: DFSNext<T> = yield target;
stack.unshift(...cb?.(target) ?? []);
}
}
export function* createDFSIterable<T>(root: T, next: DFSNext<T>) {
const iteratble = dfs(root);
let value: T|void;
let done: boolean|undefined;
while (({value, done} = iteratble.next(next)), !done) yield value;
}
/*
type Item = {
a: number;
children?: Item[];
};
const iterable = createDFSIterable<Item>(({a: 3, children: [{a: 4, children: [{a: 5}, {a: 6}]}, {a: 7}, {a: 8}]}), ({children}) => children);
*/
export function* bfs<T>(data: T) {
const stack: T[] = [data];
let target: T | undefined;
while ((target = stack.shift())) {
const cb: (target: T) => T[] | undefined = yield target;
if (typeof cb !== "function")
return;
const children = cb(target);
children && stack.push(...children);
}
}
export const createDfs = <T>(f: (p: T) => T[] | undefined) => function* (data: T) {
const iterator = dfs(data);
let target;
while (!(target = iterator.next(f)).done) yield target.value;
};
export const createBfs = <T>(f: (p: T) => T[] | undefined) => function* (data: T) {
const iterator = bfs(data);
let target;
while (!(target = iterator.next(f)).done) yield target.value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment