Assemblyscript: Array#spliceは要素を追加できません

作成日 2020年10月12日  ·  5コメント  ·  ソース: AssemblyScript/assemblyscript

通常の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>

データを既存のアレイにスプライスする他の方法はありますか?

question

全てのコメント5件

現在、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がRESTパラメータの代わりに配列を取るようなものですか?

挿入アイテムの配列は適切な解決策ではないと思います。 とにかく、可変個引数関数が必要な場所は他にもたくさんあるので、コンパイラーに実装されたこれに適切なメカニズムを追加する方がよいでしょう。

どうもありがとう@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;
}

そしてブラウザで( getArraygetStringをエクスポートする変更されたローダースクリプトを使用):

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"]

image

はい、例を修正しました。 ところで、 __reallocmemory.copyを使用して改善できます

このページは役に立ちましたか?
0 / 5 - 0 評価

関連する問題

kyegupov picture kyegupov  ·  3コメント

DanielMazurkiewicz picture DanielMazurkiewicz  ·  4コメント

MaxGraey picture MaxGraey  ·  3コメント

solidsnail picture solidsnail  ·  5コメント

pannous picture pannous  ·  4コメント