public
Created

Coding challenge: a sliding window map. Quick dummy impl on Java.

  • Download Gist
SlidingWindowMap.java
Java
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
 
/**
* @author Stanislav Kurilin
*/
public class SlidingWindowMap {
private final Set<String> keys;
private final int maxCount;
private final long periodMs;
 
private long periodStart;
private int countOnPeriod;
private Iterator<String> it;
private String currentKey;
 
public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
this.keys = keys;
this.maxCount = maxCount;
this.periodMs = periodMs;
periodStart = current();
it = keys.iterator();
}
 
/**
* @return a key that has been used less than `maxCount` times during the
* past `periodMs` milliseconds or null if no such key exists.
*/
public String getNextKey() {
if (timeToStartNewPeriod()) beginNewPeriod();
if (currentKeyIsValid()) return currentKey();
if (thereAreValidKeys()) return newValidKey();
return null;
}
 
/**
* @return current ms
*/
private long current() {
return new Date().getTime();
}
 
/**
* @return true if new period should begin false otherwise
*/
private boolean timeToStartNewPeriod() {
return current() - periodStart > periodMs;
}
 
/**
* reinitialize counters
*/
private void beginNewPeriod() {
periodStart = current();
countOnPeriod = 0;
it = keys.iterator();
}
 
/**
* @return true if current key steel valid
*/
private boolean currentKeyIsValid() {
return countOnPeriod < maxCount;
}
 
/**
* @return current key
*/
private String currentKey() {
countOnPeriod++;
return currentKey;
}
 
/**
* @return true if there are valid keys available
*/
private boolean thereAreValidKeys() {
return it.hasNext();
}
 
/**
* @return new valid key
* @throws java.util.NoSuchElementException if not available
*/
private String newValidKey() {
currentKey = it.next();
return currentKey;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.