@@ -24,10 +24,35 @@ data class CounterOptions internal constructor(
24
24
internal typealias IncFn = (Int ) -> Unit
25
25
internal typealias DecFn = (Int ) -> Unit
26
26
27
+ /* *
28
+ * Use counter
29
+ *
30
+ * @param initialValue initial value of count
31
+ * @param options
32
+ * @return
33
+ *
34
+ * 在使用第三个解构值[SetValueFn]时,如果你想传入的是数值则使用 [left] 函数, 如果想传入的是函数 则使用 [right]
35
+ * 函数,也可以手动导入[invoke]来优化使用体验。
36
+ *
37
+ * When using the third destructured value [SetValueFn], if you want to
38
+ * pass in a numerical value, use the [left] function. If you want to pass
39
+ * in a function, use the [right] function. You can also manually import
40
+ * [invoke] to optimize the user experience.
41
+ *
42
+ * ```
43
+ * set(3.left())
44
+ * set({value:Int ->
45
+ * value/3
46
+ * }.right())
47
+ * ```
48
+ */
27
49
@Composable
28
- fun useCounter (initialValue : Int = 0, options : CounterOptions ): Tuple5 <Int , IncFn , DecFn , SetValueFn <Either <Int , (Int ) - > Int >>, ResetFn> {
50
+ fun useCounter (
51
+ initialValue : Int = 0,
52
+ options : CounterOptions ,
53
+ ): Tuple5 <Int , IncFn , DecFn , SetValueFn <Either <Int , (Int ) - > Int >>, ResetFn> {
29
54
val (current, setCurrent, getCurrent) = useGetState(getTargetValue(initialValue, options))
30
- fun setValue ( value : Either <Int , (Int ) - > Int >) {
55
+ val setValue: SetValueFn < Either < Int , ( Int ) - > Int >> = { value: Either <Int , (Int ) - > Int > ->
31
56
val target = value.fold(
32
57
ifLeft = { it },
33
58
ifRight = { it(getCurrent()) }
@@ -36,18 +61,19 @@ fun useCounter(initialValue: Int = 0, options: CounterOptions): Tuple5<Int, IncF
36
61
}
37
62
38
63
fun inc (delta : Int ) {
39
- setValue( { c: Int -> c + delta }.right())
64
+ setValue { c: Int -> c + delta }
40
65
}
41
66
42
67
fun dec (delta : Int ) {
43
- setValue( { c: Int -> c - delta }.right())
68
+ setValue { c: Int -> c - delta }
44
69
}
45
70
46
71
fun set (value : Either <Int , (Int ) - > Int >) {
47
72
setValue(value)
48
73
}
74
+
49
75
fun reset () {
50
- setValue(initialValue.left() )
76
+ setValue(initialValue)
51
77
}
52
78
53
79
return Tuple5 (
@@ -63,3 +89,7 @@ private fun getTargetValue(value: Int, options: CounterOptions): Int {
63
89
val (min, max) = options
64
90
return value.coerceIn(min, max)
65
91
}
92
+
93
+ operator fun SetValueFn <Either <Int , (Int ) - > Int>>.invoke (leftValue : Int ) = this (leftValue.left())
94
+ operator fun SetValueFn <Either <Int , (Int ) - > Int>>.invoke (rightValue : (Int ) -> Int ) =
95
+ this (rightValue.right())
0 commit comments