Created
November 8, 2023 07:27
-
-
Save easrng/713d3cbe43e8604392761710aa8a4e86 to your computer and use it in GitHub Desktop.
normalize MIME types for comparison
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function normalizeMime(string) { | |
let pos = 0; | |
let normalized = ""; | |
const consume = (regex) => { | |
const match = string.match(regex); | |
if (!match) | |
throw new SyntaxError( | |
"failed to match /" + | |
regex.source + | |
"/" + | |
regex.flags + | |
" at index " + | |
pos, | |
); | |
const consumed = match[0]; | |
const length = consumed.length; | |
pos += length; | |
string = string.slice(length); | |
return consumed; | |
}; | |
const consumeQuoted = () => { | |
let str = ""; | |
consume(/^"/); | |
while (true) { | |
if (string[0] === "\\") { | |
str += consume(/^\\/); | |
str += consume(/^[\x21-\x7E]/); | |
} else if (string[0] === '"') { | |
consume(/^"/); | |
break; | |
} else { | |
str += consume(/^[\s\S]/); | |
} | |
} | |
return str; | |
}; | |
const ws = () => consume(/^\s*/); | |
const token = /^[0-9A-Za-z!#$%&'*+.^_`|~-]+/; | |
ws(); | |
normalized += consume(token); | |
ws(); | |
normalized += consume(/^\//); | |
ws(); | |
normalized += consume(token); | |
ws(); | |
while (string.length > 0) { | |
normalized += consume(/^;/); | |
ws(); | |
normalized += consume(token); | |
ws(); | |
normalized += consume(/^=/); | |
ws(); | |
const value = string[0] === '"' ? consumeQuoted() : consume(token); | |
const match = value.match(token); | |
normalized += | |
match && match[0].length === value.length ? value : `"${value}"`; | |
ws(); | |
} | |
return normalized; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment