์ผ๋ฐ JavaScript์์ :
fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
fruits // == ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]
๊ทธ๋ฌ๋ AS์์๋ง ์๋ช :
function splice(start: i32, deleteCount?: i32): Array<T>
๋ฐ์ดํฐ๋ฅผ ๊ธฐ์กด ์ด๋ ์ด์ ์ฐ๊ฒฐํ๋ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ด ์์ต๋๊น?
ํ์ฌ AS๋ ๊ฐ๋ณ ํจ์๋ฅผ ์ํ ํ ์ ์์ต๋๋ค. ๊ทธ๋์ ๋๋ ์ ํญ๋ชฉ์ ์ฝ์ ํ๊ธฐ ์ํด์ด ํด๊ฒฐ ๋ฐฉ๋ฒ์ ์ ์ํฉ๋๋ค.
export function insertAfter<T>(arr: T[], index: i32, value: T): T[] {
const len = arr.length + 1
const res = new Array<T>(len)
if (index < 0) index = len + index - 1
if (index > len) index = len - 1
let i = 0
while (i < index) res[i] = arr[i++] // or use memory.copy
res[i++] = value
while (i < len) res[i] = arr[i++ - 1] // or use memory.copy
return res
}
// intead fruits.splice(2, 0, "Lemon", "Kiwi") use:
fruits = insertAfter(fruits, 2, "Lemon");
fruits = insertAfter(fruits, 3, "Kiwi");
@MaxGraey ๊ทธ๋์ stdlib์์ ์ด๋ป๊ฒ ๋ ์ด๊ฒ์ ์ ๊ณต ํ ์ ์๋ค๊ณ ์๊ฐํ์ญ๋๊น? ๋๋จธ์ง ๋งค๊ฐ ๋ณ์ ๋์ ๋ฐฐ์ด์ ์ทจํ๋ spliceAndInsert
์ฒ๋ผ?
์ฝ์ ํญ๋ชฉ ๋ฐฐ์ด์ด ์ ์ ํ ํด๊ฒฐ์ฑ ์ด๋ผ๊ณ ์๊ฐํ์ง ์์ต๋๋ค. ์ด์จ๋ ์ฐ๋ฆฌ๋ ๊ฐ๋ณ ํจ์๊ฐ ํ์ํ ๋ค๋ฅธ ๊ณณ์ด ๋ง์ด ์์ผ๋ฏ๋ก ์ปดํ์ผ๋ฌ์์ ๊ตฌํ ๋ ์ ์ ํ ๋ฉ์ปค๋์ฆ์ ์ถ๊ฐํ๋ ๊ฒ์ด ์ข์ต๋๋ค.
๊ฐ์ฌํฉ๋๋ค @MaxGraey
insertAfter
์ (๋) ๊ด๊ณ ๋ ๊ฒ๊ณผ ์ฝ๊ฐ ๋ค๋ฅด๊ฒ ์๋ํฉ๋๋ค. ๋ด๋ถ ๋ฐฐ์ด ๊ต์ฒด๋ ์๋์ง๋ง ๋งค๋ฒ ์ ๋ฐฐ์ด์ ํ ๋นํฉ๋๋ค (์ : ๋ด๋ถ์ ์ผ๋ก realloc
). ๋ฐ๋ผ์ ์ฌ ํ ๋น์ด ํ์ํฉ๋๋ค.
import {insertAfter} from "./insertAfter";
export function example(): string[] {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits = insertAfter(fruits, 2, "Lemon");
fruits = insertAfter(fruits, 3, "Kiwi");
return fruits;
}
๊ทธ๋ฆฌ๊ณ ๋ธ๋ผ์ฐ์ ์์ ( getArray
๋ฐ getString
๋ฅผ ๋ด๋ณด๋ด๋ ์์ ๋ Loader ์คํฌ๋ฆฝํธ ์ฌ์ฉ) :
fruits_ptr = assemblyscript.module.exports.example()
// 21359280
fruits = Loader.getArray(fruits_ptr)
// (6)ย [1152, 1184, 1312, 1616, 1216, 1248]
fruits.map(Loader.getString)
// (6)ย ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]
์, ๊ณ ์ ๋ ์์
๋๋ค. __realloc
๋ฐ memory.copy
์ฌ์ฉํ์ฌ ๊ฐ์ ํ ์ ์์ต๋๋ค.