Skip to content
This repository has been archived by the owner on Aug 24, 2021. It is now read-only.

#53 feat: add distinct operator and tests #290

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.github.jcornaz.kwik.generator.api
import kotlin.random.Random

private const val DEFAULT_SAMPLE_PROBABILITY = 0.2
private const val MAX_DISTINCT_TRIES = 100

/**
* Returns a generator containing the results of applying the given transform function to each element emitted by
Expand Down Expand Up @@ -40,6 +41,31 @@ public fun <T> Generator<T>.filter(predicate: (T) -> Boolean): Generator<T> =
public fun <T, R> Generator<T>.andThen(transform: (T) -> Generator<R>): Generator<R> =
Generator { transform(generate(it)).generate(it) }

/**
* Returns a generator that emits items of the upstream generator only once (based on result of `hashCode` and `equals` method)
*
* Be sure to use a generator function that can generate a big set of values
* Be sure to not overuse it has it may slow down your tests
*/
public fun <T> Generator<T>.distinct(): Generator<T> {
var generatedValues = mutableListOf<T>()
return Generator {
var retries = 0
val genSize = generatedValues.size
generatedValues.add(generate(it))
generatedValues = generatedValues.toMutableSet().toMutableList()
while (genSize == generatedValues.size) {
if (retries > MAX_DISTINCT_TRIES) {
throw Exception("Number of retries exceeded maximum. Distinct cannot be applied to this resource")
}
generatedValues.add(generate(it))
generatedValues = generatedValues.toMutableSet().toMutableList()
retries++
}
generatedValues.last()
}
}

/**
* @Deprecated Use `andThen` operator instead
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.github.jcornaz.kwik.generator.api

import com.github.jcornaz.kwik.generator.test.AbstractGeneratorTest
import kotlin.math.absoluteValue
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertTrue

class DistinctTest : AbstractGeneratorTest() {
override val generator: Generator<String> = Generator { it: Random -> it.nextInt() }.map { it.toString() }

companion object {
const val COLLISION_TAKEN_VALUES = 2000
}

@Test
fun applyDistinction() {
val gen: Generator<Int> = Generator { it.nextInt().absoluteValue / 2000 }

// sequence known to produce collisions
val result = gen.distinct().randomSequence(1).take(COLLISION_TAKEN_VALUES)
assertTrue { COLLISION_TAKEN_VALUES == result.toList().size }

}
}