Created
March 28, 2018 23:43
-
-
Save mieszko4/cef53a9abb484064b43f4ea5c92e436f to your computer and use it in GitHub Desktop.
Js-codemod converter from bluebird's Promise.delay to delay
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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