Created
March 28, 2018 23:43
-
-
Save mieszko4/cef53a9abb484064b43f4ea5c92e436f to your computer and use it in GitHub Desktop.
Revisions
-
mieszko4 created this gist
Mar 28, 2018 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,53 @@ 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; };