Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

arr.flat、arr.flat_mapを追加 #622

Merged
merged 8 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- `Date:millisecond`を追加
- `arr.fill`, `arr.repeat`, `Arr:create`を追加
- JavaScriptのように分割代入ができるように(現段階では機能は最小限)
- `arr.flat`,`arr.flat_map`を追加

# 0.17.0
- `package.json`を修正
Expand Down
8 changes: 8 additions & 0 deletions docs/primitive-props.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,14 @@ _fromIndex_ および _toIndex_ に関する挙動は`arr.slice`に準拠しま
`arr.copy`同様シャローコピーであり、配列やオブジェクトの参照は維持されます。
_times_ には0以上の整数値を指定します。それ以外ではエラーになります。

### @(_v_: arr).flat(_depth_?: num): arr
配列に含まれる配列を _depth_ で指定した深さの階層まで結合した新しい配列を作成します。
_depth_ には0以上の整数値を指定します。省略時は1になります。

### @(_v_: arr).flat_map(_func_: @(_item_: value, _index_: num) { value }): arr
配列の各要素を _func_ の返り値で置き換えた後、1階層平坦化した新しい配列を作成します。
_func_ は非同期的に呼び出されます。

## エラー型
### #(_v_: error).name
型: `str`
Expand Down
35 changes: 34 additions & 1 deletion src/interpreter/primitive-props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { substring, length, indexOf, toArray } from 'stringz';
import { AiScriptRuntimeError } from '../error.js';
import { textEncoder } from '../const.js';
import { assertArray, assertBoolean, assertFunction, assertNumber, assertString, expectAny, eq } from './util.js';
import { assertArray, assertBoolean, assertFunction, assertNumber, assertString, expectAny, eq, isArray } from './util.js';
import { ARR, FALSE, FN_NATIVE, NULL, NUM, STR, TRUE } from './value.js';
import type { Value, VArr, VFn, VNum, VStr, VError } from './value.js';

Expand Down Expand Up @@ -86,7 +86,7 @@
split: (target: VStr): VFn => FN_NATIVE(async ([splitter], _opts) => {
if (splitter) assertString(splitter);
if (splitter) {
return ARR(target.value.split(splitter ? splitter.value : '').map(s => STR(s)));

Check warning on line 89 in src/interpreter/primitive-props.ts

View workflow job for this annotation

GitHub Actions / lint

Unnecessary conditional, value is always truthy
} else {
return ARR(toArray(target.value).map(s => STR(s)));
}
Expand Down Expand Up @@ -279,6 +279,39 @@
throw e;
}
}),

flat: (target: VArr): VFn => FN_NATIVE(async ([depth], opts) => {
depth = depth ?? NUM(1);
assertNumber(depth);
if (!Number.isInteger(depth.value)) throw new AiScriptRuntimeError('arr.flat expected integer, got non-integer');
if (depth.value < 0) throw new AiScriptRuntimeError('arr.flat expected non-negative number, got negative');
const flat = (arr: Value[], depth: number, result: Value[]) => {
if (depth === 0) {
result.push(...arr);
return;
}
for (const v of arr) {
if (isArray(v)) {
flat(v.value, depth - 1, result);
} else {
result.push(v);
}
}
};
const result: Value[] = [];
flat(target.value, depth.value, result);
return ARR(result);
}),

flat_map: (target: VArr): VFn => FN_NATIVE(async ([fn], opts) => {
assertFunction(fn);
const vals = target.value.map(async (item, i) => {
const result = await opts.call(fn, [item, NUM(i)]);
return isArray(result) ? result.value : result;
});
const mapped_vals = await Promise.all(vals);
return ARR(mapped_vals.flat());
}),
},

error: {
Expand Down
43 changes: 43 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2849,6 +2849,49 @@ describe('primitive props', () => {
ARR([]),
]));
});

test.concurrent('flat', async () => {
const res = await exe(`
var arr1 = [0, [1], [2, 3], [4, [5, 6]]]
let arr2 = arr1.flat()
let arr3 = arr1.flat(2)
<: [arr1, arr2, arr3]
`);
eq(res, ARR([
ARR([
NUM(0), ARR([NUM(1)]), ARR([NUM(2), NUM(3)]),
ARR([NUM(4), ARR([NUM(5), NUM(6)])])
]), // target not changed
ARR([
NUM(0), NUM(1), NUM(2), NUM(3),
NUM(4), ARR([NUM(5), NUM(6)]),
]),
ARR([
NUM(0), NUM(1), NUM(2), NUM(3),
NUM(4), NUM(5), NUM(6),
]),
]));
});

test.concurrent('flat_map', async () => {
const res = await exe(`
let arr1 = [0, 1, 2]
let arr2 = ["a", "b"]
let arr3 = arr1.flat_map(@(x){ arr2.map(@(y){ [x, y] }) })
<: [arr1, arr3]
`);
eq(res, ARR([
ARR([NUM(0), NUM(1), NUM(2)]), // target not changed
ARR([
ARR([NUM(0), STR("a")]),
ARR([NUM(0), STR("b")]),
ARR([NUM(1), STR("a")]),
ARR([NUM(1), STR("b")]),
ARR([NUM(2), STR("a")]),
ARR([NUM(2), STR("b")]),
]),
]));
});
});
});

Expand Down
Loading