Skip to content

Commit

Permalink
chore(stdlib): Optimize Array.join (#1948)
Browse files Browse the repository at this point in the history
  • Loading branch information
spotandjake authored Jan 25, 2024
1 parent 4fe2e52 commit f5100d3
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions stdlib/array.gr
Original file line number Diff line number Diff line change
Expand Up @@ -884,17 +884,30 @@ provide let unzip = array => {
*
* @since v0.4.0
*/
@unsafe
provide let join = (separator: String, items: Array<String>) => {
let iter = (acc, str) => {
match (acc) {
None => Some(str),
Some(prev) => Some(prev ++ separator ++ str),
}
}
match (reduce(iter, None, items)) {
None => "",
Some(s) => s,
}
from WasmI32 use { (+), (==) }
from DataStructures use { allocateString, stringSize }
let arrLen = length(items)
let sepPtr = WasmI32.fromGrain(separator)
let sepSize = stringSize(sepPtr)
let sepPtr = sepPtr + 8n
let mut strSize = 0n
for (let mut i = 0; i < arrLen; i = incr(i)) {
strSize += stringSize(WasmI32.fromGrain(items[i]))
if (i != 0) strSize += sepSize
}
let newString = allocateString(strSize)
let mut offset = newString + 8n
for (let mut i = 0; i < arrLen; i = incr(i)) {
let ptr = WasmI32.fromGrain(items[i])
let size = stringSize(ptr)
Memory.copy(offset, ptr + 8n, size)
offset += size
if (i != arrLen) Memory.copy(offset, sepPtr, sepSize)
offset += sepSize
}
WasmI32.toGrain(newString): String
}

/**
Expand Down

0 comments on commit f5100d3

Please sign in to comment.