flutter_input_library/lib/src/inputs/carousel/carousel_utils.dart

29 lines
1.1 KiB
Dart
Raw Normal View History

2022-11-29 13:16:44 +01:00
// SPDX-FileCopyrightText: 2022 Iconica
//
// SPDX-License-Identifier: BSD-3-Clause
/// Converts an index of a set size to the corresponding index of a collection
2024-02-02 11:48:45 +01:00
/// of another size as if they were circular.
2022-11-29 13:16:44 +01:00
///
/// Takes a [position] from collection Foo, a [base] from where Foo's index
/// originated and the [length] of a second collection Baa, for which the
2024-02-02 11:48:45 +01:00
/// correlating index is sought.
2022-11-29 13:16:44 +01:00
///
/// For example; We have a Carousel of 10000(simulating infinity) but only 6
/// images. We need to repeat the images to give the illusion of a never
/// ending stream. By calling [getRealIndex] with position and base we get
/// an offset. This offset modulo our length, 6, will return a number between
2024-02-02 11:48:45 +01:00
/// 0 and 5, which represent the image to be placed in the given position.
2022-11-29 13:16:44 +01:00
int getRealIndex(int position, int base, int? length) {
2024-02-02 11:48:45 +01:00
var offset = position - base;
2022-11-29 13:16:44 +01:00
return remainder(offset, length);
}
2024-02-02 11:48:45 +01:00
/// Returns the remainder of the modulo operation [input] % [source], and adjust
/// it for negative values.
2022-11-29 13:16:44 +01:00
int remainder(int input, int? source) {
if (source == 0) return 0;
2024-02-02 11:48:45 +01:00
var result = input % source!;
2022-11-29 13:16:44 +01:00
return result < 0 ? source + result : result;
}