Skip to content

Instantly share code, notes, and snippets.

@ollie314
Last active June 26, 2021 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ollie314/e1ddd10f7193d51b963b96078940b831 to your computer and use it in GitHub Desktop.
Save ollie314/e1ddd10f7193d51b963b96078940b831 to your computer and use it in GitHub Desktop.
Simple yeoman generator for recursive structure (sample excerpt)
const Generator = require('yeoman-generator');
const faker = require('faker');
const uuid = require('uuid');
const chalk = require('chalk');
const id = () => uuid.v4();
const rand = (min, max) => Math.ceil(Math.random() * (max - min)) + min;
const params = (type, max) => ({
hasChildren: type !== 'teams',
childrenType: type,
nb: rand(1, max)
});
const typeTemplate = [
{
name: 'id',
gen: id
},
{
name: 'name',
gen: faker.company.companyName
}
];
const genObject = ({...o}, {name, gen}) => {
o[name] = gen();
return o;
};
const genItem = (kind, types) => {
const f = (types, acc) => {
if(types.length === 0) return acc;
const [h, ...t] = types;
return f(t, genObject(acc, h));
};
return f(types, {kind});
};
const genStructure = (recipe) => {
const f = (result, currentRecipe, recipes) => {
const {nb, hasChildren, childrenType} = currentRecipe;
if(nb === 0) return result;
const item = genItem(childrenType, typeTemplate);
if(hasChildren) {
const [c, ...t] = recipes;
item[c.childrenType] = f([], c, t);
}
return f([...result, item], {...currentRecipe, nb: nb-1}, recipes);
};
const [head, ...tail] = recipe;
return f([], head, tail);
};
module.exports = class extends Generator {
constructor(args, opts) {
super(args, opts);
this.argument('type', {type: String, required: false});
this.option('af', {type: Number, required: false});
this.option('cms', { type: Number, required: false});
this.argument('teams', {type: Number, required: false});
}
installingDeps() {
//this.npmInstall(['faker', 'uuid', 'chalk'], { 'save-dev': true });
}
gen() {
this.log(chalk.green('Starting generation...'));
const type = this.options.type;
const nbAf = this.options.af || 3;
const nbCms = this.options.cms || 5;
const nbTeams = this.options.teams || 7;
const s = genStructure([params('af', nbAf), params('cms', nbCms), params('teams',nbTeams)]);
this.log(`Handling type: ${type}, af: ${nbAf}, Cms: ${nbCms}, teams: ${nbTeams}`);
this.log(JSON.stringify(s, null, 2));
}
};
@ollie314
Copy link
Author

Sample use:

yo egeon:app structure --af 3 --cms 5 --teams 7

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