allergies.ts 892 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. type allergyMap = { [key: number]: string };
  2. let allergies:allergyMap = {
  3. 1: 'eggs',
  4. 2: 'peanuts',
  5. 4: 'shellfish',
  6. 8: 'strawberries',
  7. 16: 'tomatoes',
  8. 32: 'chocolate',
  9. 64: 'pollen',
  10. 128: 'cats',
  11. };
  12. export class Allergies {
  13. private ids = 0;
  14. constructor(allergenIndex: number) {
  15. allergenIndex &= 255;
  16. let i = 1;
  17. while (i <= 128) {
  18. if ((i & allergenIndex) !== 0) {
  19. this.ids |= i;
  20. }
  21. i <<= 1;
  22. }
  23. }
  24. public list(): string[] {
  25. let i = 1;
  26. let res: string[] = [];
  27. while (i <= 128) {
  28. if ((i & this.ids) !== 0) {
  29. res.push(allergies[i])
  30. }
  31. i <<= 1;
  32. }
  33. return res;
  34. }
  35. public allergicTo(allergen: string): boolean {
  36. return this.list().indexOf(allergen) >= 0;
  37. }
  38. }