Skip to content

Instantly share code, notes, and snippets.

@noih
Created March 11, 2024 09:59
Show Gist options
  • Save noih/e77bb88f2d08ac6b0df67217b4d22d95 to your computer and use it in GitHub Desktop.
Save noih/e77bb88f2d08ac6b0df67217b4d22d95 to your computer and use it in GitHub Desktop.
Parse CSS loop version
/**
* Parse CSS loop verison
*
* recursive version https://gist.github.com/noih/9eae4b2fab4676a7b79b46c2200dece2
*
* @link https://playcode.io/1794542
* @author noih.dev
*/
type Style = Record<string, string>
const parse = (chars: string[]) => {
const styles: Record<string, Style> = {}
const selectors: string[] = []
let str = ''
let brackets = 0
let comment: string | undefined
for (const c of chars) {
if (typeof comment === 'string') {
comment = c === '/' && comment.endsWith('*') ? undefined : comment + c
continue
}
switch (c) {
case '{':
selectors.push(str.trim())
str = ''
brackets = 0
break
case '}':
selectors.pop()
str = ''
brackets = 0
break
case '(':
str += c
brackets += 1
break
case ')':
str += c
brackets -= 1
break
case '*':
if (str.endsWith('/')) {
str = str.slice(0, -1)
comment = ''
break
}
str += c
break
case ';': {
if (brackets) {
str += c
break
}
const selector = selectors.join(' ')
const [key, ...values] = str.split(':')
styles[selector] = {
...styles[selector],
[key.trim()]: values.join(':').trim()
}
str = ''
break
}
default:
str += c
}
}
return styles
}
const css = `
.select {
width: 475px; /* comment */
height: 40px !important;
color: rgba(148.000006377697, 163.00000548362732, 184.00000423192978, 1);
background: url(http://localhost:5050/123:456;789.png)
0px 0px / 10px 8px no-repeat border-box;
}
`
const parsed = parse(
css
.replace(/\n/gm, ' ')
.replace(/\s+/gm, ' ')
.trim()
.split('')
)
console.log(parsed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment