From 5f1acf3c66d9e128883a7a54409a08a42ab9ea05 Mon Sep 17 00:00:00 2001 From: Stephen Blott Date: Fri, 18 Mar 2016 06:12:55 +0000 Subject: Add Utils.makeIdempotent. The intention is to use this to clean up some of the initialisation sequences in the front end. --- lib/utils.coffee | 4 ++++ tests/unit_tests/utils_test.coffee | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/utils.coffee b/lib/utils.coffee index 9969811a..31f4bec6 100644 --- a/lib/utils.coffee +++ b/lib/utils.coffee @@ -236,6 +236,10 @@ Utils = # Like Nodejs's nextTick. nextTick: (func) -> @setTimeout 0, func + # Make an idempotent function. + makeIdempotent: (func) -> + (args...) -> ([previousFunc, func] = [func, null])[0]? args... + # Utility for parsing and using the custom search-engine configuration. We re-use the previous parse if the # search-engine configuration is unchanged. SearchEngines = diff --git a/tests/unit_tests/utils_test.coffee b/tests/unit_tests/utils_test.coffee index 67c3b333..9b71ca72 100644 --- a/tests/unit_tests/utils_test.coffee +++ b/tests/unit_tests/utils_test.coffee @@ -102,3 +102,26 @@ context "compare versions", assert.equal -1, Utils.compareVersions("1.40.1", "1.40.2") assert.equal -1, Utils.compareVersions("1.40.1", "1.41") assert.equal 1, Utils.compareVersions("1.41", "1.40") + +context "makeIdempotent", + setup -> + @count = 0 + @func = Utils.makeIdempotent (n = 1) => @count += n + + should "call a function once", -> + @func() + assert.equal 1, @count + + should "call a function once with an argument", -> + @func 2 + assert.equal 2, @count + + should "not call a function a second time", -> + @func() + assert.equal 1, @count + + should "not call a function a second time", -> + @func() + assert.equal 1, @count + @func() + assert.equal 1, @count -- cgit v1.2.3