resistor-color-trio.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. export function decodedResistorValue(colors: string[]): string {
  2. if (colors.length < 3) {
  3. throw new Error("Unexpected number of colors");
  4. }
  5. // Ignore extra colors.
  6. const first = colors.slice(0, 2);
  7. let value = colorCode(first[0]) * 10 + colorCode(first[1]);
  8. let scale = colorCode(colors[2]);
  9. if (value % 10 === 0) {
  10. value /= 10;
  11. scale++;
  12. }
  13. let prefix: string = '';
  14. switch (scale) {
  15. case 9:
  16. prefix = 'giga';
  17. break;
  18. case 8:
  19. prefix = 'mega';
  20. value *= 100;
  21. break;
  22. case 7:
  23. prefix = 'mega';
  24. value *= 10;
  25. break;
  26. case 6:
  27. prefix = 'mega';
  28. break;
  29. case 5:
  30. prefix = 'kilo';
  31. value *= 100;
  32. break;
  33. case 4:
  34. prefix = 'kilo';
  35. value *= 10;
  36. break;
  37. case 3:
  38. prefix = 'kilo';
  39. break;
  40. case 2:
  41. value *= 100;
  42. break;
  43. case 1:
  44. value *= 10;
  45. break;
  46. }
  47. return `${value} ${prefix}ohms`;
  48. }
  49. export const colorCode = (name: string): number => {
  50. const num = COLORS.indexOf(name.toLowerCase())
  51. if (num == -1) {
  52. throw new Error(`Invalid color name "${name}"`);
  53. }
  54. return num;
  55. }
  56. export const COLORS: string[] = [
  57. 'black',
  58. 'brown',
  59. 'red',
  60. 'orange',
  61. 'yellow',
  62. 'green',
  63. 'blue',
  64. 'violet',
  65. 'grey',
  66. 'white',
  67. ];