Groovy web console

subscribe to the feed Subscribe
to this
site

sct cbc ordercode

Published 4 months ago by tk
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
System.out.println("orderCode : " + generateUniqueOrderCode())

private String generateUniqueOrderCode() {    
    int min = 100000000
    int max = 999999999

    String result = null
    int tries = 0
    while (!result) {
        int randomCode = new Random().nextInt(max + 1 - min) + min
        System.out.println("randomCode: " + randomCode)
        String orderCode = buildOrderCode(randomCode as String)
        //if (!Order.findByOrderCode(orderCode)) {
            result = orderCode
        //}
        tries++
    }

    return result
}

private String buildOrderCode(String plainOrderCode) {
    StringBuilder builder = new StringBuilder()
    String insert = ' '
    int period = 2

    int index = 0
    String prefix = ""
    while (index < plainOrderCode.length()) {
        builder.append(prefix)
        prefix = insert
        builder.append(plainOrderCode.substring(index, Math.min(index + period, plainOrderCode.length())))
        index += period
    }
    return builder.toString()
}