Skip to content
This repository has been archived by the owner on Apr 16, 2023. It is now read-only.

Commit

Permalink
Add function to simplify either arguments of similar type
Browse files Browse the repository at this point in the history
  • Loading branch information
BartArys authored and HopeBaron committed Sep 2, 2020
1 parent 87334e5 commit f312024
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# 0.3.0

## Additions

* Added `Argument#flatten` to flatten an `Argument<Either<T,T>, CONTEXT>` into a `Argument<T, CONTEXT>`.

# 0.2.1

## Fixes
Expand All @@ -8,7 +14,6 @@

* CommandProcessor will run commands in parallel.


# 0.2.0

## Changes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,19 @@ import com.gitlab.kordlib.kordx.commands.argument.result.extension.switchOnFail
*/
infix fun <A, B, CONTEXT> Argument<A, CONTEXT>.or(
other: Argument<B, CONTEXT>
): Argument<Either<A,B>, CONTEXT> = EitherArgument(this, other)
): Argument<Either<A, B>, CONTEXT> = EitherArgument(this, other)

fun <T, CONTEXT> Argument<Either<T, T>, CONTEXT>.flatten(): Argument<T, CONTEXT> = object : Argument<T, CONTEXT> {
override val example: String
get() = this@flatten.example

override val name: String
get() = this@flatten.name

override suspend fun parse(words: List<String>, fromIndex: Int, context: CONTEXT): ArgumentResult<T> {
return this@flatten.parse(words, fromIndex, context).map { (it.left ?: it.right)!! }
}
}

/**
* Represents one of two possible values, [left] or [right].
Expand Down Expand Up @@ -73,10 +85,11 @@ sealed class Either<A, B> {
/**
* Gets the present value in either left or right.
*/
val <T, A: T, B:T> Either<A,B>.value get() = when(this) {
is Either.Left -> left
is Either.Right -> right
}
val <T, A : T, B : T> Either<A, B>.value
get() = when (this) {
is Either.Left -> left
is Either.Right -> right
}

private class EitherArgument<A, B, CONTEXT>(
private val left: Argument<A, CONTEXT>,
Expand All @@ -88,8 +101,8 @@ private class EitherArgument<A, B, CONTEXT>(

@Suppress("RemoveExplicitTypeArguments")
override suspend fun parse(words: List<String>, fromIndex: Int, context: CONTEXT): ArgumentResult<Either<A, B>> {
val left: ArgumentResult<Either<A, B>> = left.parse(words, fromIndex, context).map { Either.Left<A,B>(it) }
return left.switchOnFail { right.parse(words, fromIndex, context).map { Either.Right<A,B>(it) } }
val left: ArgumentResult<Either<A, B>> = left.parse(words, fromIndex, context).map { Either.Left<A, B>(it) }
return left.switchOnFail { right.parse(words, fromIndex, context).map { Either.Right<A, B>(it) } }
}

}

0 comments on commit f312024

Please sign in to comment.