<commit_before><commit_msg>added some extensions for typed arrays.<commit_after>package com.commonsense.android.kotlin.android.extensions

import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.support.annotation.StyleRes
import android.support.v7.content.res.AppCompatResources

/**
 * Created by kasper on 29/05/2017.
 */


fun TypedArray.getDrawableSafe(@StyleRes style: Int, context: Context): Drawable? {
    return ifHaveOrNull(style) {
        val defValue = -1
        @DrawableRes
        val drawableRes = getResourceId(style, defValue)
        if (drawableRes != defValue) {
            return@ifHaveOrNull AppCompatResources.getDrawable(context, drawableRes)
        }
        return@ifHaveOrNull null
    }
}

fun TypedArray.getTextSafe(@StyleRes style: Int): CharSequence? {
    return ifHaveOrNull(style) {
        return@ifHaveOrNull getText(style)
    }
}


inline fun <T> TypedArray.ifHaveOrNull(@StyleRes style: Int, crossinline actionIf: () -> T?): T? {
    if (hasValue(style)) {
        return actionIf()
    }
    return null
}
{'fraction_non_alphanumeric': 0.09940017137960583, 'fraction_numerical': 0.00856898029134533, 'mean_word_length': 3.76734693877551, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2150396', 'n_tokens_mistral': 349, 'n_tokens_neox': 344, 'n_words': 74}