1
1

ContentGroup.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. enum ContentGroupMatch {
  2. NO_MATCH,
  3. PARTIAL_MATCH,
  4. PERFECT_MATCH
  5. }
  6. interface ContentGroupMatchResult {
  7. type : ContentGroupMatch;
  8. unmatched : Array<ContentUnit>;
  9. }
  10. class ContentGroup {
  11. private units : Array<ContentUnit> = [];
  12. private matching : Array<ContentUnit>;
  13. constructor (...units : Array<ContentUnit>) {
  14. units.forEach(unit => {
  15. this.addUnit(unit);
  16. })
  17. }
  18. public addUnit (unit : ContentUnit) {
  19. this.units.push(unit);
  20. return this;
  21. }
  22. public addDifferentials (...differentials : Array<any>) {
  23. let unit = new ContentUnit();
  24. unit.addCategory(...differentials);
  25. this.addUnit(unit);
  26. return this;
  27. }
  28. public reset () {
  29. this.matching = this.units.slice();
  30. }
  31. public isMatching () {
  32. return this.matching.length;
  33. }
  34. public setMatching (matching : Array<ContentUnit>) {
  35. this.matching = matching;
  36. }
  37. public isMatch (cg : ContentGroup) : ContentGroupMatchResult {
  38. let unmatched = cg.matching.slice();
  39. let matching = this.units.slice();
  40. for (let i = matching.length - 1; i >= 0; i--) {
  41. for (let k = unmatched.length - 1; k >= 0; k--) {
  42. if (matching[i].isMatch(unmatched[k])) {
  43. unmatched.splice(k, 1);
  44. matching.splice(i, 1);
  45. break;
  46. }
  47. }
  48. }
  49. return {
  50. type : matching.length > 0 ? ContentGroupMatch.NO_MATCH :
  51. unmatched.length == 0 ? ContentGroupMatch.PERFECT_MATCH :
  52. ContentGroupMatch.PARTIAL_MATCH,
  53. unmatched : unmatched
  54. }
  55. }
  56. public getScore () {
  57. let score = 0;
  58. this.units.forEach(unit => {
  59. score += unit.getScore();
  60. });
  61. return score;
  62. }
  63. public matchAgainst (a : Array<ContentGroup>) : Array<number> {
  64. let matches = [];
  65. this.reset();
  66. for (let i = 0; i < a.length; i++) {
  67. let match = a[i].isMatch(this);
  68. if (match.type != ContentGroupMatch.NO_MATCH) {
  69. matches.push(i);
  70. this.setMatching(match.unmatched);
  71. }
  72. if (!this.isMatching()) {
  73. return matches;
  74. }
  75. }
  76. return undefined;
  77. }
  78. public getLength () {
  79. return this.units.length;
  80. }
  81. public getUnit (n : number) {
  82. return this.units[n];
  83. }
  84. }