Browse Source

improve generator performance

master
Fr3deric 5 years ago
parent
commit
2e7bf056b8
  1. 38
      lindenmayer-system/lindenmeyer-system.js

38
lindenmayer-system/lindenmeyer-system.js

@ -1,8 +1,7 @@
function startswith(a, b) { function rule_applicable(word, pos, consumed, rule) {
for(let i=0; i<b.length; i++) { for(let i=0; i<rule.length; i++) {
// in JS, ['X'] == 'X' if((word[pos+i] != rule[i]) | (consumed[pos+i] == true)) {
if((a[i] != b[i]) | (typeof a[i] != typeof b[i])) {
return false; return false;
} }
} }
@ -15,37 +14,36 @@ function generate(start, rules, iterations) {
return start; return start;
} }
var word = start;
var consumed = new Array(word.length);
for(let rule of rules) { for(let rule of rules) {
let pos = 0; let pos = 0;
while(pos < start.length) { var newword = [];
let w = start.slice(pos, pos + rule[0].length); var newconsumed = [];
if(startswith(w, rule[0])) { while(pos < word.length) {
if(rule_applicable(word, pos, consumed, rule[0])) {
var ruleres; var ruleres;
if(typeof rule[1] == 'function') { if(typeof rule[1] == 'function') {
ruleres = rule[1](); ruleres = rule[1]();
} else { } else {
ruleres = rule[1]; ruleres = rule[1];
} }
start.splice(pos, rule[0].length, ruleres) newword.push(...ruleres);
for(let i=0; i<ruleres.length; i++) {
newconsumed.push(true);
}
pos += rule[0].length; pos += rule[0].length;
} else { } else {
newword.push(word[pos]);
newconsumed.push(false);
pos += 1; pos += 1;
} }
} }
word = newword;
consumed = newconsumed;
} }
// TODO find a better way return generate(newword, rules, iterations - 1);
let ret = [];
for(let x of start) {
if(typeof x === 'object') {
// TODO why?
//ret.concat(x);
ret = ret.concat(x);
} else {
ret.push(x);
}
}
return generate(ret, rules, iterations - 1);
} }

Loading…
Cancel
Save