Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

69
LINES

< > BotCompany Repo | #1033886 // class Best_comparable - takes objects and scores (comparables) and keeps the highest-scoring object. now synchronized and persistable

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (4977L/28K).

sclass Best_comparable<A> {
  A best;
  Comparable score;
  bool verboseNewBest, replaceIfSameScore;
  
  transient O onChange;
  transient O stringifier; // func(A) -> S
  
  synchronized bool isNewBest(Comparable score) {
    ret this.score == null
      || (replaceIfSameScore
        ? cmp(score, this.score) >= 0
        : cmp(score, this.score) > 0);
  }
  
  synchronized Comparable bestScore() {
    ret score;
  }
  
  Comparable score() { ret bestScore(); }
  Comparable getScore() { ret bestScore(); }
  
  synchronized float floatScoreOr(float defaultValue) {
    ret best == null ? defaultValue : (float) score;
  }
  
  bool put(Pair<? extends A, Comparable> p) {
    ret p != null && put(p.a, p.b);
  }
  
  bool put(Best<? extends A> b) {
    ret b != null && put(b!, b.score);
  }
  
  bool put(A a, Comparable score) {
    ping();
    bool change;
    if (a != null) synchronized(this) {
      if (isNewBest(score)) {
        best = a;
        this.score = score;
        set change;
      }
    }
    if (change) {
      if (verboseNewBest) print("New best! " + this);
      pcallF(onChange);
    }
    ret change;
  }
  
  synchronized A get() { ret best; }
  synchronized bool has() { ret best != null; }
  
  synchronized Pair<A, Comparable> pair() { ret main pair(best, bestScore()); }

  synchronized A getIfScoreAbove(Comparable x) { ret cmp(x, score()) >= 0 ? best : null; }
  
  toString {
    ret !has() ? "-" : "Score " + score + ": " + callStringifier(stringifier, best);
  }
  
  bool putAndPrintIfNewBest(A a, Comparable score) {
    if (!put(a, score)) false;
    ret true with print(this);
  }
  
  synchronized void clear() { best = null; score = 0; }
}

Author comment

Began life as a copy of #1006090

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, ekrmjmnbrukm, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1033886
Snippet name: class Best_comparable - takes objects and scores (comparables) and keeps the highest-scoring object. now synchronized and persistable
Eternal ID of this version: #1033886/3
Text MD5: ef7eb1157be733b8edfa05e5fc6fdb3a
Transpilation MD5: 614b8423e104e221c08cfa333491f100
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-01-08 22:56:54
Source code size: 1756 bytes / 69 lines
Pitched / IR pitched: No / No
Views / Downloads: 71 / 132
Version history: 2 change(s)
Referenced in: [show references]