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'. |
|||
⚫ | |||
⚫ | |||
⚫ | |||
return rs |
|||
} |
} |
||
// Returns 's' repeated 'reps' times. |
// Returns 's' repeated 'reps' times. |
||
⚫ | |||
// 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 |
Fiber.abort("Repetitions must be a non-negative integer.") |
||
} |
} |
||
⚫ | |||
if (!(chunkSize is Num && chunkSize.isInteger && chunkSize > 0)) { |
|||
⚫ | |||
Fiber.abort("Chunk size must be a positive integer.") |
|||
⚫ | |||
} |
|||
⚫ | |||
var chunks = (reps/chunkSize).floor |
|||
if (chunks == 0) return repeat_(s, reps) |
|||
var lastSize = reps % chunkSize |
|||
if (lastSize == 0) { |
|||
lastSize = chunkSize |
|||
} else { |
} else { |
||
while (true) { |
|||
if (reps % 2 == 1) rs = rs + s |
|||
} |
|||
reps = reps >> 1 |
|||
if (reps == 0) break |
|||
s = s + s |
|||
} |
|||
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. |