-
Notifications
You must be signed in to change notification settings - Fork 3
/
erratic.js
41 lines (32 loc) · 1.04 KB
/
erratic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright 2012 Daniel Connelly.
// Released under the Simplified (2-clause) BSD License.
// See http://dhconnelly.com/erratic or the LICENSE file for more details.
(function (exports, imports) {
'use strict';
exports.version = '0.1.0';
exports.parse = parse;
exports.generate = generate;
var prettybnf = imports.prettybnf;
function extract(prop, o) {
return o[prop];
}
function parse(grammar) {
var ast = prettybnf.parse(grammar);
var rules = {};
ast.productions.forEach(function (prod) {
rules[prod.lhs.text] = prod.rhs.map(extract.bind(null, 'terms'));
});
return rules;
}
function choose(things) {
return things[Math.floor(Math.random() * things.length)];
}
function generateTerm(rules, term) {
return (term.type === 'terminal') ? term.text : generate(rules, term.text);
}
function generate(rules, rule) {
return choose(rules[rule]).map(generateTerm.bind(null, rules)).join('');
}
}(typeof exports === 'undefined' ? this.erratic = {} : exports, {
prettybnf: this.prettybnf || require('prettybnf')
}));