1 /***********************************************************************************************
2 *	Copyright: © 2017-2021 UI Manufaktur UG
3 *	License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
4 *	Authors: UI Manufaktur Team
5 *	Documentation [DE]: https://ui-manufaktur.com/docu/uim-core/dataytypes/integral
6 ************************************************************************************************/
7 module uim.core.datatypes.integral;
8 
9 @safe:
10 import uim.core;
11 
12 /// convert integral values to string with defined length
13 string toString(T)(T value, size_t length = 0, string fillTxt = "0") if (isIntegral!T) {
14   string result = fill(length, fillTxt);
15   
16   import std.conv;
17   string convert = to!string(value);
18   if (convert.length < length) {
19     result = result[0..$-convert.length] ~ convert;
20   }
21   else result = convert;  
22 
23   return result;
24 }
25 unittest {
26   assert(1.toString == "1");
27   assert(1.toString == "1");
28   assert(1.toString(10, "X") == "XXXXXXXXX1");
29 }
30 
31 /// limits the value on the min or max 
32 T limits(T)(T value, T minLimit, T maxLimit) if (isIntegral!T) 
33   in(minLimit < maxLimit, "minLimit should not be equal or greater then maxLimit")
34   do {
35     T result = value;
36     
37     if (minLimit > result) result = minLimit;
38     if (result > maxLimit) result = maxLimit;
39     
40     return result;
41   }
42 unittest {
43   assert(10.limit(2, 8) == 8);
44   assert(10.limit(12, 13) == 12);
45   assert(10.limit(13, 13) > 0);
46   assert(10.limit(14, 13) > 0);
47 }
48 
49 /// transform value minOld/maxOld to newMin/newMax 
50 T transform(T)(T value, T minOld, T maxOld, T newMin, T newMax) if (isIntegral!T) 
51   in((value >= minOld) && (value <= maxOld), "value should be between minOld and maxOld")
52   in(minOld < maxOld, "minOld should not be equal or greater then maxOld")
53   in(newMin != newMax, "newMin should not equal to newMax")
54   in(newMin < newMax, "newMin should not be equl or greater then newMax")
55   do {
56     T deltaOld = maxOld - minOld;
57     T deltaNew = newMax - newMin;
58     T result = to!T(newMin + (deltaNew*((100*(value - minOld)) / deltaOld))/100);
59     
60     return result;
61   }
62 unittest {
63   assert(8.transform(0, 10, 0, 100) == 80);
64   assert(80.transform(0, 100, 0, 10) == 8);
65 }
66 
67 pure bool isLess(T)(T base, T[] values...) {
68   foreach(value;values) if (value <= base) return false;
69   return true;  
70 }
71 unittest {
72   assert(8.isLess(10, 100));
73   assert(!80.isLess(10, 100));
74 }
75 
76 pure bool isGreater(T)(T base, T[] values...) {
77   foreach(value; values) if (value >= base) return false;
78   return true; // base is always greater
79 }
80 unittest {
81   assert(800.isGreater(10, 100));
82   assert(!80.isGreater(10, 100));
83 }
84