Skip to content

Commit

Permalink
feat: use alternative of str.match (#3400)
Browse files Browse the repository at this point in the history
  • Loading branch information
chu121su12 committed Nov 30, 2023
1 parent 235c377 commit 9357448
Show file tree
Hide file tree
Showing 20 changed files with 32 additions and 33 deletions.
4 changes: 2 additions & 2 deletions packages/autocomplete/src/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function createAutocomplete(uno: UnoGenerator, options: AutocompleteOptio

await Promise.all(
[...matched]
.filter(i => i.match(/^\w+$/) && i.length > 3)
.filter(i => /^\w+$/.test(i) && i.length > 3)
.map(i => suggest(`${i}-`)
.then(i => i.forEach(j => matched.add(j)))),
)
Expand Down Expand Up @@ -187,7 +187,7 @@ export function createAutocomplete(uno: UnoGenerator, options: AutocompleteOptio

function processSuggestions(suggestions: (string[] | undefined)[], prefix = '', suffix = '') {
return uniq(suggestions.flat())
.filter((i): i is string => !!(i && !i.match(/-$/) && !uno.isBlocked(i)))
.filter((i): i is string => !!(i && !i.endsWith('-') && !uno.isBlocked(i)))
.sort((a, b) => {
if (/\d/.test(a) && /\D/.test(b))
return 1
Expand Down
2 changes: 1 addition & 1 deletion packages/autocomplete/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function searchUsageBoundary(line: string, index: number) {

export function searchAttrKey(content: string, cursor: number) {
const text = content.substring(0, cursor)
if (text.match(/(<\w+\s*)[^>]*$/) !== null)
if (/(<\w+\s*)[^>]*$/.test(text))
return text.match(/\S+(?=\s*=\s*["']?[^"']*$)/)?.[0]
}

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/generator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,7 @@ export function createGenerator<Theme extends object = object>(config?: UserConf

export const regexScopePlaceholder = /\s\$\$\s+/g
export function hasScopePlaceholder(css: string) {
return css.match(/\s\$\$\s/)
return regexScopePlaceholder.test(css)
}

function applyScope(css: string, scope?: string) {
Expand Down
2 changes: 1 addition & 1 deletion packages/extractor-arbitrary-variants/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function splitCodeWithArbitraryVariants(code: string): string[] {
const result: string[] = []

for (const match of code.matchAll(arbitraryPropertyRE)) {
if (match.index !== 0 && !code[match.index! - 1]?.match(/^[\s'"`]/))
if (match.index !== 0 && !/^[\s'"`]/.test(code[match.index! - 1] ?? ''))
continue

result.push(match[0])
Expand Down
2 changes: 1 addition & 1 deletion packages/extractor-mdc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export default function extractorMdc(): Extractor {
return {
name: '@unocss/extractor-mdc',
async extract(ctx) {
if (!(ctx.id?.match(/\.(md|mdc|markdown)$/i)))
if (!/\.(md|mdc|markdown)$/i.test(ctx.id ?? ''))
return

ctx.code.match(/\.[\w:\/_-]+/g)?.forEach((c) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/extractor-pug/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ export default function extractorPug(options: Options = {}): Extractor {
async extract(ctx) {
if (!ctx.id)
return
if (ctx.id.match(/\.pug$/) || ctx.id.match(/\?vue&type=template/)) {
if (ctx.id.endsWith('.pug') || ctx.id.includes('?vue&type=template')) {
try {
ctx.code = await compile(ctx.code, ctx.id) || ctx.code
}
catch {}
}
else if (ctx.id.match(/\.vue$/)) {
else if (ctx.id.endsWith('.vue')) {
const matches = Array.from(ctx.code.matchAll(regexVueTemplate))
let tail = ''
for (const match of matches) {
Expand Down
2 changes: 1 addition & 1 deletion packages/preset-mini/src/_rules/variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const cssProperty: Rule[] = [
const [prop, ...rest] = body.split(':')
const value = rest.join(':')

if (!isURI(body) && prop.match(/^[a-z-]+$/) && isValidCSSBody(value)) {
if (!isURI(body) && /^[a-z-]+$/.test(prop) && isValidCSSBody(value)) {
let parsed

if (hasThemeFn(value))
Expand Down
6 changes: 3 additions & 3 deletions packages/preset-mini/src/_utils/handlers/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function auto(str: string) {
}

export function rem(str: string) {
if (str.match(unitOnlyRE))
if (unitOnlyRE.test(str))
return `1${str}`
const match = str.match(numberWithUnitRE)
if (!match)
Expand All @@ -99,7 +99,7 @@ export function rem(str: string) {
}

export function px(str: string) {
if (str.match(unitOnlyRE))
if (unitOnlyRE.test(str))
return `1${str}`
const match = str.match(numberWithUnitRE)
if (!match)
Expand Down Expand Up @@ -225,7 +225,7 @@ export function bracketOfPosition(str: string) {
}

export function cssvar(str: string) {
if (str.match(/^\$[^\s'"`;{}]/))
if (/^\$[^\s'"`;{}]/.test(str))
return `var(--${escapeSelector(str.slice(1))})`
}

Expand Down
6 changes: 3 additions & 3 deletions packages/preset-mini/src/_utils/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ export function parseColor(body: string, theme: Theme, key?: ThemeColorKeys): Pa
if (h.numberWithUnit(bracketOrMain))
return

if (bracketOrMain.match(/^#[\da-fA-F]+/g))
if (/^#[\da-fA-F]+/.test(bracketOrMain))
color = bracketOrMain
else if (bracketOrMain.match(/^hex-[\da-fA-F]+/g))
else if (/^hex-[\da-fA-F]+/.test(bracketOrMain))
color = `#${bracketOrMain.slice(4)}`
else if (main.startsWith('$'))
color = h.cssvar(main)
Expand All @@ -121,7 +121,7 @@ export function parseColor(body: string, theme: Theme, key?: ThemeColorKeys): Pa
if (!color) {
let colorData
const [scale] = colors.slice(-1)
if (scale.match(/^\d+$/)) {
if (/^\d+$/.test(scale)) {
no = scale
colorData = getThemeColor(theme, colors.slice(0, -1), key)
if (!colorData || typeof colorData === 'string')
Expand Down
2 changes: 1 addition & 1 deletion packages/preset-mini/src/_variants/negative.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const variantNegative: Variant = {
const value = v[1]?.toString()
if (!value || value === '0')
return
if (ignoreProps.some(i => v[0].match(i)))
if (ignoreProps.some(i => i.test(v[0])))
return
const negated = negateFunctions(value)
if (negated) {
Expand Down
4 changes: 2 additions & 2 deletions packages/shared-common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export function getMatchedPositions(

// highlight classes that includes `><`
function highlightLessGreaterThanSign(str: string) {
if (str.match(/[><]/)) {
if (/[><]/.test(str)) {
for (const match of code.matchAll(new RegExp(escapeRegExp(str), 'g'))) {
const start = match.index!
const end = start + match[0].length
Expand Down Expand Up @@ -162,7 +162,7 @@ export function getMatchedPositions(
const escaped = match[1]
const body = match[0].slice(escaped.length)
let bodyIndex = body.match(`[\\b\\s'"]${escapeRegExp(value)}[\\b\\s'"]`)?.index ?? -1
if (body[bodyIndex]?.match(/[\s'"]/))
if (/[\s'"]/.test(body[bodyIndex] ?? ''))
bodyIndex++
if (bodyIndex < 0)
return
Expand Down
8 changes: 4 additions & 4 deletions packages/shared-docs/src/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,23 +65,23 @@ export function createSearch(
input = input.trim()

// mdn
if (input.match(/^(mdn|doc):/)) {
if (input.startsWith('mdn:') || input.startsWith('doc:')) {
input = input.slice(4).trim()
if (!input)
return docs.value.slice(0, limit)
return docsFuse.value.search(input, { limit }).map(i => i.item)
}

// guide
if (input.match(/^guide:/)) {
if (input.startsWith('guide:')) {
input = input.slice(6).trim()
if (!input)
return guides.slice(0, limit)
return guideFuse.search(input, { limit }).map(i => i.item)
}

// random
if (input.match(/^rand(om)?:/))
if (input.startsWith('rand:') || input.startsWith('random:'))
return sampleArray(fuseCollection, limit)

const parts = input.split(/\s/g).filter(notNull)
Expand Down Expand Up @@ -212,7 +212,7 @@ export function createSearch(
function getUrls(css: string) {
return uniq([...css.matchAll(/\burl\(([^)]+)\)/mg)]
.map(i => i[1]))
.map(i => i.match(/^(['"]).*\1$/) ? i.slice(1, -1) : i)
.map(i => /^(['"]).*\1$/.test(i) ? i.slice(1, -1) : i)
}

function getUtilsOfFeature(name: string) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
export function removeOuterQuotes(input: string): string {
if (!input)
return ''
const match = input.match(/^(['"]).*\1$/)
return match ? input.slice(1, -1) : input
return /^(['"]).*\1$/.test(input) ? input.slice(1, -1) : input
}

if (import.meta.vitest) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function createCssTransformerPlugins(context: SvelteScopedContext, cssTra
enforce: enforce === 'default' ? undefined : enforce,

async transform(code, id) {
if (!id.match(cssIdRE) || id.match(svelteIdRE))
if (!cssIdRE.test(id) || svelteIdRE.test(id))
return
context.uno.config.transformers = cssTransformers ?? []
return applyTransformers({
Expand Down
2 changes: 1 addition & 1 deletion packages/transformer-directives/src/apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export async function parseApply({ code, uno, offset, applyVariable }: Transform
else if (childNode!.type === 'Declaration' && applyVariable.includes(childNode.property) && childNode.value.type === 'Raw') {
body = childNode.value.value.trim()
// remove quotes
if (body.match(/^(['"]).*\1$/))
if (/^(['"]).*\1$/.test(body))
body = body.slice(1, -1)
}

Expand Down
2 changes: 1 addition & 1 deletion packages/transformer-directives/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default function transformerDirectives(options: TransformerDirectivesOpti
return {
name: '@unocss/transformer-directives',
enforce: options?.enforce,
idFilter: id => !!id.match(cssIdRE),
idFilter: id => cssIdRE.test(id),
transform: (code, id, ctx) => {
return transformDirectives(code, ctx.uno, options, id)
},
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/modes/global/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export function GlobalModeBuildPlugin(ctx: UnocssPluginContext<VitePluginConfig>
return null

// skip hash generation on non-entry chunk
if (!Object.keys(chunk.modules).some(i => i.match(RESOLVED_ID_RE)))
if (!Object.keys(chunk.modules).some(i => RESOLVED_ID_RE.test(i)))
return null

const cssPost = cssPostPlugins.get(options.dir)
Expand Down Expand Up @@ -208,7 +208,7 @@ export function GlobalModeBuildPlugin(ctx: UnocssPluginContext<VitePluginConfig>
if (isLegacyChunk(chunk, options))
return null

if (!Object.keys(chunk.modules).some(i => i.match(RESOLVED_ID_RE)))
if (!Object.keys(chunk.modules).some(i => RESOLVED_ID_RE.test(i)))
return null

const cssPost = cssPostPlugins.get(options.dir)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/modes/per-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function PerModuleModePlugin({ uno, filter }: UnocssPluginContext): Plugi
if (!filter(code, id))
return
const hash = getHash(id)
const hasScope = code.match(SCOPE_IMPORT_RE)
const hasScope = SCOPE_IMPORT_RE.test(code)

const { css } = await uno.generate(code, { id, scope: hasScope ? `.${hash}` : undefined, preflights: false })
if (!css && !hasScope)
Expand Down
4 changes: 2 additions & 2 deletions packages/vscode/src/contextLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ export class ContextLoader {
log.appendLine(`🛠 New configuration loaded from\n${sources.map(s => ` - ${s}`).join('\n')}`)
log.appendLine(`ℹ️ ${context.uno.config.presets.length} presets, ${context.uno.config.rulesSize} rules, ${context.uno.config.shortcuts.length} shortcuts, ${context.uno.config.variants.length} variants, ${context.uno.config.transformers?.length || 0} transformers loaded`)

if (!sources.some(i => i.match(/\buno(css)?\.config\./))) {
if (!sources.some(i => /\buno(css)?\.config\./.test(i))) {
log.appendLine('💡 To have the best IDE experience, it\'s recommended to move UnoCSS configurations into a standalone `uno.config.ts` file at the root of your project.')
log.appendLine('👉 Learn more at https://unocss.dev/guide/config-file')
}
Expand All @@ -217,7 +217,7 @@ export class ContextLoader {
if (!this.contextsMap.size)
return undefined

if (file.match(/[\/](node_modules|dist|\.temp|\.cache)[\/]/g))
if (/[\/](node_modules|dist|\.temp|\.cache)[\/]/g.test(file))
return undefined

if (this.fileContextCache.has(file))
Expand Down
2 changes: 1 addition & 1 deletion packages/webpack/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export default function WebpackPlugin<Theme extends object>(
name: 'unocss:webpack',
enforce: 'pre',
transformInclude(id) {
return filter('', id) && !id.match(/\.html$/) && !RESOLVED_ID_RE.test(id)
return filter('', id) && !id.endsWith('.html') && !RESOLVED_ID_RE.test(id)
},
async transform(code, id) {
const result = await applyTransformers(ctx, code, id, 'pre')
Expand Down

0 comments on commit 9357448

Please sign in to comment.