Category talk:Wren-str: Difference between revisions

Content added Content deleted
(Added Str.fromBytes and Str.fromCodePoints methods. Removed type aliases which are no longer needed.)
(→‎Source code: Replaced Str.repeat method with a much more efficient version.)
Line 364: Line 364:
chars[j] = t
chars[j] = t
return Strs.concat(chars)
return Strs.concat(chars)
}

// Private helper method for 'repeat'.
static repeat_(s, reps) {
var rs = ""
for (i in 0...reps) rs = rs + s
return rs
}
}


// Returns 's' repeated 'reps' times.
// Returns 's' repeated 'reps' times.
static repeat(s, reps) {
// If 'chunkSize' is chosen appropriately, this should be much faster than String's * operator
// for a large number of repetitions.
static repeat(s, reps, chunkSize) {
if (!(s is String)) s = "%(s)"
if (!(s is String)) s = "%(s)"
if (!(reps is Num && reps.isInteger && reps > 0)) {
if (!(reps is Num && reps.isInteger && reps >= 0)) {
Fiber.abort("Repetitions must be a positive integer.")
Fiber.abort("Repetitions must be a non-negative integer.")
}
}
var rs = ""
if (!(chunkSize is Num && chunkSize.isInteger && chunkSize > 0)) {
if (reps < 10) {
Fiber.abort("Chunk size must be a positive integer.")
for (i in 0...reps) rs = rs + s
}
if (reps == 0) return ""
var chunks = (reps/chunkSize).floor
if (chunks == 0) return repeat_(s, reps)
var lastSize = reps % chunkSize
if (lastSize == 0) {
lastSize = chunkSize
} else {
} else {
chunks = chunks + 1
while (true) {
if (reps % 2 == 1) rs = rs + s
}
var rs = ""
reps = reps >> 1
var chunk = repeat_(s, chunkSize)
if (reps == 0) break
var lastChunk = repeat_(s, lastSize)
s = s + s
for (i in 0...chunks) {
}
rs = rs + ((i < chunks - 1) ? chunk : lastChunk)
}
}
return rs
return rs
}
}

// Convenience version of the above which uses a 'chunkSize' of 8000. This usually gives a good result.
static repeat(s, reps) { repeat(s, reps, 8000) }


// Splits a string 's' into chunks of not more than 'size' characters.
// Splits a string 's' into chunks of not more than 'size' characters.