File size: 1,138 Bytes
63f6453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/** Roma rakamları dönüştürücü (1–3999). */
const TABLE: Array<[number, string]> = [
  [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
  [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
  [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],
];

export function toRoman(n: number): string {
  if (!Number.isInteger(n) || n < 1 || n > 3999) {
    throw new RangeError('1 ile 3999 arasında tam sayı olmalı');
  }
  let out = '';
  let rest = n;
  for (const [value, sym] of TABLE) {
    while (rest >= value) {
      out += sym;
      rest -= value;
    }
  }
  return out;
}

export function fromRoman(s: string): number {
  const str = s.trim().toUpperCase();
  if (!/^[MDCLXVI]+$/.test(str)) throw new SyntaxError('Geçersiz Roma rakamı');
  const val: Record<string, number> = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 };
  let total = 0;
  for (let i = 0; i < str.length; i++) {
    const cur = val[str[i]];
    const next = i + 1 < str.length ? val[str[i + 1]] : 0;
    total += cur < next ? -cur : cur;
  }
  if (toRoman(total) !== str) throw new SyntaxError('Kanonik olmayan Roma rakamı');
  return total;
}