Skip to content

@st-kurilin /SlidingWindowMap.java
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Coding challenge: a sliding window map. Quick dummy impl on Java.
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.