Created
December 10, 2019 11:07
-
-
Save WouterSpaak/e676dd1651a55dd7f8c185eec592411b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!
Micro amendment:
yield axiom
at the very beginning if the*iterate()
in order to see the seed as well.