Skip to content

Commit 8ec38f6

Browse files
committed
Add Callback.{log,with}Duration
1 parent 2e5fab0 commit 8ec38f6

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

core/src/main/scala/japgolly/scalajs/react/Callback.scala

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package japgolly.scalajs.react
33
import org.scalajs.dom.console
44
import scala.annotation.implicitNotFound
55
import scala.concurrent.{Future, Promise}
6-
import scala.concurrent.duration.FiniteDuration
6+
import scala.concurrent.duration.{FiniteDuration, MILLISECONDS}
77
import scala.scalajs.js
88
import js.{undefined, UndefOr, Function0 => JFn0, Function1 => JFn1}
99
import js.timers.RawTimers
@@ -248,11 +248,19 @@ final class CallbackTo[A] private[react] (private[CallbackTo] val f: () => A) ex
248248
b <- cb
249249
} yield (a, b)
250250

251+
/**
252+
* Discard the callback's return value, return a given value instead.
253+
*
254+
* `ret`, short for `return`.
255+
*/
256+
def ret[B](b: B): CallbackTo[B] =
257+
map(_ => b)
258+
251259
/**
252260
* Discard the value produced by this callback.
253261
*/
254262
def void: Callback =
255-
map(_ => ())
263+
ret(())
256264

257265
def conditionally(cond: => Boolean): CallbackTo[Option[A]] =
258266
CallbackTo(if (cond) Some(f()) else None)
@@ -385,6 +393,41 @@ final class CallbackTo[A] private[react] (private[CallbackTo] val f: () => A) ex
385393
p.future
386394
}
387395

396+
/**
397+
* Record the duration of this callback's execution.
398+
*/
399+
def withDuration[B](f: (A, FiniteDuration) => CallbackTo[B]): CallbackTo[B] = {
400+
@inline def nowMS: Long = System.currentTimeMillis()
401+
CallbackTo {
402+
val s = nowMS
403+
val a = runNow()
404+
val e = nowMS
405+
val d = FiniteDuration(e - s, MILLISECONDS)
406+
f(a, d).runNow()
407+
}
408+
}
409+
410+
/**
411+
* Log the duration of this callback's execution.
412+
*/
413+
def logDuration(fmt: FiniteDuration => String): CallbackTo[A] =
414+
withDuration((a, d) =>
415+
Callback.log(fmt(d)) ret a)
416+
417+
/**
418+
* Log the duration of this callback's execution.
419+
*
420+
* @param name Prefix to appear the log output.
421+
*/
422+
def logDuration(name: String): CallbackTo[A] =
423+
logDuration(d => s"$name completed in $d.")
424+
425+
/**
426+
* Log the duration of this callback's execution.
427+
*/
428+
def logDuration: CallbackTo[A] =
429+
logDuration("Callback")
430+
388431
def asCBO[B](implicit ev: This =:= CallbackTo[Option[B]]): CallbackOption[B] =
389432
CallbackOption(ev(this))
390433

0 commit comments

Comments
 (0)