All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.slink.tsv.tsv.kt Maven / Gradle / Ivy

The newest version!
package io.slink.tsv

import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.nio.charset.Charset

fun InputStream.readTsv(
        commentChar: Char = '#',
        charset: Charset = Charsets.UTF_8,
        processRow: (List) -> Unit,
) {
    BufferedReader(InputStreamReader(this, charset)).useLines {
        it.forEach { line ->
            line.toTsvRow(commentChar)?.let(processRow)
        }
    }
}

fun InputStream.readTsv(commentChar: Char = '#', charset: Charset = Charsets.UTF_8): List> {
    val rows = mutableListOf>()
    readTsv(commentChar, charset) { rows.add(it) }
    return rows
}

fun String.readTsv(commentChar: Char = '#', processRow: (List) -> Unit) {
    split("\n").forEach { line ->
        line.toTsvRow(commentChar)?.let(processRow)
    }
}

fun String.readTsv(commentChar: Char = '#'): List> {
    val rows = mutableListOf>()
    readTsv(commentChar) { rows.add(it) }
    return rows
}

fun InputStream.readTsvWithHeader(
        commentChar: Char = '#',
        charset: Charset = Charsets.UTF_8,
        processRow: (Map) -> Unit,
) {
    var headers: List? = null
    BufferedReader(InputStreamReader(this, charset)).useLines {
        it.forEach { line ->
            if (headers == null) {
                headers = line.toTsvRow(commentChar)
            } else {
                line.toTsvRow(headers!!, commentChar)?.let(processRow)
            }
        }
    }
}

fun InputStream.readTsvWithHeader(commentChar: Char = '#', charset: Charset = Charsets.UTF_8): List> {
    val rows = mutableListOf>()
    readTsvWithHeader(commentChar, charset) { rows.add(it) }
    return rows
}

fun String.readTsvWithHeader(
        commentChar: Char = '#',
        processRow: (Map) -> Unit
) {
    var headers: List? = null
    split("\n").forEach { line ->
        if (headers == null) {
            headers = line.toTsvRow(commentChar)
        } else {
            line.toTsvRow(headers!!, commentChar)?.let(processRow)
        }
    }
}

fun String.readTsvWithHeader(commentChar: Char = '#'): List> {
    val rows = mutableListOf>()
    readTsvWithHeader(commentChar) { rows.add(it) }
    return rows
}

private fun String.toTsvRow(commentChar: Char): List? {
    val row = this.trim()
    return if (row.isNotEmpty() && row[0] != commentChar) {
        row.split("\t")
    } else {
        null
    }
}

private fun String.toTsvRow(headers: List, commentChar: Char): Map? {
    return toTsvRow(commentChar)
            ?.mapIndexed { index, element ->
                headers[index] to element
            }
            ?.toMap()
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy