changeset 5693:9e9cedae718a sr-v2

Add inverse funtion to delta.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Mon, 12 Feb 2024 14:38:10 +0100
parents d920f0fa2f04
children 3bc15e38c7e8
files pkg/common/delta.go pkg/common/delta_test.go
diffstat 2 files changed, 54 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/pkg/common/delta.go	Mon Feb 12 13:53:32 2024 +0100
+++ b/pkg/common/delta.go	Mon Feb 12 14:38:10 2024 +0100
@@ -17,16 +17,21 @@
 // the first time and the delta to the last call afterwards.
 func Delta() func(int64) int64 {
 	var last int64
-	first := true
 	return func(x int64) (y int64) {
-		if first {
-			first = false
-			y = x
-			last = x
-		} else {
-			y = x - last
-			last = x
-		}
+		y = x - last
+		last = x
 		return
 	}
 }
+
+// InvDelta is the inverse function to Delta. A squence of numbers
+// fed into the function generated by InvDelta restores
+// the values fed into the function generated by Delta.
+func InvDelta() func(int64) int64 {
+	var last int64
+	return func(x int64) (y int64) {
+		y = x + last
+		last = y
+		return
+	}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkg/common/delta_test.go	Mon Feb 12 14:38:10 2024 +0100
@@ -0,0 +1,40 @@
+// This is Free Software under GNU Affero General Public License v >= 3.0
+// without warranty, see README.md and license for details.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// License-Filename: LICENSES/AGPL-3.0.txt
+//
+// Copyright (C) 2024 by via donau
+//   – Österreichische Wasserstraßen-Gesellschaft mbH
+// Software engineering by Intevation GmbH
+//
+// Author(s):
+//  * Sascha L. Teichmann <sascha.teichmann@intevation.de>
+
+package common
+
+import "testing"
+
+func TestDelta(t *testing.T) {
+	var (
+		input = []int64{1, 2, 3, 2, 1}
+		want  = []int64{1, 1, 1, -1, -1}
+	)
+	delta := Delta()
+	for i, in := range input {
+		if got := delta(in); got != want[i] {
+			t.Errorf("input %d: got %d expected %d", in, got, want[i])
+		}
+	}
+}
+
+func TestInvDelta(t *testing.T) {
+	input := []int64{1, 2, 3, 2, 1, -10, 100}
+	delta := Delta()
+	invDelta := InvDelta()
+	for _, in := range input {
+		if got := invDelta(delta(in)); got != in {
+			t.Errorf("input %d: got %d expected %d", in, got, in)
+		}
+	}
+}