# HG changeset patch # User Sascha L. Teichmann # Date 1707745090 -3600 # Node ID 9e9cedae718a4a8336ff12e847409276b8847edf # Parent d920f0fa2f04ab3ac5465a7f13c1cbafde9d8ad5 Add inverse funtion to delta. diff -r d920f0fa2f04 -r 9e9cedae718a pkg/common/delta.go --- 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 + } +} diff -r d920f0fa2f04 -r 9e9cedae718a pkg/common/delta_test.go --- /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 + +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) + } + } +}