提交 b4964bcf 编写于 作者: M Matt Bierner

Replace some common index based for loops with `for-of` loops

Replaces many loops of the form:

```js
for (let i = 0; i < elements.length; ++i) {
    const i = elements[i];
   ...
}
```

with:

```js
for (const element of elements) {
    ...
}
```

Mix of a horrible regex based find/replace and manual touch ups
上级 dc261e04
......@@ -139,8 +139,7 @@ export function createESMSourcesAndResources2(options: IOptions2): void {
};
const allFiles = walkDirRecursive(SRC_FOLDER);
for (let i = 0; i < allFiles.length; i++) {
const file = allFiles[i];
for (const file of allFiles) {
if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) {
continue;
......@@ -242,8 +241,7 @@ export function createESMSourcesAndResources2(options: IOptions2): void {
function toggleComments(fileContents: string): string {
let lines = fileContents.split(/\r\n|\r|\n/);
let mode = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
for (const line of lines) {
if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) {
......
......@@ -61,8 +61,7 @@ export interface ITreeShakingResult {
}
function printDiagnostics(diagnostics: ReadonlyArray<ts.Diagnostic>): void {
for (let i = 0; i < diagnostics.length; i++) {
const diag = diagnostics[i];
for (const diag of diagnostics) {
let result = '';
if (diag.file) {
result += `${diag.file.fileName}: `;
......@@ -465,8 +464,7 @@ function markNodes(languageService: ts.LanguageService, options: ITreeShakingOpt
}
if (black_queue.length === 0) {
for (let i = 0; i < gray_queue.length; i++) {
const node = gray_queue[i];
for (const node of gray_queue) {
const nodeParent = node.parent;
if ((ts.isClassDeclaration(nodeParent) || ts.isInterfaceDeclaration(nodeParent)) && nodeOrChildIsBlack(nodeParent)) {
gray_queue.splice(i, 1);
......@@ -610,8 +608,7 @@ function generateResult(languageService: ts.LanguageService, shakeLevel: ShakeLe
}
} else {
let survivingImports: string[] = [];
for (let i = 0; i < node.importClause.namedBindings.elements.length; i++) {
const importNode = node.importClause.namedBindings.elements[i];
for (const importNode of node.importClause.namedBindings.elements) {
if (getColor(importNode) === NodeColor.Black) {
survivingImports.push(importNode.getFullText(sourceFile));
}
......
......@@ -148,8 +148,7 @@ class NoUnexternalizedStringsRuleWalker extends Lint.RuleWalker {
if (isStringLiteral(keyArg)) {
this.recordKey(keyArg, this.messageIndex && callInfo ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
} else if (isObjectLiteral(keyArg)) {
for (let i = 0; i < keyArg.properties.length; i++) {
const property = keyArg.properties[i];
for (const property of keyArg.properties) {
if (isPropertyAssignment(property)) {
const name = property.name.getText();
if (name === 'key') {
......
......@@ -105,9 +105,9 @@ function doWrapping(individualLines: boolean, args: any) {
function revertPreview(): Thenable<any> {
return editor.edit(builder => {
for (let i = 0; i < rangesToReplace.length; i++) {
builder.replace(rangesToReplace[i].previewRange, rangesToReplace[i].originalContent);
rangesToReplace[i].previewRange = rangesToReplace[i].originalRange;
for (const rangeToReplace of rangesToReplace) {
builder.replace(rangeToReplace.previewRange, rangeToReplace.originalContent);
rangeToReplace.previewRange = rangeToReplace.originalRange;
}
}, { undoStopBefore: false, undoStopAfter: false });
}
......
......@@ -29,9 +29,9 @@ function updateCSSNode(editor: TextEditor, property: Property): Thenable<boolean
let currentPrefix = '';
// Find vendor prefix of given property node
for (let i = 0; i < vendorPrefixes.length; i++) {
if (property.name.startsWith(vendorPrefixes[i])) {
currentPrefix = vendorPrefixes[i];
for (const prefix of vendorPrefixes) {
if (property.name.startsWith(prefix)) {
currentPrefix = prefix;
break;
}
}
......
......@@ -119,9 +119,7 @@ function getNextAttribute(selectionStart: vscode.Position, selectionEnd: vscode.
return;
}
for (let i = 0; i < node.attributes.length; i++) {
let attr = node.attributes[i];
for (const attr of node.attributes) {
if (selectionEnd.isBefore(attr.start)) {
// select full attr
return new vscode.Selection(attr.start, attr.end);
......
......@@ -39,8 +39,7 @@ export function toggleComment(): Thenable<boolean> | undefined {
return result === 0 ? arr1[0].range.start.character - arr2[0].range.start.character : result;
});
let lastEditPosition = new vscode.Position(0, 0);
for (let i = 0; i < allEdits.length; i++) {
const edits = allEdits[i];
for (const edits of allEdits) {
if (edits[0].range.end.isAfterOrEqual(lastEditPosition)) {
edits.forEach(x => {
editBuilder.replace(x.range, x.newText);
......@@ -151,8 +150,8 @@ function toggleCommentStylesheet(selection: vscode.Selection, rootNode: Styleshe
}
function adjustStartNodeCss(node: Node | null, pos: vscode.Position, rootNode: Stylesheet): vscode.Position {
for (let i = 0; i < rootNode.comments.length; i++) {
let commentRange = new vscode.Range(rootNode.comments[i].start, rootNode.comments[i].end);
for (const comment of rootNode.comments) {
let commentRange = new vscode.Range(comment.start, comment.end);
if (commentRange.contains(pos)) {
return pos;
}
......@@ -184,8 +183,8 @@ function adjustStartNodeCss(node: Node | null, pos: vscode.Position, rootNode: S
}
function adjustEndNodeCss(node: Node | null, pos: vscode.Position, rootNode: Stylesheet): vscode.Position {
for (let i = 0; i < rootNode.comments.length; i++) {
let commentRange = new vscode.Range(rootNode.comments[i].start, rootNode.comments[i].end);
for (const comment of rootNode.comments) {
let commentRange = new vscode.Range(comment.start, comment.end);
if (commentRange.contains(pos)) {
return pos;
}
......
......@@ -139,9 +139,9 @@ function pathToSuggestion(p: string, valueBeforeCursor: string, fullValue: strin
}
function resolveWorkspaceRoot(activeDoc: TextDocument, workspaceFolders: WorkspaceFolder[]): string | undefined {
for (let i = 0; i < workspaceFolders.length; i++) {
if (startsWith(activeDoc.uri, workspaceFolders[i].uri)) {
return path.resolve(URI.parse(workspaceFolders[i].uri).fsPath);
for (const folder of workspaceFolders) {
if (startsWith(activeDoc.uri, folder.uri)) {
return path.resolve(URI.parse(folder.uri).fsPath);
}
}
return undefined;
......
......@@ -237,9 +237,9 @@ export default class CommandHandler implements vscode.Disposable {
return null;
}
for (let i = 0; i < conflicts.length; i++) {
if (conflicts[i].range.contains(editor.selection.active)) {
return conflicts[i];
for (const conflict of conflicts) {
if (conflict.range.contains(editor.selection.active)) {
return conflict;
}
}
......
......@@ -70,8 +70,7 @@ function getPrePostScripts(scripts: any): Set<string> {
'pretest', 'postest', 'prepublishOnly'
]);
let keys = Object.keys(scripts);
for (let i = 0; i < keys.length; i++) {
const script = keys[i];
for (const script of keys) {
const prepost = ['pre' + script, 'post' + script];
prepost.forEach(each => {
if (scripts[each] !== undefined) {
......@@ -96,8 +95,7 @@ export async function hasNpmScripts(): Promise<boolean> {
return false;
}
try {
for (let i = 0; i < folders.length; i++) {
let folder = folders[i];
for (const folder of folders) {
if (isAutoDetectionEnabled(folder)) {
let relativePattern = new RelativePattern(folder, '**/package.json');
let paths = await workspace.findFiles(relativePattern, '**/node_modules/**');
......@@ -123,13 +121,11 @@ async function detectNpmScripts(): Promise<Task[]> {
return emptyTasks;
}
try {
for (let i = 0; i < folders.length; i++) {
let folder = folders[i];
for (const folder of folders) {
if (isAutoDetectionEnabled(folder)) {
let relativePattern = new RelativePattern(folder, '**/package.json');
let paths = await workspace.findFiles(relativePattern, '**/node_modules/**');
for (let j = 0; j < paths.length; j++) {
let path = paths[j];
for (const path of paths) {
if (!isExcluded(folder, path) && !visitedPackageJsonFiles.has(path.fsPath)) {
let tasks = await provideNpmScriptsForFolder(path);
visitedPackageJsonFiles.add(path.fsPath);
......
......@@ -13,8 +13,7 @@ import { ResourceMap } from '../utils/resourceMap';
function objsAreEqual<T>(a: T, b: T): boolean {
let keys = Object.keys(a);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
for (const key of keys) {
if ((a as any)[key] !== (b as any)[key]) {
return false;
}
......
......@@ -136,8 +136,7 @@ suite('window namespace tests', () => {
}).then(() => {
assert.equal(actualEvents.length, 2);
for (let i = 0; i < actualEvents.length; i++) {
const event = actualEvents[i];
for (const event of actualEvents) {
assert.equal(event.viewColumn, event.textEditor.viewColumn);
}
......
......@@ -92,12 +92,12 @@ export class GlobalMouseMoveMonitor<R> extends Disposable {
this.onStopCallback = onStopCallback;
let windowChain = IframeUtils.getSameOriginWindowChain();
for (let i = 0; i < windowChain.length; i++) {
this.hooks.push(dom.addDisposableThrottledListener(windowChain[i].window.document, 'mousemove',
for (const element of windowChain) {
this.hooks.push(dom.addDisposableThrottledListener(element.window.document, 'mousemove',
(data: R) => this.mouseMoveCallback!(data),
(lastEvent: R, currentEvent) => this.mouseMoveEventMerger!(lastEvent, currentEvent as MouseEvent)
));
this.hooks.push(dom.addDisposableListener(windowChain[i].window.document, 'mouseup', (e: MouseEvent) => this.stopMonitoring(true)));
this.hooks.push(dom.addDisposableListener(element.window.document, 'mouseup', (e: MouseEvent) => this.stopMonitoring(true)));
}
if (IframeUtils.hasDifferentOriginAncestor()) {
......
......@@ -111,8 +111,7 @@ export class IframeUtils {
let windowChain = this.getSameOriginWindowChain();
for (let i = 0; i < windowChain.length; i++) {
let windowChainEl = windowChain[i];
for (const windowChainEl of windowChain) {
if (windowChainEl.window === ancestorWindow) {
break;
......
......@@ -802,8 +802,7 @@ export class GridView implements IDisposable {
const children: GridNode[] = [];
let offset = 0;
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
for (const child of node.children) {
const childOrientation = orthogonal(orientation);
const childBox: Box = orientation === Orientation.HORIZONTAL
? { top: box.top, left: box.left + offset, width: child.width, height: box.height }
......
......@@ -58,12 +58,10 @@ export class HighlightedLabel implements IDisposable {
private render() {
dom.clearNode(this.domNode);
let htmlContent: string[] = [],
highlight: IHighlight,
pos = 0;
let htmlContent: string[] = [];
let pos = 0;
for (let i = 0; i < this.highlights.length; i++) {
highlight = this.highlights[i];
for (const highlight of this.highlights) {
if (highlight.end === highlight.start) {
continue;
}
......
......@@ -70,8 +70,7 @@ class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData>
splice(start: number, deleteCount: number, insertCount: number): void {
const rendered: IRenderedContainer[] = [];
for (let i = 0; i < this.renderedElements.length; i++) {
const renderedElement = this.renderedElements[i];
for (const renderedElement of this.renderedElements) {
if (renderedElement.index < start) {
rendered.push(renderedElement);
......
......@@ -30,7 +30,7 @@ function doParseOcticons(text: string, firstOcticonIndex: number): IParsedOctico
if (chars) {
textWithoutOcticons += chars;
for (let i = 0; i < chars.length; i++) {
for (const _ of chars) {
octiconOffsets.push(octiconsOffset); // make sure to fill in octicon offsets
}
}
......@@ -115,10 +115,10 @@ export function matchesFuzzyOcticonAware(query: string, target: IParsedOcticons,
// Map matches back to offsets with octicons and trimming
if (matches) {
for (let i = 0; i < matches.length; i++) {
const octiconOffset = octiconOffsets[matches[i].start + leadingWhitespaceOffset] /* octicon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */;
matches[i].start += octiconOffset;
matches[i].end += octiconOffset;
for (const match of matches) {
const octiconOffset = octiconOffsets[match.start + leadingWhitespaceOffset] /* octicon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */;
match.start += octiconOffset;
match.end += octiconOffset;
}
}
......
......@@ -393,8 +393,7 @@ export function resolveTerminalEncoding(verbose?: boolean): Promise<string> {
exec('chcp', (err, stdout, stderr) => {
if (stdout) {
const windowsTerminalEncodingKeys = Object.keys(windowsTerminalEncodings);
for (let i = 0; i < windowsTerminalEncodingKeys.length; i++) {
const key = windowsTerminalEncodingKeys[i];
for (const key of windowsTerminalEncodingKeys) {
if (stdout.indexOf(key) >= 0) {
return resolve(windowsTerminalEncodings[key]);
}
......
......@@ -675,8 +675,7 @@ export class QuickOpenWidget extends Disposable implements IModelProvider {
let caseInsensitiveMatch: any;
const prefix = autoFocus.autoFocusPrefixMatch;
const lowerCasePrefix = prefix.toLowerCase();
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
for (const entry of entries) {
const label = input.dataSource.getLabel(entry);
if (!caseSensitiveMatch && label.indexOf(prefix) === 0) {
......
......@@ -43,8 +43,7 @@ function findWindowOnFilePath<W extends ISimpleWindow>(windows: W[], fileUri: UR
// First check for windows with workspaces that have a parent folder of the provided path opened
const workspaceWindows = windows.filter(window => !!window.openedWorkspace);
for (let i = 0; i < workspaceWindows.length; i++) {
const window = workspaceWindows[i];
for (const window of workspaceWindows) {
const resolvedWorkspace = workspaceResolver(window.openedWorkspace!);
if (resolvedWorkspace && resolvedWorkspace.folders.some(folder => isEqualOrParent(fileUri, folder.uri))) {
return window;
......
......@@ -74,8 +74,7 @@ export abstract class AbstractCodeEditorService extends Disposable implements IC
let editorWithWidgetFocus: ICodeEditor | null = null;
let editors = this.listCodeEditors();
for (let i = 0; i < editors.length; i++) {
let editor = editors[i];
for (const editor of editors) {
if (editor.hasTextFocus()) {
// bingo!
......
......@@ -639,8 +639,7 @@ export class ViewLines extends ViewPart implements IVisibleLinesHost<ViewLine>,
};
}
for (let i = 0; i < visibleRanges.length; i++) {
let visibleRange = visibleRanges[i];
for (const visibleRange of visibleRanges) {
if (visibleRange.left < boxStartX) {
boxStartX = visibleRange.left;
}
......
......@@ -675,8 +675,7 @@ class CommandExecutor {
for (let i = 0; i < ctx.selectionsBefore.length; i++) {
groupedInverseEditOperations[i] = [];
}
for (let i = 0; i < inverseEditOperations.length; i++) {
const op = inverseEditOperations[i];
for (const op of inverseEditOperations) {
if (!op.identifier) {
// perhaps auto whitespace trim edits
continue;
......
......@@ -254,8 +254,7 @@ class PieceTreeSearchCache {
if (hasInvalidVal) {
let newArr: CacheEntry[] = [];
for (let i = 0; i < tmp.length; i++) {
const entry = tmp[i];
for (const entry of tmp) {
if (entry !== null) {
newArr.push(entry);
}
......
......@@ -16,11 +16,11 @@ export const USUAL_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?';
*/
function createWordRegExp(allowInWords: string = ''): RegExp {
let source = '(-?\\d*\\.\\d\\w*)|([^';
for (let i = 0; i < USUAL_WORD_SEPARATORS.length; i++) {
if (allowInWords.indexOf(USUAL_WORD_SEPARATORS[i]) >= 0) {
for (const sep of USUAL_WORD_SEPARATORS) {
if (allowInWords.indexOf(sep) >= 0) {
continue;
}
source += '\\' + USUAL_WORD_SEPARATORS[i];
source += '\\' + sep;
}
source += '\\s]+)';
return new RegExp(source, 'g');
......
......@@ -119,8 +119,7 @@ export class LanguageFeatureRegistry<T> {
this._updateScores(model);
for (let from = 0; from < this._entries.length; from++) {
let entry = this._entries[from];
for (const entry of this._entries) {
if (entry._score > 0) {
callback(entry);
}
......
......@@ -238,8 +238,7 @@ class EditorModelManager extends Disposable {
}
public esureSyncedResources(resources: URI[]): void {
for (let i = 0; i < resources.length; i++) {
let resource = resources[i];
for (const resource of resources) {
let resourceStr = resource.toString();
if (!this._syncedModels[resourceStr]) {
......
......@@ -76,8 +76,8 @@ export class LanguagesRegistry extends Disposable {
_registerLanguages(desc: ILanguageExtensionPoint[]): void {
for (let i = 0; i < desc.length; i++) {
this._registerLanguage(desc[i]);
for (const d of desc) {
this._registerLanguage(d);
}
// Rebuild fast path maps
......@@ -201,8 +201,7 @@ export class LanguagesRegistry extends Disposable {
}
if (langAliases !== null) {
for (let i = 0; i < langAliases.length; i++) {
const langAlias = langAliases[i];
for (const langAlias of langAliases) {
if (!langAlias || langAlias.length === 0) {
continue;
}
......
......@@ -286,9 +286,9 @@ export class SplitLinesCollection implements IViewModelLinesCollection {
// END TODO@Martin: Please stop calling this method on each model change!
let newDecorations: IModelDeltaDecoration[] = [];
for (let i = 0; i < newRanges.length; i++) {
for (const newRange of newRanges) {
newDecorations.push({
range: newRanges[i],
range: newRange,
options: ModelDecorationOptions.EMPTY
});
}
......@@ -403,8 +403,8 @@ export class SplitLinesCollection implements IViewModelLinesCollection {
let hiddenAreas = this.getHiddenAreas();
let isInHiddenArea = false;
let testPosition = new Position(fromLineNumber, 1);
for (let i = 0; i < hiddenAreas.length; i++) {
if (hiddenAreas[i].containsPosition(testPosition)) {
for (const hiddenArea of hiddenAreas) {
if (hiddenArea.containsPosition(testPosition)) {
isInHiddenArea = true;
break;
}
......
......@@ -28,8 +28,8 @@ class MoveCaretAction extends EditorAction {
let commands: ICommand[] = [];
let selections = editor.getSelections();
for (let i = 0; i < selections.length; i++) {
commands.push(new MoveCaretCommand(selections[i], this.left));
for (const selection of selections) {
commands.push(new MoveCaretCommand(selection, this.left));
}
editor.pushUndoStop();
......
......@@ -113,8 +113,8 @@ export class BlockCommentCommand implements editorCommon.ICommand {
this._usedEndToken = ops.length === 1 ? endToken : null;
}
for (let i = 0; i < ops.length; i++) {
builder.addTrackedEditOperation(ops[i].range, ops[i].text);
for (const op of ops) {
builder.addTrackedEditOperation(op.range, op.text);
}
}
......
......@@ -70,8 +70,7 @@ export class DefinitionAction extends EditorAction {
// * find reference at the current pos
let idxOfCurrent = -1;
const result: DefinitionLink[] = [];
for (let i = 0; i < references.length; i++) {
let reference = references[i];
for (const reference of references) {
if (!reference || !reference.range) {
continue;
}
......
......@@ -361,8 +361,7 @@ class LinkDetector implements editorCommon.IEditorContribution {
endColumn: position.column
}, 0, true);
for (let i = 0; i < decorations.length; i++) {
const decoration = decorations[i];
for (const decoration of decorations) {
const currentOccurrence = this.currentOccurrences[decoration.id];
if (currentOccurrence) {
return currentOccurrence;
......
......@@ -122,8 +122,7 @@ export class QuickCommandAction extends BaseEditorQuickOpenAction {
let actions: IEditorAction[] = editor.getSupportedActions();
let entries: EditorActionCommandEntry[] = [];
for (let i = 0; i < actions.length; i++) {
let action = actions[i];
for (const action of actions) {
let keybinding = keybindingService.lookupKeybinding(action.id);
......
......@@ -181,8 +181,7 @@ export class QuickOutlineAction extends BaseEditorQuickOpenAction {
normalizedSearchValue = normalizedSearchValue.substr(SCOPE_PREFIX.length);
}
for (let i = 0; i < flattened.length; i++) {
let element = flattened[i];
for (const element of flattened) {
let label = strings.trim(element.name);
// Check for meatch
......
......@@ -838,8 +838,7 @@ function findBracket(lexer: monarchCommon.ILexer, matched: string) {
matched = monarchCommon.fixCase(lexer, matched);
let brackets = lexer.brackets;
for (let i = 0; i < brackets.length; i++) {
let bracket = brackets[i];
for (const bracket of brackets) {
if (bracket.open === matched) {
return { token: bracket.token, bracketType: monarchCommon.MonarchBracket.Open };
}
......
......@@ -52,8 +52,7 @@ export class BenchmarkSuite {
run() {
console.log(`|${this.name}\t|line buffer\t|piece table\t|edcore\t`);
console.log('|---|---|---|---|');
for (let i = 0; i < this.benchmarks.length; i++) {
let benchmark = this.benchmarks[i];
for (const benchmark of this.benchmarks) {
let columns: string[] = [benchmark.name];
[new PieceTreeTextBufferBuilder()].forEach((builder: ITextBufferBuilder) => {
let timeDiffTotal = 0.0;
......
......@@ -53,8 +53,8 @@ for (let fileSize of fileSizes) {
},
fn: (textBuffer) => {
// for line model, this loop doesn't reflect the real situation.
for (let k = 0; k < edits.length; k++) {
textBuffer.applyEdits([edits[k]], false);
for (const edit of edits) {
textBuffer.applyEdits([edit], false);
}
}
});
......@@ -66,8 +66,8 @@ for (let fileSize of fileSizes) {
return textBufferBuilder.finish();
},
preCycle: (textBuffer) => {
for (let k = 0; k < edits.length; k++) {
textBuffer.applyEdits([edits[k]], false);
for (const edit of edits) {
textBuffer.applyEdits([edit], false);
}
return textBuffer;
},
......@@ -90,8 +90,8 @@ for (let fileSize of fileSizes) {
return textBufferBuilder.finish();
},
preCycle: (textBuffer) => {
for (let k = 0; k < edits.length; k++) {
textBuffer.applyEdits([edits[k]], false);
for (const edit of edits) {
textBuffer.applyEdits([edit], false);
}
return textBuffer;
},
......@@ -120,8 +120,8 @@ for (let fileSize of fileSizes) {
return textBufferBuilder.finish();
},
preCycle: (textBuffer) => {
for (let k = 0; k < edits.length; k++) {
textBuffer.applyEdits([edits[k]], false);
for (const edit of edits) {
textBuffer.applyEdits([edit], false);
}
return textBuffer;
},
......
......@@ -653,8 +653,7 @@ suite('viewLineRenderer.renderLine', () => {
for (let partIndex = 0; partIndex < expectedCharPartOffsets.length; partIndex++) {
const part = expectedCharPartOffsets[partIndex];
for (let i = 0; i < part.length; i++) {
const charIndex = part[i];
for (const charIndex of part) {
expectedCharAbsoluteOffset.push(currentPartAbsoluteOffset + charIndex);
}
......
......@@ -386,8 +386,7 @@ export class BackupMainService implements IBackupMainService {
try {
const backupSchemas = await readdir(backupPath);
for (let i = 0; i < backupSchemas.length; i++) {
const backupSchema = backupSchemas[i];
for (const backupSchema of backupSchemas) {
try {
const backupSchemaChildren = await readdir(path.join(backupPath, backupSchema));
if (backupSchemaChildren.length > 0) {
......
......@@ -227,11 +227,11 @@ function doRemoveFromValueTree(valueTree: any, segments: string[]): void {
export function getConfigurationValue<T>(config: any, settingPath: string, defaultValue?: T): T {
function accessSetting(config: any, path: string[]): any {
let current = config;
for (let i = 0; i < path.length; i++) {
for (const component of path) {
if (typeof current !== 'object' || current === null) {
return undefined;
}
current = current[path[i]];
current = current[component];
}
return <T>current;
}
......
......@@ -81,8 +81,7 @@ export class ContributableActionProvider implements IActionProvider {
const context = this.toContext(tree, element);
const contributors = this.registry.getActionBarContributors(Scope.VIEWER);
for (let i = 0; i < contributors.length; i++) {
const contributor = contributors[i];
for (const contributor of contributors) {
if (contributor.hasActions(context)) {
return true;
}
......@@ -97,8 +96,7 @@ export class ContributableActionProvider implements IActionProvider {
// Collect Actions
const contributors = this.registry.getActionBarContributors(Scope.VIEWER);
for (let i = 0; i < contributors.length; i++) {
const contributor = contributors[i];
for (const contributor of contributors) {
if (contributor.hasActions(context)) {
actions.push(...contributor.getActions(context));
}
......@@ -111,8 +109,7 @@ export class ContributableActionProvider implements IActionProvider {
const context = this.toContext(tree, element);
const contributors = this.registry.getActionBarContributors(Scope.VIEWER);
for (let i = 0; i < contributors.length; i++) {
const contributor = contributors[i];
for (const contributor of contributors) {
if (contributor.hasSecondaryActions(context)) {
return true;
}
......@@ -127,8 +124,7 @@ export class ContributableActionProvider implements IActionProvider {
// Collect Actions
const contributors = this.registry.getActionBarContributors(Scope.VIEWER);
for (let i = 0; i < contributors.length; i++) {
const contributor = contributors[i];
for (const contributor of contributors) {
if (contributor.hasSecondaryActions(context)) {
actions.push(...contributor.getSecondaryActions(context));
}
......@@ -300,8 +296,7 @@ class ActionBarRegistry implements IActionBarRegistry {
getActionItemForContext(scope: string, context: any, action: Action): BaseActionItem {
const contributors = this.getContributors(scope);
for (let i = 0; i < contributors.length; i++) {
const contributor = contributors[i];
for (const contributor of contributors) {
const item = contributor.getActionItem(context, action);
if (item) {
return item;
......
......@@ -390,8 +390,7 @@ export function fillResourceDataTransfers(accessor: ServicesAccessor, resources:
// Try to find editor view state from the visible editors that match given resource
let viewState: IEditorViewState;
const textEditorWidgets = editorService.visibleTextEditorWidgets;
for (let i = 0; i < textEditorWidgets.length; i++) {
const textEditorWidget = textEditorWidgets[i];
for (const textEditorWidget of textEditorWidgets) {
if (isCodeEditor(textEditorWidget)) {
const model = textEditorWidget.getModel();
if (model && model.uri && model.uri.toString() === file.resource.toString()) {
......
......@@ -107,8 +107,7 @@ class EditorRegistry implements IEditorRegistry {
const findEditorDescriptors = (input: EditorInput, byInstanceOf?: boolean): EditorDescriptor[] => {
const matchingDescriptors: EditorDescriptor[] = [];
for (let i = 0; i < this.editors.length; i++) {
const editor = this.editors[i];
for (const editor of this.editors) {
const inputDescriptors = <SyncDescriptor<EditorInput>[]>editor[INPUT_DESCRIPTORS_PROPERTY];
for (let j = 0; j < inputDescriptors.length; j++) {
const inputClass = inputDescriptors[j].ctor;
......@@ -156,8 +155,7 @@ class EditorRegistry implements IEditorRegistry {
}
getEditorById(editorId: string): EditorDescriptor {
for (let i = 0; i < this.editors.length; i++) {
const editor = this.editors[i];
for (const editor of this.editors) {
if (editor.getId() === editorId) {
return editor;
}
......@@ -176,8 +174,7 @@ class EditorRegistry implements IEditorRegistry {
getEditorInputs(): any[] {
const inputClasses: any[] = [];
for (let i = 0; i < this.editors.length; i++) {
const editor = this.editors[i];
for (const editor of this.editors) {
const editorInputDescriptors = <SyncDescriptor<EditorInput>[]>editor[INPUT_DESCRIPTORS_PROPERTY];
inputClasses.push(...editorInputDescriptors.map(descriptor => descriptor.ctor));
}
......
......@@ -512,9 +512,7 @@ export class EditorDropTarget extends Themable {
private findTargetGroupView(child: HTMLElement): IEditorGroupView {
const groups = this.accessor.groups;
for (let i = 0; i < groups.length; i++) {
const groupView = groups[i];
for (const groupView of groups) {
if (isAncestor(child, groupView.element)) {
return groupView;
}
......
......@@ -143,8 +143,7 @@ class NotificationMessageRenderer {
// Message has links
else {
let index = 0;
for (let i = 0; i < message.links.length; i++) {
const link = message.links[i];
for (const link of message.links) {
const textBefore = message.value.substring(index, link.offset);
if (textBefore) {
......
......@@ -490,8 +490,7 @@ export class QuickOpenController extends Component implements IQuickOpenService
// Remove results already showing by checking for a "resource" property
const mapEntryToResource = this.mapEntriesToResource(quickOpenModel);
const additionalHandlerResults: QuickOpenEntry[] = [];
for (let i = 0; i < handlerResults.length; i++) {
const result = handlerResults[i];
for (const result of handlerResults) {
const resource = result.getResource();
if (!result.mergeWithEditorHistory() || !resource || !mapEntryToResource[resource.toString()]) {
......
......@@ -67,8 +67,7 @@ export class StatusbarPart extends Part implements IStatusbarService {
const container = this.statusItemsContainer;
const neighbours = this.getEntries(alignment);
let inserted = false;
for (let i = 0; i < neighbours.length; i++) {
const neighbour = neighbours[i];
for (const neighbour of neighbours) {
const nPriority = Number(neighbour.getAttribute(StatusbarPart.PRIORITY_PROP));
if (
alignment === StatusbarAlignment.LEFT && nPriority < priority ||
......
......@@ -384,8 +384,7 @@ export class ContributableViewsModel extends Disposable {
}
}
for (let i = 0; i < splice.toInsert.length; i++) {
const viewDescriptor = splice.toInsert[i];
for (const viewDescriptor of splice.toInsert) {
const state = this.viewStates.get(viewDescriptor.id);
if (state.visible) {
......
......@@ -148,8 +148,7 @@ export class EditorGroup extends Disposable {
return null; // fast check for resource opened or not
}
for (let i = 0; i < this.editors.length; i++) {
const editor = this.editors[i];
for (const editor of this.editors) {
const editorResource = toResource(editor, { supportSideBySide: true });
if (editorResource && editorResource.toString() === resource.toString()) {
return editor;
......
......@@ -126,8 +126,7 @@ export class NotificationsModel extends Disposable implements INotificationsMode
}
private findNotification(item: INotificationViewItem): INotificationViewItem | undefined {
for (let i = 0; i < this._notifications.length; i++) {
const notification = this._notifications[i];
for (const notification of this._notifications) {
if (notification.equals(item)) {
return notification;
}
......
......@@ -330,8 +330,7 @@ export class ElectronWindow extends Themable {
// Convert into command action multi array
const items: ICommandAction[][] = [];
let group: ICommandAction[] = [];
for (let i = 0; i < actions.length; i++) {
const action = actions[i];
for (const action of actions) {
// Command
if (action instanceof MenuItemAction) {
......
......@@ -72,8 +72,7 @@ export class SelectionClipboard extends Disposable implements IEditorContributio
selections.sort(Range.compareRangesUsingStarts);
let resultLength = 0;
for (let i = 0; i < selections.length; i++) {
let sel = selections[i];
for (const sel of selections) {
if (sel.isEmpty()) {
// Only write if all cursors have selection
return;
......@@ -88,8 +87,7 @@ export class SelectionClipboard extends Disposable implements IEditorContributio
}
let result: string[] = [];
for (let i = 0; i < selections.length; i++) {
let sel = selections[i];
for (const sel of selections) {
result.push(model.getValueInRange(sel, EndOfLinePreference.TextDefined));
}
......
......@@ -118,8 +118,7 @@ class CommentingRangeDecorator {
}
let commentingRangeDecorations: CommentingRangeDecoration[] = [];
for (let i = 0; i < commentInfos.length; i++) {
let info = commentInfos[i];
for (const info of commentInfos) {
info.commentingRanges.forEach(range => {
commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.owner, range, info.reply, this.decorationOptions));
});
......
......@@ -382,10 +382,10 @@ export class ExtensionsListView extends ViewletPanel {
options = assign(options, { text: text.substr(0, 350), source: 'searchText' });
if (!hasUserDefinedSortOrder) {
const searchExperiments = await this.getSearchExperiments();
for (let i = 0; i < searchExperiments.length; i++) {
if (text.toLowerCase() === searchExperiments[i].action.properties['searchText'] && Array.isArray(searchExperiments[i].action.properties['preferredResults'])) {
preferredResults = searchExperiments[i].action.properties['preferredResults'];
options.source += `-experiment-${searchExperiments[i].id}`;
for (const experiment of searchExperiments) {
if (text.toLowerCase() === experiment.action.properties['searchText'] && Array.isArray(experiment.action.properties['preferredResults'])) {
preferredResults = experiment.action.properties['preferredResults'];
options.source += `-experiment-${experiment.id}`;
break;
}
}
......@@ -397,9 +397,9 @@ export class ExtensionsListView extends ViewletPanel {
const pager = await this.extensionsWorkbenchService.queryGallery(options);
let positionToUpdate = 0;
for (let i = 0; i < preferredResults.length; i++) {
for (const preferredResult of preferredResults) {
for (let j = positionToUpdate; j < pager.firstPage.length; j++) {
if (areSameExtensions(pager.firstPage[j].identifier, { id: preferredResults[i] })) {
if (areSameExtensions(pager.firstPage[j].identifier, { id: preferredResult })) {
if (positionToUpdate !== j) {
const preferredExtension = pager.firstPage.splice(j, 1)[0];
pager.firstPage.splice(positionToUpdate, 0, preferredExtension);
......
......@@ -270,8 +270,7 @@ export class FileEditorTracker extends Disposable implements IWorkbenchContribut
private getViewStateFor(resource: URI, group: IEditorGroup): IEditorViewState | undefined {
const editors = this.editorService.visibleControls;
for (let i = 0; i < editors.length; i++) {
const editor = editors[i];
for (const editor of editors) {
if (editor && editor.input && editor.group === group) {
const editorResource = editor.input.getResource();
if (editorResource && resource.toString() === editorResource.toString()) {
......
......@@ -640,9 +640,7 @@ export class ExplorerView extends TreeViewsViewletPanel implements IExplorerView
// Check added: Refresh if added file/folder is not part of resolved root and parent is part of it
const ignoredPaths: { [resource: string]: boolean } = <{ [resource: string]: boolean }>{};
for (let i = 0; i < added.length; i++) {
const change = added[i];
for (const change of added) {
// Find parent
const parent = resources.dirname(change.resource);
......@@ -669,9 +667,7 @@ export class ExplorerView extends TreeViewsViewletPanel implements IExplorerView
if (deleted.length) {
// Check deleted: Refresh if deleted file/folder part of resolved root
for (let j = 0; j < deleted.length; j++) {
const del = deleted[j];
for (const del of deleted) {
if (this.model.findClosest(del.resource)) {
return true;
}
......@@ -683,9 +679,7 @@ export class ExplorerView extends TreeViewsViewletPanel implements IExplorerView
const updated = e.getUpdated();
// Check updated: Refresh if updated file/folder part of resolved root
for (let j = 0; j < updated.length; j++) {
const upd = updated[j];
for (const upd of updated) {
if (this.model.findClosest(upd.resource)) {
return true;
}
......
......@@ -57,8 +57,7 @@ CommandsRegistry.registerCommand('_workbench.previewHtml', function (
// Find already opened HTML input if any
if (targetGroup) {
const editors = targetGroup.editors;
for (let i = 0; i < editors.length; i++) {
const editor = editors[i];
for (const editor of editors) {
const editorResource = editor.getResource();
if (editor instanceof HtmlInput && editorResource && editorResource.toString() === resource.toString()) {
input = editor;
......
......@@ -45,8 +45,7 @@ export class OutputLinkComputer {
private getModel(uri: string): IMirrorModel | null {
const models = this.ctx.getMirrorModels();
for (let i = 0; i < models.length; i++) {
const model = models[i];
for (const model of models) {
if (model.uri.toString() === uri) {
return model;
}
......
......@@ -486,8 +486,7 @@ export class CommandsHandler extends QuickOpenHandler {
private editorActionsToEntries(actions: IEditorAction[], searchValue: string): EditorActionCommandEntry[] {
const entries: EditorActionCommandEntry[] = [];
for (let i = 0; i < actions.length; i++) {
const action = actions[i];
for (const action of actions) {
if (action.id === ShowAllCommandsAction.ID) {
continue; // avoid duplicates
}
......
......@@ -175,8 +175,7 @@ export class OpenFileHandler extends QuickOpenHandler {
const results: QuickOpenEntry[] = [];
if (!token.isCancellationRequested) {
for (let i = 0; i < complete.results.length; i++) {
const fileMatch = complete.results[i];
for (const fileMatch of complete.results) {
const label = paths.basename(fileMatch.resource.fsPath);
const description = this.labelService.getUriLabel(resources.dirname(fileMatch.resource), { relative: true });
......
......@@ -171,8 +171,7 @@ export class AbstractProblemCollector implements IDisposable {
if (!candidates) {
continue;
}
for (let i = 0; i < candidates.length; i++) {
let matcher = candidates[i];
for (const matcher of candidates) {
let result = matcher.handle(this.buffer, startIndex);
if (result.match) {
this.captureMatch(result.match);
......@@ -445,8 +444,7 @@ export class WatchingProblemCollector extends AbstractProblemCollector implement
private tryBegin(line: string): boolean {
let result = false;
for (let i = 0; i < this.backgroundPatterns.length; i++) {
let background = this.backgroundPatterns[i];
for (const background of this.backgroundPatterns) {
let matches = background.begin.regexp.exec(line);
if (matches) {
if (this._activeBackgroundMatchers.has(background.key)) {
......@@ -472,8 +470,7 @@ export class WatchingProblemCollector extends AbstractProblemCollector implement
private tryFinish(line: string): boolean {
let result = false;
for (let i = 0; i < this.backgroundPatterns.length; i++) {
let background = this.backgroundPatterns[i];
for (const background of this.backgroundPatterns) {
let matches = background.end.regexp.exec(line);
if (matches) {
if (this._activeBackgroundMatchers.has(background.key)) {
......
......@@ -290,8 +290,7 @@ export abstract class TerminalService implements ITerminalService {
}
private _getTabForInstance(instance: ITerminalInstance): ITerminalTab | null {
for (let i = 0; i < this._terminalTabs.length; i++) {
const tab = this._terminalTabs[i];
for (const tab of this._terminalTabs) {
if (tab.terminalInstances.indexOf(instance) !== -1) {
return tab;
}
......
......@@ -193,16 +193,14 @@ class Snapper {
private _enrichResult(result: IToken[], themesResult: IThemesResult): void {
let index: { [themeName: string]: number; } = {};
let themeNames = Object.keys(themesResult);
for (let t = 0; t < themeNames.length; t++) {
let themeName = themeNames[t];
for (const themeName of themeNames) {
index[themeName] = 0;
}
for (let i = 0, len = result.length; i < len; i++) {
let token = result[i];
for (let t = 0; t < themeNames.length; t++) {
let themeName = themeNames[t];
for (const themeName of themeNames) {
let themedToken = themesResult[themeName].tokens[index[themeName]];
themedToken.text = themedToken.text.substr(token.c.length);
......
......@@ -441,8 +441,7 @@ export class ConfigurationEditingService {
// Check for standalone workspace configurations
if (config.key) {
const standaloneConfigurationKeys = Object.keys(WORKSPACE_STANDALONE_CONFIGURATIONS);
for (let i = 0; i < standaloneConfigurationKeys.length; i++) {
const key = standaloneConfigurationKeys[i];
for (const key of standaloneConfigurationKeys) {
const resource = this.getConfigurationFileResource(target, WORKSPACE_STANDALONE_CONFIGURATIONS[key], overrides.resource);
// Check for prefix
......
......@@ -143,8 +143,7 @@ export class EditorService extends Disposable implements EditorServiceImpl {
}
private onGroupWillOpenEditor(group: IEditorGroup, event: IEditorOpeningEvent): void {
for (let i = 0; i < this.openEditorHandlers.length; i++) {
const handler = this.openEditorHandlers[i];
for (const handler of this.openEditorHandlers) {
const result = handler(event.editor, event.options, group);
if (result && result.override) {
event.prevent((() => result.override));
......@@ -270,8 +269,7 @@ export class EditorService extends Disposable implements EditorServiceImpl {
// Respect option to reveal an editor if it is already visible in any group
if (options && options.revealIfVisible) {
for (let i = 0; i < groupsByLastActive.length; i++) {
const group = groupsByLastActive[i];
for (const group of groupsByLastActive) {
if (input.matches(group.activeEditor)) {
targetGroup = group;
break;
......@@ -281,8 +279,7 @@ export class EditorService extends Disposable implements EditorServiceImpl {
// Respect option to reveal an editor if it is open (not necessarily visible)
if ((options && options.revealIfOpened) || this.configurationService.getValue<boolean>('workbench.editor.revealIfOpen')) {
for (let i = 0; i < groupsByLastActive.length; i++) {
const group = groupsByLastActive[i];
for (const group of groupsByLastActive) {
if (group.isOpened(input)) {
targetGroup = group;
break;
......@@ -402,8 +399,7 @@ export class EditorService extends Disposable implements EditorServiceImpl {
}
// For each editor group
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
for (const group of groups) {
// Typed editor
if (editor instanceof EditorInput) {
......
......@@ -120,8 +120,7 @@ export class ResourceEncodings extends Disposable implements IResourceEncodings
private getEncodingOverride(resource: uri): string | null {
if (resource && this.encodingOverride && this.encodingOverride.length) {
for (let i = 0; i < this.encodingOverride.length; i++) {
const override = this.encodingOverride[i];
for (const override of this.encodingOverride) {
// check if the resource is child of encoding override path
if (override.parent && isParent(resource.fsPath, override.parent.fsPath, !isLinux /* ignorecase */)) {
......
......@@ -30,8 +30,7 @@ export function normalize(changes: IRawFileChange[]): IRawFileChange[] {
// Build deltas
let normalizer = new EventNormalizer();
for (let i = 0; i < changes.length; i++) {
let event = changes[i];
for (const event of changes) {
normalizer.processEvent(event);
}
......
......@@ -99,9 +99,7 @@ export class NsfwWatcherService implements IWatcherService {
}
nsfw(request.basePath, events => {
for (let i = 0; i < events.length; i++) {
const e = events[i];
for (const e of events) {
// Logging
if (this._verboseLogging) {
const logPath = e.action === nsfw.actions.RENAMED ? path.join(e.directory, e.oldFile || '') + ' -> ' + e.newFile : path.join(e.directory, e.file || '');
......
......@@ -10,9 +10,9 @@ export function getByName(root: IFileStat, name: string): IFileStat | null {
return null;
}
for (let i = 0; i < root.children.length; i++) {
if (root.children[i].name === name) {
return root.children[i];
for (const child of root.children) {
if (child.name === name) {
return child;
}
}
......
......@@ -904,8 +904,7 @@ export class HistoryService extends Disposable implements IHistoryService {
// Multiple folders: find the last active one
const history = this.getHistory();
for (let i = 0; i < history.length; i++) {
const input = history[i];
for (const input of history) {
if (input instanceof EditorInput) {
continue;
}
......
......@@ -318,8 +318,7 @@ export class SearchService implements IRawSearchService {
// Pattern match on results
const results: IRawFileMatch[] = [];
const normalizedSearchValueLowercase = strings.stripWildcards(searchValue).toLowerCase();
for (let i = 0; i < cachedEntries.length; i++) {
const entry = cachedEntries[i];
for (const entry of cachedEntries) {
// Check if this entry is a match for the search value
if (!strings.fuzzyContains(entry.relativePath, normalizedSearchValueLowercase)) {
......
......@@ -432,8 +432,7 @@ export abstract class TextFileService extends Disposable implements ITextFileSer
// Preflight for untitled to handle cancellation from the dialog
const targetsForUntitled: URI[] = [];
for (let i = 0; i < untitledResources.length; i++) {
const untitled = untitledResources[i];
for (const untitled of untitledResources) {
if (this.untitledEditorService.exists(untitled)) {
let targetUri: URI;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册