Question

I am unable to use the fabulous tr() at the moment as I can only use Groovy 1.7.1 and wanted to know if there is an elegant way of going backwards and forwards between string and number encoded with Base32, but with the values A to Z then 2 to 7, rather than 0 to 9 then A to V.

This is to remove customer error in typing in a human readable code by not using zero or one.

I can think of 72 Regex expressions that would enable this, but that seems like overkill when

tr( 'A-Z2-7', 0-9A-V')

is SO much easier

Was it helpful?

Solution

The beauty of Groovy is its dynamic nature. If you need the feature, but it's not there, add it! Somewhere in a convenient entry point to your application, or in a static block in the class that needs it, add the code lifted straight from the 1.7.3+ sources:

String.metaClass.'static'.tr = { String text, String source, String replacement ->
    if (!text || !source) { return text }
    source = expandHyphen(source)
    replacement = expandHyphen(replacement)

    // padding replacement with a last character, if necessary
    replacement = replacement.padRight(source.size(), replacement[replacement.size() - 1])

    return text.collect { original ->
        if (source.contains(original)) {
            replacement[source.lastIndexOf(original)]
        } else {
            original
        }
    }.join()
}


String.metaClass.'static'.expandHyphen = { String text ->
    if (!text.contains('-')) { return text }
    return text.replaceAll(/(.)-(.)/, { all, begin, end -> (begin..end).join() })
}

String.metaClass.tr = { String source, String replacement ->
    String.tr(delegate, source, replacement)
}

The nice thing about this is whenever you can upgrade to 1.7.3, you can just remove this meta-magic and you won't need to change your other sources.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top