public
Created

Coding challenge: a sliding window map

  • Download Gist
SlidingWindowMap.groovy
Groovy
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
import java.util.concurrent.DelayQueue
import java.util.concurrent.Delayed
import java.util.concurrent.TimeUnit
 
class SlidingWindowMap {
private periodMs
private available = new DelayQueue<DelayedKey<String>>()
SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
this.periodMs = periodMs
keys.each { key -> maxCount.times { available << new DelayedKey<String>(payload: key) } }
}
 
/**
* @return a key that has been used less than `maxCount` times during the
* past `periodMs` milliseconds or null if no such key exists.
*/
String getNextKey() {
def delayedKey = available.poll()
if (delayedKey) available << delayedKey.blockFor(periodMs)
return delayedKey?.payload
}
 
}
 
class DelayedKey<T> implements Delayed {
T payload
long targetTimestamp
long getDelay(TimeUnit unit) { unit.convert(targetTimestamp - System.currentTimeMillis(), TimeUnit.MILLISECONDS) }
int compareTo(Delayed o) { getDelay(TimeUnit.MILLISECONDS) <=> o.getDelay(TimeUnit.MILLISECONDS) }
DelayedKey<T> blockFor(long delayMs) {
targetTimestamp=System.currentTimeMillis() + delayMs
return this
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.