diff --git a/src/main/kotlin/ArrayExtensions.kt b/src/main/kotlin/ArrayExtensions.kt new file mode 100644 index 0000000..2b7b9dd --- /dev/null +++ b/src/main/kotlin/ArrayExtensions.kt @@ -0,0 +1,37 @@ +package main.kotlin + +inline fun print2DArray(twoDArray: Array>) { + for (i in 0 until twoDArray.size) { + for (j in 0 until twoDArray[i].size) { + print(twoDArray[i][j]) + if (j != twoDArray[i].size - 1) print(" ") + } + if (i != twoDArray.size - 1) println() + } +} + + +inline fun print1DArray(twoDArray: Array) { + for (i in 0 until twoDArray.size) { + print("${twoDArray[i]}") + if (i != twoDArray.size - 1) print(" ") + } +} + +fun Array.isEvery(action: (T) -> Boolean): Boolean { + for (element in this) { + if (!action(element)) { + return false + } + } + return true +} + +fun Array.isSome(action: (T) -> Boolean): Boolean { + for (element in this) { + if (action(element)) { + return true + } + } + return false +} \ No newline at end of file diff --git a/src/test/kotlin/ArrayExtensionSpec.kt b/src/test/kotlin/ArrayExtensionSpec.kt new file mode 100644 index 0000000..8b56126 --- /dev/null +++ b/src/test/kotlin/ArrayExtensionSpec.kt @@ -0,0 +1,85 @@ +import main.kotlin.isEvery +import main.kotlin.isSome +import main.kotlin.print1DArray +import main.kotlin.print2DArray +import org.junit.Before +import org.junit.Test +import java.io.PrintStream +import java.io.ByteArrayOutputStream +import org.junit.After +import org.junit.Assert.assertEquals + + +class ArrayExtensionSpec { + + private val outContent = ByteArrayOutputStream() + private val originalOut = System.out + + @Before + fun setUp() { + System.setOut(PrintStream(outContent)) + } + + @Test + fun shouldPrint2dArray() { + val twoDArray = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6,7)) + print2DArray(twoDArray) + + val twoDArrayString = outContent.toString() + + outContent.reset() + + val oneDArray = arrayOf(1, 2, 3) + print1DArray(oneDArray) + + val oneDArrayString = outContent.toString() + + assertEquals("1 2 3\n4 5 6 7", twoDArrayString) + assertEquals("1 2 3", oneDArrayString) + } + + @Test + fun shouldReturnTrueIfEveryElementPassesThePredicate() { + val array = arrayOf(4,6,8) + + val result = array.isEvery { + it % 2 == 0 + } + assertEquals(true, result) + } + + @Test + fun shouldReturnFalseIfEveryElementDoesNotPassesThePredicate() { + val array = arrayOf(5,6,8) + + val result = array.isEvery { + it % 2 == 0 + } + assertEquals(false, result) + } + + @Test + fun shouldReturnTrueIfSomeElementPassesThePredicate() { + val array = arrayOf(1,6,7) + + val result = array.isSome { + it % 2 == 0 + } + assertEquals(true, result) + } + + @Test + fun shouldReturnFalseIfNoElementPassesThePredicate() { + val array = arrayOf(5,7,9) + + val result = array.isSome { + it % 2 == 0 + } + assertEquals(false, result) + } + + @After + fun restoreStreams() { + System.setOut(originalOut) + } +} \ No newline at end of file