Skip to content

Instantly share code, notes, and snippets.

@mieszko4
Created March 28, 2018 23:43
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 mieszko4/cef53a9abb484064b43f4ea5c92e436f to your computer and use it in GitHub Desktop.
Save mieszko4/cef53a9abb484064b43f4ea5c92e436f to your computer and use it in GitHub Desktop.
Js-codemod converter from bluebird's Promise.delay to delay
module.exports = function (fileInfo, api) {
const j = api.jscodeshift;
const isPromiseDelay = (nodePath) => {
const { object, property } = nodePath.node.callee;
return object && object.name === 'Promise' && property && property.name === 'delay';
};
const isRequire = (nodePath, name) => {
if (nodePath.parent.node.type === 'Program') {
return j(nodePath)
.find(j.VariableDeclarator)
.filter((p) => {
const { id, init } = p.node;
return id.type === 'Identifier' && id.name === name &&
init.type === 'CallExpression' && init.callee.type === 'Identifier' &&
init.callee.name === 'require';
})
.size() > 0;
}
return false;
};
const transfromPromiseDelay = (nodePath) => {
const { node } = nodePath;
const idDelay = j.identifier('delay');
const newCallExpression = j.callExpression(idDelay, node.arguments);
j(nodePath).replaceWith(newCallExpression);
};
const output = j(fileInfo.source);
// replace Promise.delay to delay
const didItTransform = output.find(j.CallExpression)
.filter(isPromiseDelay)
.forEach(transfromPromiseDelay)
.size() > 0;
// add require
if (didItTransform) {
output
.find(j.VariableDeclaration)
.filter(p => isRequire(p, 'Promise'))
.forEach((nodePath) => {
j(nodePath).insertBefore('const delay = require(\'delay\');');
});
}
return didItTransform ? output.toSource() : null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment