|
| 1 | +import jscodeshift from 'jscodeshift'; |
| 2 | +import { removeImport } from '../shared.js'; |
| 3 | + |
| 4 | +/** |
| 5 | + * @typedef {import('../../types.js').Codemod} Codemod |
| 6 | + * @typedef {import('../../types.js').CodemodOptions} CodemodOptions |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * @param {CodemodOptions} [options] |
| 11 | + * @returns {Codemod} |
| 12 | + */ |
| 13 | +export default function (options) { |
| 14 | + return { |
| 15 | + name: 'iterate-iterator', |
| 16 | + transform: ({ file }) => { |
| 17 | + const j = jscodeshift; |
| 18 | + const root = j(file.source); |
| 19 | + let isDirty = false; |
| 20 | + |
| 21 | + const { identifier } = removeImport('iterate-iterator', root, j); |
| 22 | + |
| 23 | + if (identifier) { |
| 24 | + const callExpressions = root.find(j.CallExpression, { |
| 25 | + callee: { |
| 26 | + type: 'Identifier', |
| 27 | + name: identifier, |
| 28 | + }, |
| 29 | + }); |
| 30 | + |
| 31 | + for (const path of callExpressions.paths()) { |
| 32 | + const args = path.node.arguments; |
| 33 | + |
| 34 | + if (args.length === 1) { |
| 35 | + // Case: Converting an iterator to an array |
| 36 | + const [iterable] = args; |
| 37 | + const arrayFromExpression = j.callExpression( |
| 38 | + j.memberExpression(j.identifier('Array'), j.identifier('from')), |
| 39 | + [iterable], |
| 40 | + ); |
| 41 | + |
| 42 | + j(path).replaceWith(arrayFromExpression); |
| 43 | + isDirty = true; |
| 44 | + } else if (args.length === 2) { |
| 45 | + // Case: Using a callback function |
| 46 | + const [iterable, callback] = args; |
| 47 | + const iterableArg = |
| 48 | + iterable.type === 'SpreadElement' ? iterable.argument : iterable; |
| 49 | + |
| 50 | + if ( |
| 51 | + callback.type !== 'Identifier' && |
| 52 | + callback.type !== 'FunctionExpression' && |
| 53 | + callback.type !== 'ArrowFunctionExpression' |
| 54 | + ) { |
| 55 | + continue; |
| 56 | + } |
| 57 | + |
| 58 | + const forOfStatement = j.forOfStatement( |
| 59 | + j.variableDeclaration('const', [ |
| 60 | + j.variableDeclarator(j.identifier('i')), |
| 61 | + ]), |
| 62 | + iterableArg, |
| 63 | + j.blockStatement([ |
| 64 | + j.expressionStatement( |
| 65 | + j.callExpression(callback, [j.identifier('i')]), |
| 66 | + ), |
| 67 | + ]), |
| 68 | + ); |
| 69 | + |
| 70 | + j(path).replaceWith(forOfStatement); |
| 71 | + isDirty = true; |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return isDirty ? root.toSource(options) : file.source; |
| 77 | + }, |
| 78 | + }; |
| 79 | +} |
0 commit comments