Skip to content

Commit 0d0a406

Browse files
committed
♻️ refactor solution for challenge 8
1 parent ef26989 commit 0d0a406

File tree

2 files changed

+10
-16
lines changed

2 files changed

+10
-16
lines changed

src/challenges/08.ts

+9-15
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,16 @@
11
export function organizeGifts (gifts: string): string {
22
const giftsRegex = /(\d+)([a-z])/g
33
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-
})
84
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)}`
2014
}
2115
return ans
2216
}

src/tests/08.spec.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { test, expectTypeOf, expect, describe } from 'vitest'
22
import { organizeGifts } from '../challenges/08'
33

4-
describe('Challenge Test Template', () => {
4+
describe('Challenge #08', () => {
55
test('Test #01', () => {
66
expectTypeOf(organizeGifts).returns.toEqualTypeOf('')
77
})

0 commit comments

Comments
 (0)