Skip to content

Commit 459a69d

Browse files
committed
Solve 'Dashatize it' kata
1 parent b220cdd commit 459a69d

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/dashatize-it/dashatize.ts

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* https://www.codewars.com/kata/58223370aef9fc03fd000071/train/typescript
3+
*/
4+
export function dashatize (num: number): string {
5+
if (isNaN(num)) {
6+
return 'NaN'
7+
}
8+
9+
if (num < 0) {
10+
return dashatize(-num)
11+
}
12+
13+
const digits = num
14+
.toString()
15+
.split('')
16+
.map(Number)
17+
18+
const groups = splitBy(digits, (a, b) => {
19+
return isOdd(a) || isOdd(b)
20+
})
21+
22+
return groups
23+
.map(group => group.join(''))
24+
.join('-')
25+
}
26+
27+
function isOdd (num: number): boolean {
28+
return num % 2 === 1
29+
}
30+
31+
function splitBy<T> (array: T[], predicate: (a: T, b: T) => boolean): T[][] {
32+
const splitBetween = (groups: T[][], value: T, i: number): T[][] => {
33+
if (i === 0 || !predicate(array[i - 1], value)) {
34+
let group = groups[groups.length - 1]
35+
36+
if (group === undefined) {
37+
group = []
38+
groups.push(group)
39+
}
40+
41+
group.push(value)
42+
} else {
43+
groups.push([value])
44+
}
45+
46+
return groups
47+
}
48+
49+
return array.reduce(splitBetween, [])
50+
}

test/dashatize-it/dashatize.spec.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { dashatize } from '../../src/dashatize-it/dashatize'
2+
import { assert } from 'chai'
3+
4+
function doTest (num: number, expected: string): void {
5+
const actual: string = dashatize(num)
6+
assert.strictEqual(actual, expected, `Testing for num = ${num}`)
7+
}
8+
9+
describe('Dashatize it', () => {
10+
describe('Sample Tests', () => {
11+
it('Basic', () => {
12+
doTest(274, '2-7-4')
13+
doTest(5311, '5-3-1-1')
14+
doTest(86320, '86-3-20')
15+
doTest(974302, '9-7-4-3-02')
16+
})
17+
18+
it('Weird', () => {
19+
doTest(0, '0')
20+
doTest(-1, '1')
21+
doTest(-28369, '28-3-6-9')
22+
})
23+
})
24+
})

0 commit comments

Comments
 (0)