Last active
August 29, 2015 14:26
-
-
Save pathikrit/79ad500a6b31f62ab4e8 to your computer and use it in GitHub Desktop.
Debounce in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import scala.compat.Platform.{currentTime => now} | |
| import scala.concurrent.duration.FiniteDuration | |
| import java.util.concurrent.atomic.AtomicBoolean | |
| /** | |
| * Debounce a function i.e. it can only be invoked iff it is not already running | |
| * and atleast wait duration has passed since it last stopped running | |
| * Usage: | |
| * def test(i: Int) = println(i) | |
| * val f = debounce(1.second)(test) | |
| * (0 to 1e9.toInt).par.map(f) | |
| * | |
| * @return a function such that it returns Some(original output) if it was invoked | |
| * or else if it failed to run because of above rules, None | |
| */ | |
| def debounce[A, B](wait: FiniteDuration)(f: A => B): A => Option[B] = { | |
| var (isRunning, lastStopTime) = (new AtomicBoolean(false), Long.MinValue) | |
| (input: A) => { | |
| val doneWaiting = lastStopTime + wait.toMillis <= now | |
| if (isRunning.compareAndSet(false, doneWaiting) && doneWaiting) { | |
| try { | |
| Some(f(input)) | |
| } finally { | |
| lastStopTime = now | |
| isRunning.set(false) | |
| } | |
| } else { | |
| None | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment