Skip to content

Instantly share code, notes, and snippets.

@mieszko4
Created March 28, 2018 23:43
Show Gist options
  • Save mieszko4/cef53a9abb484064b43f4ea5c92e436f to your computer and use it in GitHub Desktop.
Save mieszko4/cef53a9abb484064b43f4ea5c92e436f to your computer and use it in GitHub Desktop.

Revisions

  1. mieszko4 created this gist Mar 28, 2018.
    53 changes: 53 additions & 0 deletions PromiseDelayToDelay.codemod.js
    Original 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;
    };