perf: replace String and Array indexOf method calls with includes method call (#55482)

This commit is contained in:
Sampo Kivistö 2023-08-25 21:27:55 +03:00 committed by GitHub
parent c3c5abb3a7
commit ec2bd4e252
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 98 additions and 124 deletions

View File

@ -71,7 +71,7 @@ async function checkSourceFiles() {
let count = 0;
console.log("== List of errors not used in source ==");
for (const errName of errorNames) {
if (allSrc.indexOf(errName) < 0) {
if (!allSrc.includes(errName)) {
console.log(errName);
count++;
}

View File

@ -157,7 +157,7 @@ module.exports = createRule({
}
}
const hasNewLine = sourceCodeText.slice(commentRangeEnd, argRangeStart).indexOf("\n") >= 0;
const hasNewLine = sourceCodeText.slice(commentRangeEnd, argRangeStart).includes("\n");
if (argRangeStart !== commentRangeEnd + 1 && !hasNewLine) {
// TODO(jakebailey): range should be whitespace
context.report({

View File

@ -88,7 +88,7 @@ async function main() {
const mergeTree = runSequence([
["git", ["merge-tree", mergeBase.trim(), branch, "experimental"]],
]);
if (mergeTree.indexOf(`===${"="}===`) >= 0) { // 7 equals is the center of the merge conflict marker
if (mergeTree.includes(`===${"="}===`)) { // 7 equals is the center of the merge conflict marker
throw new Error(`Merge conflict detected involving PR ${branch} with other experiment`);
}
// Merge (always producing a merge commit)

View File

@ -39,7 +39,7 @@ function createCancellationToken(args: string[]): ServerCancellationToken {
// in this case pipe name will be build dynamically as <cancellationPipeName><request_seq>.
if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") {
const namePrefix = cancellationPipeName.slice(0, -1);
if (namePrefix.length === 0 || namePrefix.indexOf("*") >= 0) {
if (namePrefix.length === 0 || namePrefix.includes("*")) {
throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'.");
}
let perRequestPipeName: string | undefined;

View File

@ -964,7 +964,6 @@ import {
SpreadElement,
startsWith,
Statement,
stringContains,
StringLiteral,
StringLiteralLike,
StringLiteralType,
@ -7908,14 +7907,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (!specifier) {
specifier = getSpecifierForModuleSymbol(chain[0], context);
}
if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic && specifier.indexOf("/node_modules/") >= 0) {
if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic && specifier.includes("/node_modules/")) {
const oldSpecifier = specifier;
if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node16 || getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeNext) {
// We might be able to write a portable import type using a mode override; try specifier generation again, but with a different mode set
const swappedMode = contextFile?.impliedNodeFormat === ModuleKind.ESNext ? ModuleKind.CommonJS : ModuleKind.ESNext;
specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode);
if (specifier.indexOf("/node_modules/") >= 0) {
if (specifier.includes("/node_modules/")) {
// Still unreachable :(
specifier = oldSpecifier;
}
@ -8661,7 +8660,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (group.length > 1) {
// remove group members from statements and then merge group members and add back to statements
statements = [
...filter(statements, s => group.indexOf(s as ExportDeclaration) === -1),
...filter(statements, s => !group.includes(s as ExportDeclaration)),
factory.createExportDeclaration(
/*modifiers*/ undefined,
/*isTypeOnly*/ false,
@ -24250,7 +24249,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const originalKeywordKind = identifierToKeywordKind(param.name);
if (
(isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) &&
param.parent.parameters.indexOf(param) > -1 &&
param.parent.parameters.includes(param) &&
(resolveName(param, param.name.escapedText, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, param.name.escapedText, /*isUse*/ true) ||
originalKeywordKind && isTypeNodeKind(originalKeywordKind))
) {
@ -30962,7 +30961,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
function isHyphenatedJsxName(name: string | __String) {
return stringContains(name as string, "-");
return (name as string).includes("-");
}
/**
@ -49648,7 +49647,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// Realism (size) checking
// We should test against `getTextOfNode(node)` rather than `node.text`, because `node.text` for large numeric literals can contain "."
// e.g. `node.text` for numeric literal `1100000000000000000000` is `1.1e21`.
const isFractional = getTextOfNode(node).indexOf(".") !== -1;
const isFractional = getTextOfNode(node).includes(".");
const isScientific = node.numericLiteralFlags & TokenFlags.Scientific;
// Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint

View File

@ -104,7 +104,6 @@ import {
returnTrue,
ScriptTarget,
startsWith,
stringContains,
StringLiteral,
SyntaxKind,
sys,
@ -1710,7 +1709,7 @@ export function parseListTypeOption(opt: CommandLineOptionOfListType, value = ""
if (startsWith(value, "-")) {
return undefined;
}
if (opt.type === "listOrElement" && !stringContains(value, ",")) {
if (opt.type === "listOrElement" && !value.includes(",")) {
return validateJsonOptionValue(opt, value, errors);
}
if (value === "") {
@ -3078,7 +3077,7 @@ function parseConfig(
basePath = normalizeSlashes(basePath);
const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath);
if (resolutionStack.indexOf(resolvedPath) >= 0) {
if (resolutionStack.includes(resolvedPath)) {
errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> ")));
return { raw: json || convertToObject(sourceFile!, errors) };
}

View File

@ -2484,11 +2484,6 @@ export function tryRemoveSuffix(str: string, suffix: string): string | undefined
return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
}
/** @internal */
export function stringContains(str: string, substring: string): boolean {
return str.indexOf(substring) !== -1;
}
/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*

View File

@ -407,7 +407,6 @@ import {
SpreadElement,
stableSort,
Statement,
stringContains,
StringLiteral,
supportedJSExtensionsFlat,
SwitchStatement,
@ -3065,9 +3064,9 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
// If the number will be printed verbatim and it doesn't already contain a dot or an exponent indicator, add one
// if the expression doesn't have any comments that will be emitted.
return !(expression.numericLiteralFlags & TokenFlags.WithSpecifier)
&& !stringContains(text, tokenToString(SyntaxKind.DotToken)!)
&& !stringContains(text, String.fromCharCode(CharacterCodes.E))
&& !stringContains(text, String.fromCharCode(CharacterCodes.e));
&& !text.includes(tokenToString(SyntaxKind.DotToken)!)
&& !text.includes(String.fromCharCode(CharacterCodes.E))
&& !text.includes(String.fromCharCode(CharacterCodes.e));
}
else if (isAccessExpression(expression)) {
// check if constant enum value is a non-negative integer

View File

@ -100,7 +100,6 @@ import {
sort,
SourceFile,
startsWith,
stringContains,
supportedDeclarationExtensions,
supportedJSExtensionsFlat,
supportedTSImplementationExtensions,
@ -1808,7 +1807,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
&& features & NodeResolutionFeatures.Exports
&& !isExternalModuleNameRelative(moduleName)
&& !extensionIsOk(Extensions.TypeScript | Extensions.Declaration, result.value.resolved.extension)
&& conditions.indexOf("import") > -1
&& conditions.includes("import")
) {
traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update);
const diagnosticState = {
@ -1849,7 +1848,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
resolved = loadModuleFromSelfNameReference(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
}
if (!resolved) {
if (moduleName.indexOf(":") > -1) {
if (moduleName.includes(":")) {
if (traceEnabled) {
trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions));
}
@ -1944,7 +1943,7 @@ function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string,
export const nodeModulesPathPart = "/node_modules/";
/** @internal */
export function pathContainsNodeModules(path: string): boolean {
return stringContains(path, nodeModulesPathPart);
return path.includes(nodeModulesPathPart);
}
/**
@ -2006,7 +2005,7 @@ function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecor
function loadModuleFromFileNoImplicitExtensions(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined {
const filename = getBaseFileName(candidate);
if (filename.indexOf(".") === -1) {
if (!filename.includes(".")) {
return undefined; // extensionless import, no lookups performed, since we don't support extensionless files
}
let extensionless = removeFileExtension(candidate);
@ -2223,7 +2222,7 @@ function loadEntrypointsFromExportMap(
function loadEntrypointsFromTargetExports(target: unknown): boolean | undefined {
if (typeof target === "string" && startsWith(target, "./")) {
if (target.indexOf("*") >= 0 && state.host.readDirectory) {
if (target.includes("*") && state.host.readDirectory) {
if (target.indexOf("*") !== target.lastIndexOf("*")) {
return false;
}
@ -2243,7 +2242,7 @@ function loadEntrypointsFromExportMap(
}
else {
const partsAfterFirst = getPathComponents(target).slice(2);
if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) {
return false;
}
const resolvedTarget = combinePaths(scope.packageDirectory, target);
@ -2609,11 +2608,11 @@ export function comparePatternKeys(a: string, b: string) {
function loadModuleFromImportsOrExports(extensions: Extensions, state: ModuleResolutionState, cache: ModuleResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined, moduleName: string, lookupTable: object, scope: PackageJsonInfo, isImports: boolean): SearchResult<Resolved> | undefined {
const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports);
if (!endsWith(moduleName, directorySeparator) && moduleName.indexOf("*") === -1 && hasProperty(lookupTable, moduleName)) {
if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) {
const target = (lookupTable as { [idx: string]: unknown; })[moduleName];
return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName);
}
const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike<unknown>), k => k.indexOf("*") !== -1 || endsWith(k, "/")), comparePatternKeys);
const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike<unknown>), k => k.includes("*") || endsWith(k, "/")), comparePatternKeys);
for (const potentialTarget of expandingKeys) {
if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) {
const target = (lookupTable as { [idx: string]: unknown; })[potentialTarget];
@ -2677,7 +2676,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
}
const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target);
const partsAfterFirst = parts.slice(1);
if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
}
@ -2687,7 +2686,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
// TODO: Assert that `resolvedTarget` is actually within the package directory? That's what the spec says.... but I'm not sure we need
// to be in the business of validating everyone's import and export map correctness.
const subpathParts = getPathComponents(subpath);
if (subpathParts.indexOf("..") >= 0 || subpathParts.indexOf(".") >= 0 || subpathParts.indexOf("node_modules") >= 0) {
if (subpathParts.includes("..") || subpathParts.includes(".") || subpathParts.includes("node_modules")) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
}
@ -2706,7 +2705,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
if (!Array.isArray(target)) {
traceIfEnabled(state, Diagnostics.Entering_conditional_exports);
for (const condition of getOwnKeys(target as MapLike<unknown>)) {
if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) {
if (condition === "default" || state.conditions.includes(condition) || isApplicableVersionedTypesKey(state.conditions, condition)) {
traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition);
const subTarget = (target as MapLike<unknown>)[condition];
const result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key);
@ -2772,7 +2771,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
if (
!state.isConfigLookup
&& (state.compilerOptions.declarationDir || state.compilerOptions.outDir)
&& finalPath.indexOf("/node_modules/") === -1
&& !finalPath.includes("/node_modules/")
&& (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)
) {
// So that all means we'll only try these guesses for files outside `node_modules` in a directory where the `package.json` and `tsconfig.json` are siblings.
@ -2876,7 +2875,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
/** @internal */
export function isApplicableVersionedTypesKey(conditions: readonly string[], key: string) {
if (conditions.indexOf("types") === -1) return false; // only apply versioned types conditions if the types condition is applied
if (!conditions.includes("types")) return false; // only apply versioned types conditions if the types condition is applied
if (!startsWith(key, "types@")) return false;
const range = VersionRange.tryParse(key.substring("types@".length));
if (!range) return false;
@ -3099,7 +3098,7 @@ export function getPackageNameFromTypesPackageName(mangledName: string): string
/** @internal */
export function unmangleScopedPackageName(typesPackageName: string): string {
return stringContains(typesPackageName, mangledScopedPackageSeparator) ?
return typesPackageName.includes(mangledScopedPackageSeparator) ?
"@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) :
typesPackageName;
}

View File

@ -101,7 +101,6 @@ import {
SourceFile,
startsWith,
startsWithDirectory,
stringContains,
StringLiteral,
Symbol,
SymbolFlags,
@ -866,7 +865,7 @@ function tryGetModuleNameFromExports(options: CompilerOptions, targetFilePath: s
return forEach(getOwnKeys(exports as MapLike<unknown>), k => {
const subPackageName = getNormalizedAbsolutePath(combinePaths(packageName, k), /*currentDirectory*/ undefined);
const mode = endsWith(k, "/") ? MatchingMode.Directory
: stringContains(k, "*") ? MatchingMode.Pattern
: k.includes("*") ? MatchingMode.Pattern
: MatchingMode.Exact;
return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, (exports as MapLike<unknown>)[k], conditions, mode);
});
@ -874,7 +873,7 @@ function tryGetModuleNameFromExports(options: CompilerOptions, targetFilePath: s
else {
// conditional mapping
for (const key of getOwnKeys(exports as MapLike<unknown>)) {
if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) {
if (key === "default" || conditions.includes(key) || isApplicableVersionedTypesKey(conditions, key)) {
const subTarget = (exports as MapLike<unknown>)[key];
const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode);
if (result) {
@ -1093,7 +1092,7 @@ function processEnding(fileName: string, allowedEndings: readonly ModuleSpecifie
else if (fileExtensionIsOneOf(fileName, [Extension.Dmts, Extension.Mts, Extension.Dcts, Extension.Cts])) {
return noExtension + getJSExtensionForFile(fileName, options);
}
else if (!fileExtensionIsOneOf(fileName, [Extension.Dts]) && fileExtensionIsOneOf(fileName, [Extension.Ts]) && stringContains(fileName, ".d.")) {
else if (!fileExtensionIsOneOf(fileName, [Extension.Dts]) && fileExtensionIsOneOf(fileName, [Extension.Ts]) && fileName.includes(".d.")) {
// `foo.d.json.ts` and the like - remap back to `foo.json`
return tryGetRealFileNameForNonJsDeclarationFileName(fileName)!;
}
@ -1129,7 +1128,7 @@ function processEnding(fileName: string, allowedEndings: readonly ModuleSpecifie
/** @internal */
export function tryGetRealFileNameForNonJsDeclarationFileName(fileName: string) {
const baseName = getBaseFileName(fileName);
if (!endsWith(fileName, Extension.Ts) || !stringContains(baseName, ".d.") || fileExtensionIsOneOf(baseName, [Extension.Dts])) return undefined;
if (!endsWith(fileName, Extension.Ts) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [Extension.Dts])) return undefined;
const noExtension = removeExtension(fileName, Extension.Ts);
const ext = noExtension.substring(noExtension.lastIndexOf("."));
return noExtension.substring(0, noExtension.indexOf(".d.")) + ext;

View File

@ -338,7 +338,6 @@ import {
SpreadElement,
startsWith,
Statement,
stringContains,
StringLiteral,
supportedDeclarationExtensions,
SwitchStatement,
@ -10408,7 +10407,7 @@ namespace IncrementalParser {
/** @internal */
export function isDeclarationFileName(fileName: string): boolean {
return fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || (fileExtensionIs(fileName, Extension.Ts) && stringContains(getBaseFileName(fileName), ".d."));
return fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || (fileExtensionIs(fileName, Extension.Ts) && getBaseFileName(fileName).includes(".d."));
}
function parseResolutionMode(mode: string | undefined, pos: number, end: number, reportDiagnostic: PragmaDiagnosticReporter): ResolutionMode {

View File

@ -15,7 +15,6 @@ import {
Path,
some,
startsWith,
stringContains,
} from "./_namespaces/ts";
/**
@ -113,7 +112,7 @@ export function pathIsBareSpecifier(path: string): boolean {
/** @internal */
export function hasExtension(fileName: string): boolean {
return stringContains(getBaseFileName(fileName), ".");
return getBaseFileName(fileName).includes(".");
}
/** @internal */
@ -524,7 +523,7 @@ export function getPathFromPathComponents<T extends string>(pathComponents: read
* @internal
*/
export function normalizeSlashes(path: string): string {
return path.indexOf("\\") !== -1
return path.includes("\\")
? path.replace(backslashRegExp, directorySeparator)
: path;
}

View File

@ -304,7 +304,6 @@ import {
stableSort,
startsWith,
Statement,
stringContains,
StringLiteral,
StringLiteralLike,
StructureIsReused,
@ -2016,7 +2015,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
// but the resolved real path may be the .d.ts from project reference
// Note:: Currently we try the real path only if the
// file is from node_modules to avoid having to run real path on all file paths
if (!host.realpath || !options.preserveSymlinks || !stringContains(file.originalFileName, nodeModulesPathPart)) return undefined;
if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) return undefined;
const realDeclarationPath = toPath(host.realpath(file.originalFileName));
return realDeclarationPath === file.path ? undefined : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath);
}
@ -3565,7 +3564,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
host.realpath &&
options.preserveSymlinks &&
isDeclarationFileName(fileName) &&
stringContains(fileName, nodeModulesPathPart)
fileName.includes(nodeModulesPathPart)
) {
const realPath = toPath(host.realpath(fileName));
if (realPath !== path) source = getSourceOfProjectReferenceRedirect(realPath);
@ -5090,7 +5089,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource
if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) return;
// Because we already watch node_modules, handle symlinks in there
if (!originalRealpath || !stringContains(directory, nodeModulesPathPart)) return;
if (!originalRealpath || !directory.includes(nodeModulesPathPart)) return;
const symlinkCache = host.getSymlinkCache();
const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory));
if (symlinkCache.getSymlinkedDirectories()?.has(directoryPath)) return;
@ -5124,7 +5123,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource
const symlinkedDirectories = symlinkCache.getSymlinkedDirectories();
if (!symlinkedDirectories) return false;
const fileOrDirectoryPath = host.toPath(fileOrDirectory);
if (!stringContains(fileOrDirectoryPath, nodeModulesPathPart)) return false;
if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) return false;
if (isFile && symlinkCache.getSymlinkedFiles()?.has(fileOrDirectoryPath)) return true;
// If it contains node_modules check if its one of the symlinked path we know of

View File

@ -72,7 +72,6 @@ import {
some,
SourceFile,
startsWith,
stringContains,
StringLiteralLike,
trace,
updateResolutionField,
@ -219,7 +218,7 @@ export function removeIgnoredPath(path: Path): Path | undefined {
return removeSuffix(path, "/.staging") as Path;
}
return some(ignoredPaths, searchPath => stringContains(path, searchPath)) ?
return some(ignoredPaths, searchPath => path.includes(searchPath)) ?
undefined :
path;
}

View File

@ -39,7 +39,6 @@ import {
resolveJSModule,
some,
startsWith,
stringContains,
timestamp,
unorderedRemoveItem,
WatchDirectoryKind,
@ -814,9 +813,9 @@ function createDirectoryWatcherSupportingRecursive({
}
function isInPath(path: string, searchPath: string) {
if (stringContains(path, searchPath)) return true;
if (path.includes(searchPath)) return true;
if (useCaseSensitiveFileNames) return false;
return stringContains(toCanonicalFilePath(path), searchPath);
return toCanonicalFilePath(path).includes(searchPath);
}
}

View File

@ -202,7 +202,6 @@ import {
SourceFile,
startsWith,
Statement,
stringContains,
StringLiteral,
Symbol,
SymbolAccessibility,
@ -241,7 +240,7 @@ export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver
function hasInternalAnnotation(range: CommentRange, currentSourceFile: SourceFile) {
const comment = currentSourceFile.text.substring(range.pos, range.end);
return stringContains(comment, "@internal");
return comment.includes("@internal");
}
/** @internal */

View File

@ -492,7 +492,6 @@ import {
startsWith,
startsWithUseStrict,
Statement,
stringContains,
StringLiteral,
StringLiteralLike,
StringLiteralType,
@ -802,7 +801,7 @@ export function createModuleNotFoundChain(sourceFile: SourceFile, host: TypeChec
/*details*/ undefined,
Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings,
node10Result,
node10Result.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageName)}` : packageName,
node10Result.includes(nodeModulesPathPart + "@types/") ? `@types/${mangleScopedPackageName(packageName)}` : packageName,
)
: host.typesPackageExists(packageName)
? chainDiagnosticMessages(
@ -5986,7 +5985,7 @@ function isQuoteOrBacktick(charCode: number) {
/** @internal */
export function isIntrinsicJsxName(name: __String | string) {
const ch = (name as string).charCodeAt(0);
return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || stringContains(name as string, "-");
return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || (name as string).includes("-");
}
const indentStrings: string[] = ["", " "];
@ -6007,7 +6006,7 @@ export function getIndentSize() {
/** @internal */
export function isNightly() {
return stringContains(version, "-dev") || stringContains(version, "-insiders");
return version.includes("-dev") || version.includes("-insiders");
}
/** @internal */
@ -6236,7 +6235,7 @@ export function getExternalModuleNameFromDeclaration(host: ResolveModuleNameReso
const specifier = getExternalModuleName(declaration);
if (
specifier && isStringLiteralLike(specifier) && !pathIsRelative(specifier.text) &&
getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1
!getCanonicalAbsolutePath(host, file.path).includes(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory())))
) {
return undefined;
}
@ -9335,7 +9334,7 @@ export function getSupportedExtensions(options?: CompilerOptions, extraFileExten
const flatBuiltins = flatten(builtins);
const extensions = [
...builtins,
...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension as Extension) === -1 ? [x.extension] : undefined),
...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) && !flatBuiltins.includes(x.extension as Extension) ? [x.extension] : undefined),
];
return extensions;
@ -10052,7 +10051,7 @@ export function expressionResultIsUnused(node: Expression): boolean {
/** @internal */
export function containsIgnoredPath(path: string) {
return some(ignoredPaths, p => stringContains(path, p));
return some(ignoredPaths, p => path.includes(p));
}
/** @internal */

View File

@ -77,7 +77,6 @@ import {
SourceFile,
startsWith,
startTracing,
stringContains,
supportedJSExtensionsFlat,
supportedTSExtensionsFlat,
sys,
@ -193,7 +192,7 @@ function createColors(sys: System) {
return `\x1b[1m${str}\x1b[22m`;
}
const isWindows = sys.getEnvironmentVariable("OS") && stringContains(sys.getEnvironmentVariable("OS").toLowerCase(), "windows");
const isWindows = sys.getEnvironmentVariable("OS") && sys.getEnvironmentVariable("OS").toLowerCase().includes("windows");
const isWindowsTerminal = sys.getEnvironmentVariable("WT_SESSION");
const isVSCode = sys.getEnvironmentVariable("TERM_PROGRAM") && sys.getEnvironmentVariable("TERM_PROGRAM") === "vscode";

View File

@ -213,7 +213,7 @@ export class CompilationResult {
}
else {
path = vpath.resolve(this.vfs.cwd(), path);
const outDir = ext === ".d.ts" || ext === ".d.mts" || ext === ".d.cts" || (ext.endsWith(".ts") || ts.stringContains(ext, ".d.")) ? this.options.declarationDir || this.options.outDir : this.options.outDir;
const outDir = ext === ".d.ts" || ext === ".d.mts" || ext === ".d.cts" || (ext.endsWith(".ts") || ext.includes(".d.")) ? this.options.declarationDir || this.options.outDir : this.options.outDir;
if (outDir) {
const common = this.commonSourceDirectory;
if (common) {

View File

@ -440,7 +440,7 @@ export class TestState {
const keys = ts.getAllKeys(ls);
for (const k of keys) {
const key = k as keyof typeof ls;
if (cacheableMembers.indexOf(key) === -1) {
if (!cacheableMembers.includes(key)) {
proxy[key] = (...args: any[]) => (ls[key] as (...args: any[]) => any)(...args);
continue;
}
@ -4321,7 +4321,7 @@ export class TestState {
private tryFindFileWorker(name: string): { readonly file: FourSlashFile | undefined; readonly availableNames: readonly string[]; } {
name = ts.normalizePath(name);
// names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName
name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name;
name = name.includes("/") ? name : (this.basePath + "/" + name);
const availableNames: string[] = [];
const file = ts.forEach(this.testData.files, file => {
@ -4905,7 +4905,7 @@ function parseFileContent(content: string, fileName: string, markerMap: Map<stri
openMarker = undefined;
state = State.none;
}
else if (validMarkerChars.indexOf(currentChar) < 0) {
else if (!validMarkerChars.includes(currentChar)) {
if (currentChar === "*" && i < content.length - 1 && content.charAt(i + 1) === "/") {
// The marker is about to be closed, ignore the 'invalid' char
}

View File

@ -1493,7 +1493,7 @@ export namespace Baseline {
const referenceDir = referencePath(relativeFileBase, opts && opts.Baselinefolder, opts && opts.Subfolder);
let existing = IO.readDirectory(referenceDir, referencedExtensions || [extension]);
if (extension === ".ts" || referencedExtensions && referencedExtensions.indexOf(".ts") > -1 && referencedExtensions.indexOf(".d.ts") === -1) {
if (extension === ".ts" || referencedExtensions && referencedExtensions.includes(".ts") && !referencedExtensions.includes(".d.ts")) {
// special-case and filter .d.ts out of .ts results
existing = existing.filter(f => !ts.endsWith(f, ".d.ts"));
}

View File

@ -846,7 +846,7 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger {
}
readFile(fileName: string): string | undefined {
if (ts.stringContains(fileName, Compiler.defaultLibFileName)) {
if (fileName.includes(Compiler.defaultLibFileName)) {
fileName = Compiler.defaultLibFileName;
}

View File

@ -33,7 +33,7 @@ export function splitContentByNewlines(content: string) {
/** Reads a file under /tests */
export function readTestFile(path: string) {
if (path.indexOf("tests") < 0) {
if (!path.includes("tests")) {
path = "tests/" + path;
}
@ -138,7 +138,7 @@ export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | un
}
const child = (node as any)[childName];
if (isNodeOrArray(child)) {
assert.isFalse(childNodesAndArrays.indexOf(child) < 0, "Missing child when forEach'ing over node: " + ts.Debug.formatSyntaxKind(node.kind) + "-" + childName);
assert.isFalse(!childNodesAndArrays.includes(child), "Missing child when forEach'ing over node: " + ts.Debug.formatSyntaxKind(node.kind) + "-" + childName);
}
}
}

View File

@ -133,5 +133,5 @@ export function isDefaultLibrary(path: string) {
}
export function isTsConfigFile(path: string): boolean {
return path.indexOf("tsconfig") !== -1 && path.indexOf("json") !== -1;
return path.includes("tsconfig") && path.includes("json");
}

View File

@ -49,7 +49,7 @@ export namespace Arguments {
/** @internal */
export function hasArgument(argumentName: string) {
return sys.args.indexOf(argumentName) >= 0;
return sys.args.includes(argumentName);
}
/** @internal */

View File

@ -4093,7 +4093,7 @@ export class ProjectService {
for (const type of rule.types) {
// Best-effort de-duping here - doesn't need to be unduplicated but
// we don't want the list to become a 400-element array of just 'kendo'
if (typeAcqInclude.indexOf(type) < 0) {
if (!typeAcqInclude.includes(type)) {
typeAcqInclude.push(type);
}
}
@ -4118,7 +4118,7 @@ export class ProjectService {
}).join("");
});
if (excludeRules.indexOf(processedRule) === -1) {
if (!excludeRules.includes(processedRule)) {
excludeRules.push(processedRule);
}
}
@ -4126,7 +4126,7 @@ export class ProjectService {
else {
// If not rules listed, add the default rule to exclude the matched file
const escaped = ProjectService.escapeFilenameForRegex(root);
if (excludeRules.indexOf(escaped) < 0) {
if (!excludeRules.includes(escaped)) {
excludeRules.push(escaped);
}
}
@ -4155,7 +4155,7 @@ export class ProjectService {
exclude = true;
// ... but *include* it in the list of types to acquire
// Same best-effort dedupe as above
if (typeAcqInclude.indexOf(typeName) < 0) {
if (!typeAcqInclude.includes(typeName)) {
typeAcqInclude.push(typeName);
}
}

View File

@ -1503,7 +1503,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
protected removeExistingTypings(include: string[]): string[] {
const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost);
return include.filter(i => existing.indexOf(i) < 0);
return include.filter(i => !existing.includes(i));
}
private updateGraphWorker() {

View File

@ -31,7 +31,6 @@ import {
some,
SourceFile,
SourceFileLike,
stringContains,
TextSpan,
unorderedRemoveItem,
} from "./_namespaces/ts";
@ -339,9 +338,9 @@ export class TextStorage {
export function isDynamicFileName(fileName: NormalizedPath) {
return fileName[0] === "^" ||
((stringContains(fileName, "walkThroughSnippet:/") || stringContains(fileName, "untitled:/")) &&
((fileName.includes("walkThroughSnippet:/") || fileName.includes("untitled:/")) &&
getBaseFileName(fileName)[0] === "^") ||
(stringContains(fileName, ":^") && !stringContains(fileName, directorySeparator));
(fileName.includes(":^") && !fileName.includes(directorySeparator));
}
/** @internal */

View File

@ -124,7 +124,6 @@ import {
some,
SourceFile,
startsWith,
stringContains,
SymbolDisplayPart,
SyntaxKind,
TextChange,
@ -2960,7 +2959,7 @@ export class Session<TMessage = string> implements EventSender {
}
// No need to analyze lib.d.ts
const fileNamesInProject = fileNames!.filter(value => !stringContains(value, "lib.d.ts")); // TODO: GH#18217
const fileNamesInProject = fileNames!.filter(value => !value.includes("lib.d.ts")); // TODO: GH#18217
if (fileNamesInProject.length === 0) {
return;
}

View File

@ -415,7 +415,7 @@ function mayDeleteParameter(checker: TypeChecker, sourceFile: SourceFile, parame
}
function isCallbackLike(checker: TypeChecker, sourceFile: SourceFile, name: Identifier): boolean {
return !!FindAllReferences.Core.eachSymbolReferenceInFile(name, checker, sourceFile, reference => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0);
return !!FindAllReferences.Core.eachSymbolReferenceInFile(name, checker, sourceFile, reference => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.includes(reference));
}
function isLastParameter(func: FunctionLikeDeclaration, parameter: ParameterDeclaration, isFixAll: boolean): boolean {

View File

@ -49,7 +49,6 @@ import {
SourceFile,
startsWith,
Statement,
stringContains,
stripQuotes,
Symbol,
SymbolFlags,
@ -443,7 +442,7 @@ export function forEachExternalModuleToImportFrom(
function forEachExternalModule(checker: TypeChecker, allSourceFiles: readonly SourceFile[], excludePatterns: readonly RegExp[] | undefined, cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) {
const isExcluded = excludePatterns && ((fileName: string) => excludePatterns.some(p => p.test(fileName)));
for (const ambient of checker.getAmbientModules()) {
if (!stringContains(ambient.name, "*") && !(excludePatterns && ambient.declarations?.every(d => isExcluded!(d.getSourceFile().fileName)))) {
if (!ambient.name.includes("*") && !(excludePatterns && ambient.declarations?.every(d => isExcluded!(d.getSourceFile().fileName)))) {
cb(ambient, /*sourceFile*/ undefined);
}
}

View File

@ -971,5 +971,5 @@ function isSemicolonInsertionContext(context: FormattingContext): boolean {
function isNotPropertyAccessOnIntegerLiteral(context: FormattingContext): boolean {
return !isPropertyAccessExpression(context.contextNode)
|| !isNumericLiteral(context.contextNode.expression)
|| context.contextNode.expression.getText().indexOf(".") !== -1;
|| context.contextNode.expression.getText().includes(".");
}

View File

@ -150,7 +150,7 @@ export namespace SmartIndenter {
const containerList = getListByPosition(position, precedingToken.parent, sourceFile);
// use list position if the preceding token is before any list items
if (containerList && !rangeContainsRange(containerList, precedingToken)) {
const useTheSameBaseIndentation = [SyntaxKind.FunctionExpression, SyntaxKind.ArrowFunction].indexOf(currentToken.parent.kind) !== -1;
const useTheSameBaseIndentation = [SyntaxKind.FunctionExpression, SyntaxKind.ArrowFunction].includes(currentToken.parent.kind);
const indentSize = useTheSameBaseIndentation ? 0 : options.indentSize!;
return getActualIndentationForListStartLine(containerList, sourceFile, options) + indentSize; // TODO: GH#18217
}

View File

@ -2128,7 +2128,7 @@ function collectReadsAndWrites(
function checkForUsedDeclarations(node: Node) {
// If this node is entirely within the original extraction range, we don't need to do anything.
if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node as Statement) >= 0)) {
if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.includes(node as Statement))) {
return;
}

View File

@ -283,7 +283,6 @@ import {
SourceMapSource,
startsWith,
Statement,
stringContains,
StringLiteral,
StringLiteralLike,
StringLiteralType,
@ -2959,7 +2958,7 @@ export function createLanguageService(
}
function isNodeModulesFile(path: string): boolean {
return stringContains(path, "/node_modules/");
return path.includes("/node_modules/");
}
}

View File

@ -125,7 +125,6 @@ import {
skipParentheses,
SourceFile,
startsWith,
stringContains,
StringLiteralLike,
StringLiteralType,
stripQuotes,
@ -572,7 +571,7 @@ function directoryResult(name: string): NameAndKind {
function addReplacementSpans(text: string, textStart: number, names: readonly NameAndKind[]): readonly PathCompletion[] {
const span = getDirectoryFragmentTextSpan(text, textStart);
const wholeSpan = text.length === 0 ? undefined : createTextSpan(textStart, text.length);
return names.map(({ name, kind, extension }): PathCompletion => Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span });
return names.map(({ name, kind, extension }): PathCompletion => (name.includes(directorySeparator) || name.includes(altDirectorySeparator)) ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span });
}
function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker, preferences: UserPreferences): readonly PathCompletion[] {
@ -979,7 +978,7 @@ function getPatternFromFirstMatchingCondition(target: unknown, conditions: reado
}
if (target && typeof target === "object" && !isArray(target)) {
for (const condition in target) {
if (condition === "default" || conditions.indexOf(condition) > -1 || isApplicableVersionedTypesKey(conditions, condition)) {
if (condition === "default" || conditions.includes(condition) || isApplicableVersionedTypesKey(conditions, condition)) {
const pattern = (target as MapLike<unknown>)[condition];
return getPatternFromFirstMatchingCondition(pattern, conditions);
}
@ -1001,7 +1000,7 @@ function getCompletionsForPathMapping(
): readonly NameAndKind[] {
if (!endsWith(path, "*")) {
// For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion.
return !stringContains(path, "*") ? justPathMappingName(path, ScriptElementKind.scriptElement) : emptyArray;
return !path.includes("*") ? justPathMappingName(path, ScriptElementKind.scriptElement) : emptyArray;
}
const pathPrefix = path.slice(0, path.length - 1);
@ -1102,7 +1101,7 @@ function removeLeadingDirectorySeparator(path: string): string {
function getAmbientModuleCompletions(fragment: string, fragmentDirectory: string | undefined, checker: TypeChecker): readonly string[] {
// Get modules that the type checker picked up
const ambientModules = checker.getAmbientModules().map(sym => stripQuotes(sym.name));
const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment) && moduleName.indexOf("*") < 0);
const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment) && !moduleName.includes("*"));
// Nested modules of the form "module-name/sub" need to be adjusted to only return the string
// after the last '/' that appears in the fragment because that's where the replacement span
@ -1233,7 +1232,7 @@ const tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\
const nodeModulesDependencyKeys: readonly string[] = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
function containsSlash(fragment: string) {
return stringContains(fragment, directorySeparator);
return fragment.includes(directorySeparator);
}
/**

View File

@ -330,7 +330,6 @@ import {
SpreadElement,
stableSort,
startsWith,
stringContains,
StringLiteral,
StringLiteralLike,
stringToToken,
@ -3854,7 +3853,7 @@ export function createPackageJsonImportFilter(fromFile: SourceFile, preferences:
}
function getNodeModulesPackageNameFromFileName(importedFileName: string, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost): string | undefined {
if (!stringContains(importedFileName, "node_modules")) {
if (!importedFileName.includes("node_modules")) {
return undefined;
}
const specifier = moduleSpecifiers.getNodeModulesPackageName(

View File

@ -329,7 +329,7 @@ class CompilerTest {
}
public verifyTypesAndSymbols() {
if (this.fileName.indexOf("APISample") >= 0) {
if (this.fileName.includes("APISample")) {
return;
}

View File

@ -161,7 +161,7 @@ function handleTestConfig() {
const runnerConfig = testConfig.runners || testConfig.test;
if (runnerConfig && runnerConfig.length > 0) {
if (testConfig.runners) {
runUnitTests = runnerConfig.indexOf("unittest") !== -1;
runUnitTests = runnerConfig.includes("unittest");
}
for (const option of runnerConfig) {
if (!option) {

View File

@ -60,7 +60,7 @@ export function replaceText(fs: vfs.FileSystem, path: string, oldText: string, n
throw new Error(`File ${path} does not exist`);
}
const old = fs.readFileSync(path, "utf-8");
if (old.indexOf(oldText) < 0) {
if (!old.includes(oldText)) {
throw new Error(`Text "${oldText}" does not exist in file ${path}`);
}
const newContent = old.replace(oldText, newText);

View File

@ -63,7 +63,7 @@ function runBaseline(scenario: string, baselines: readonly string[]) {
describe("unittests:: moduleResolution:: Node module resolution - relative paths", () => {
// node module resolution does _not_ implicitly append these extensions to an extensionless path (though will still attempt to load them if explicitly)
const nonImplicitExtensions = [ts.Extension.Mts, ts.Extension.Dmts, ts.Extension.Mjs, ts.Extension.Cts, ts.Extension.Dcts, ts.Extension.Cjs];
const autoExtensions = ts.filter(ts.supportedTSExtensionsFlat, e => nonImplicitExtensions.indexOf(e) === -1);
const autoExtensions = ts.filter(ts.supportedTSExtensionsFlat, e => !nonImplicitExtensions.includes(e));
it("load as file", () => {
const baselines: string[] = [];

View File

@ -59,7 +59,7 @@ describe("unittests:: tsbuild - graph-ordering", () => {
if (!circular) {
for (const dep of deps) {
const child = getProjectFileName(dep[0]);
if (buildQueue.indexOf(child) < 0) continue;
if (!buildQueue.includes(child)) continue;
const parent = getProjectFileName(dep[1]);
assert.isAbove(buildQueue.indexOf(child), buildQueue.indexOf(parent), `Expecting child ${child} to be built after parent ${parent}`);
}
@ -73,8 +73,8 @@ describe("unittests:: tsbuild - graph-ordering", () => {
function writeProjects(fileSystem: vfs.FileSystem, projectNames: string[], deps: [string, string][]): string[] {
const projFileNames: string[] = [];
for (const dep of deps) {
if (projectNames.indexOf(dep[0]) < 0) throw new Error(`Invalid dependency - project ${dep[0]} does not exist`);
if (projectNames.indexOf(dep[1]) < 0) throw new Error(`Invalid dependency - project ${dep[1]} does not exist`);
if (!projectNames.includes(dep[0])) throw new Error(`Invalid dependency - project ${dep[0]} does not exist`);
if (!projectNames.includes(dep[1])) throw new Error(`Invalid dependency - project ${dep[1]} does not exist`);
}
for (const proj of projectNames) {
fileSystem.mkdirpSync(`/project/${proj}`);

View File

@ -1,4 +1,3 @@
import * as ts from "../../_namespaces/ts";
import * as Utils from "../../_namespaces/Utils";
import {
verifyTscWatch,
@ -131,7 +130,7 @@ describe("unittests:: tsc:: declarationEmit::", () => {
{ path: `/user/username/projects/myproject/plugin-one/node_modules/plugin-two`, symLink: `/user/username/projects/myproject/plugin-two` },
libFile,
],
changeCaseFileTestPath: str => ts.stringContains(str, "/plugin-two"),
changeCaseFileTestPath: str => str.includes("/plugin-two"),
});
verifyDeclarationEmit({
@ -161,7 +160,7 @@ ${pluginOneAction()}`,
{ path: `/user/username/projects/myproject/plugin-one/node_modules/plugin-two`, symLink: `/temp/yarn/data/link/plugin-two` },
libFile,
],
changeCaseFileTestPath: str => ts.stringContains(str, "/plugin-two"),
changeCaseFileTestPath: str => str.includes("/plugin-two"),
});
});
@ -254,6 +253,6 @@ ${pluginOneAction()}`,
},
libFile,
],
changeCaseFileTestPath: str => ts.stringContains(str, "/pkg1"),
changeCaseFileTestPath: str => str.includes("/pkg1"),
});
});

View File

@ -69,7 +69,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution
return false;
}
fileExistsIsCalled = true;
assert.isTrue(fileName.indexOf("/f2.") !== -1);
assert.isTrue(fileName.includes("/f2."));
return originalFileExists.call(host, fileName);
};
sys.writeFile(root.path, `import {x} from "f2"`);
@ -88,7 +88,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution
return false;
}
fileExistsIsCalled = true;
assert.isTrue(fileName.indexOf("/f1.") !== -1);
assert.isTrue(fileName.includes("/f1."));
return originalFileExists.call(host, fileName);
};
sys.writeFile(root.path, `import {x} from "f1"`);
@ -129,7 +129,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution
return false;
}
if (!fileExistsCalledForBar) {
fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1;
fileExistsCalledForBar = fileName.includes("/bar.");
}
return originalFileExists.call(host, fileName);
@ -187,7 +187,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution
return false;
}
if (!fileExistsCalledForBar) {
fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1;
fileExistsCalledForBar = fileName.includes("/bar.");
}
return originalFileExists.call(host, fileName);
};

View File

@ -717,7 +717,7 @@ describe("unittests:: tsserver:: typingsInstaller:: General functionality", () =
logger,
(installer, requestId, packageNames, cb) => {
let typingFiles: (File & { typings: string; })[] = [];
if (packageNames.indexOf(ts.server.typingsInstaller.typingsName("commander")) >= 0) {
if (packageNames.includes(ts.server.typingsInstaller.typingsName("commander"))) {
typingFiles = [commander, jquery, lodash, cordova];
}
else {
@ -1243,7 +1243,7 @@ describe("unittests:: tsserver:: typingsInstaller:: General functionality", () =
logger,
(installer, requestId, packageNames, cb) => {
let typingFiles: (File & { typings: string; })[] = [];
if (packageNames.indexOf(ts.server.typingsInstaller.typingsName("commander")) >= 0) {
if (packageNames.includes(ts.server.typingsInstaller.typingsName("commander"))) {
typingFiles = [commander];
}
else {

View File

@ -10,7 +10,6 @@ import {
MapLike,
normalizePath,
normalizeSlashes,
stringContains,
sys,
toPath,
version,
@ -123,7 +122,7 @@ export class NodeTypingsInstaller extends TypingsInstaller {
this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, this.installTypingHost);
// If the NPM path contains spaces and isn't wrapped in quotes, do so.
if (stringContains(this.npmPath, " ") && this.npmPath[0] !== `"`) {
if (this.npmPath.includes(" ") && this.npmPath[0] !== `"`) {
this.npmPath = `"${this.npmPath}"`;
}
if (this.log.isEnabled()) {