(input: string)
| 35 | * @since 1.0.0 |
| 36 | */ |
| 37 | export function parse(input: string) { |
| 38 | // Optimization: Use new Empty() instead of Object.create(null) for performance |
| 39 | // v8 has a better optimization for initializing functions compared to Object |
| 40 | const result = new Empty() |
| 41 | |
| 42 | if (typeof input !== "string") { |
| 43 | return result |
| 44 | } |
| 45 | |
| 46 | const inputLength = input.length |
| 47 | let key = "" |
| 48 | let value = "" |
| 49 | let startingIndex = -1 |
| 50 | let equalityIndex = -1 |
| 51 | let shouldDecodeKey = false |
| 52 | let shouldDecodeValue = false |
| 53 | let keyHasPlus = false |
| 54 | let valueHasPlus = false |
| 55 | let hasBothKeyValuePair = false |
| 56 | let c = 0 |
| 57 | |
| 58 | // Have a boundary of input.length + 1 to access last pair inside the loop. |
| 59 | for (let i = 0; i < inputLength + 1; i++) { |
| 60 | c = i !== inputLength ? input.charCodeAt(i) : 38 |
| 61 | |
| 62 | // Handle '&' and end of line to pass the current values to result |
| 63 | if (c === 38) { |
| 64 | hasBothKeyValuePair = equalityIndex > startingIndex |
| 65 | |
| 66 | // Optimization: Reuse equality index to store the end of key |
| 67 | if (!hasBothKeyValuePair) { |
| 68 | equalityIndex = i |
| 69 | } |
| 70 | |
| 71 | key = input.slice(startingIndex + 1, equalityIndex) |
| 72 | |
| 73 | // Add key/value pair only if the range size is greater than 1; a.k.a. contains at least "=" |
| 74 | if (hasBothKeyValuePair || key.length > 0) { |
| 75 | // Optimization: Replace '+' with space |
| 76 | if (keyHasPlus) { |
| 77 | key = key.replace(plusRegex, " ") |
| 78 | } |
| 79 | |
| 80 | // Optimization: Do not decode if it's not necessary. |
| 81 | if (shouldDecodeKey) { |
| 82 | try { |
| 83 | key = decodeURIComponent(key) || key |
| 84 | } catch {} |
| 85 | } |
| 86 | |
| 87 | if (hasBothKeyValuePair) { |
| 88 | value = input.slice(equalityIndex + 1, i) |
| 89 | |
| 90 | if (valueHasPlus) { |
| 91 | value = value.replace(plusRegex, " ") |
| 92 | } |
| 93 | |
| 94 | if (shouldDecodeValue) { |
no test coverage detected