Browse Source

improve generator performance

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

38
lindenmayer-system/lindenmeyer-system.js

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

Loading…
Cancel
Save