import type { TSESLint , TSESTree } from '@typescript-eslint/experimental-utils' ; import docsUrl from '../utils/docs-url' ; const rule = { meta : { messages : { replaceForWithWhileLoop : 'Replace this "for" loop with a "while" loop.' , } , schema : [ ] , type : 'suggestion' , docs : { description : 'A "while" loop should be used instead of a "for" loop' , recommended : 'error' , url : docsUrl ( __filename ) , } , fixable : 'code' , } , create ( context ) { return { ForStatement ( node ) { const forLoop = node as TSESTree . ForStatement ; const forKeyword = context . getSourceCode ( ) . getFirstToken ( node ) ; if ( ! forLoop . init && ! forLoop . update && forLoop . test && forKeyword ) { context . report ( { messageId : `replaceForWithWhileLoop` , loc : forKeyword . loc , fix : getFix ( forLoop ) , } ) ; } } , } ; function getFix ( forLoop ) { const forLoopRange = forLoop . range ; const closingParenthesisToken = context . getSourceCode ( ) . getTokenBefore ( forLoop . body ) ; const condition = forLoop . test ; if ( condition && forLoopRange && closingParenthesisToken ) { return ( fixer ) => { const start = forLoopRange [ 0 ] ; const end = closingParenthesisToken . range [ 1 ] ; const conditionText = context . getSourceCode ( ) . getText ( condition ) ; return fixer . replaceTextRange ( [ start , end ] , `while (${ conditionText })` ) ; } ; } return undefined ; } } , } ; export = rule ;