Wednesday, August 19, 2015

string.format() modified

Make the below examples work for string.format() method.
"{} is a {meta-for-test}".format("this", "test")
    => "this is a test"
"the name is {last}. {first} {last}.".format("bond", "james")
    => "the name is bond. james bond."
For the built-in string.format(), the below formats work.
string.format("{0} is a {1}",  "this", "test")
    => "this is a test"
string.format("the name is {0}. {1} {0}.",  "bond", "james")
    => "the name is bond. james bond."
The code works by converting the formats into the workable ones and delegating to the built-in string.format() method.
format(format, args):
    buffer = new buffer(format)
    i = 0
    param = 0
    metatoparamMap = new
    while i < buffer.length:
        // stop at { or }
        while i < buffer.length && buffer[i] != '{' && != '}':
            i++
        // no more left
        if i == buffer.length:
            break
        // escaped {{ or }}
        if i +1 < buffer.length && buffer[i] == buffer[i+1]:
            i += 2
            continue
        // } before {
        if buffer[i] == '}':
            break
        start = i
        // stop at }
        while i < buffer.length && buffer[i] != '}':
            i++
        // { not matched
        if i == buffer.length:
            break
        end = i
        // get meta substring
        metastart = metaend = start+1
        // ',' and ':' are special formatting chars
        while buffer[metaend] != '}' && != ',' && != ':':
            metaend++
        meta = buffer.substring(metastart, metaend-metastart)
        increment = true
        // insert param only if meta is not int
        if !int.tryparse(meta):
            buffer.remove(metastart, meta.length)
            metakey = meta.trim()
            // if meta is in meta->paramindex map, reuse the index
            if metatoparamMap.has(metakey):
                paramindex = metatoparamMap[metakey]
                // do not increment param index as reusing
                increment = false
            else:
                paramindex = param.tostring()
                // put in meta->paramindex map
                if metakey != "":
                    metatoparamMap[metakey] = paramindex
            buffer.insert(metastart, paramindex)
            // adjust end as buffer is inserted/removed
            end += -meta.length +paramindex.length
        // increment param even if index is not inserted
        if increment:
            param++
        i = end +1 // i++ does not work
    return string.format(buffer.tostring(), args)

No comments:

Post a Comment