|
1 | 1 | export function organizeGifts (gifts: string): string {
|
2 | 2 | const giftsRegex = /(\d+)([a-z])/g
|
3 | 3 | const giftsMatches = gifts.matchAll(giftsRegex)
|
4 |
| - const giftsArray = Array.from(giftsMatches).map((match) => { |
5 |
| - const [, count, symbol] = match |
6 |
| - return { count: Number(count), symbol } |
7 |
| - }) |
8 | 4 | let ans = ''
|
9 |
| - for (const { count, symbol } of giftsArray) { |
10 |
| - let remainder = count |
11 |
| - const pallets = Math.floor(remainder / 50) |
12 |
| - remainder -= pallets * 50 |
13 |
| - const boxes = Math.floor(remainder / 10) |
14 |
| - remainder -= boxes * 10 |
15 |
| - const bags = remainder |
16 |
| - const palletsStr = `[${symbol}]`.repeat(pallets) |
17 |
| - const boxesStr = `{${symbol}}`.repeat(boxes) |
18 |
| - const bagsStr = `(${symbol.repeat(bags)})`.repeat(Math.min(1, bags)) |
19 |
| - ans += palletsStr + boxesStr + bagsStr |
| 5 | + for (const match of giftsMatches) { |
| 6 | + const [, qty, symbol] = match |
| 7 | + let left = +qty |
| 8 | + ans = `${ans}${`[${symbol}]`.repeat((left - (left % 50)) / 50)}` |
| 9 | + left -= 50 * ((left - (left % 50)) / 50) |
| 10 | + ans = `${ans}${`{${symbol}}`.repeat((left - (left % 10)) / 10)}` |
| 11 | + left -= 10 * (left - (left % 10)) / 10 |
| 12 | + const x = ((left - 1) + ((left - 1) >> 31)) ^ ((left - 1) >> 31) |
| 13 | + ans = `${ans}${`(${symbol.repeat(left)})`.repeat((left + 1 - x) / 2)}` |
20 | 14 | }
|
21 | 15 | return ans
|
22 | 16 | }
|
0 commit comments