Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support shorthand object initializer syntax (fixes #9) #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
},
"homepage": "https://github.com/captainsafia/fony#readme",
"dependencies": {
"babel-core": "^6.24.1",
"chance": "^1.0.6",
"commander": "^2.9.0"
}
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const program = require('commander');

const _version_ = require('../package.json').version;
const createData = require('./utils');
const transform = require('./transform');

program
.version(_version_);
Expand All @@ -16,7 +17,7 @@ program

var template;
try {
template = JSON.parse(program.template);
template = eval(transform(program.template));
} catch (error) {
return console.log(error);
}
Expand Down
26 changes: 26 additions & 0 deletions src/transform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Generate AST from an es6 object initializer string
// May want to support syntax like "word*3" to generate an array of 3 words
// or other more complex syntaxes
const babel = require("babel-core");

// transforms ({ a: a }) or equivalently ({ a }) into
// ({a: "a" }), note the value is stringified
function transformPlugin(babel) {
const { types: t } = babel;

return {
visitor: {
Property({ node }) {
if (t.isIdentifier(node.value))
node.value = t.stringLiteral(node.value.name);
}
}
};
}

module.exports = code => {
return babel.transform(`(${code})`, {
plugins: [transformPlugin],
ast: false // don't need the ast (for now?)
}).code;
};