Skip to content

Instantly share code, notes, and snippets.

@WouterSpaak
Created December 10, 2019 11:07
Show Gist options
  • Save WouterSpaak/e676dd1651a55dd7f8c185eec592411b to your computer and use it in GitHub Desktop.
Save WouterSpaak/e676dd1651a55dd7f8c185eec592411b to your computer and use it in GitHub Desktop.
/**
* LSystem implementation.
* @see https://jsantell.com/l-systems.
*/
class LSystem<T> {
constructor(
private readonly productions: Map<T, T>,
private readonly splitter: (serialized: T) => T[],
private readonly serializer: (collection: T[]) => T
) { }
*iterate(axiom: T, iterations: number) {
while (iterations--) {
axiom = this.serializer(this.splitter(axiom).map((item) => {
return this.productions.get(item) || item;
}));
yield axiom;
}
}
}
const system = new LSystem(
new Map([
['a', 'ab'],
['b', 'c'],
['c', 'ba']
]),
(serialized) => serialized.split(''),
(collection) => collection.join('')
);
for (const iteration of system.iterate('a', 10)) {
console.log(iteration);
}
@rom-melnyk
Copy link

Nice!
Micro amendment: yield axiom at the very beginning if the *iterate() in order to see the seed as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment