Skip to content

Commit

Permalink
Date:parseの失敗時にエラー型の値を返すように (#10) (#739)
Browse files Browse the repository at this point in the history
* Date:parse to return error-type when failing

* Update CHANGELOG.md

* Create date-parse-err.md

* re-add test
  • Loading branch information
FineArchs authored Aug 3, 2024
1 parent e1454f4 commit 90fd542
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/std.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ _date_ を渡した場合、_date_に対応するミリ秒、
渡していない場合は現在時刻のミリ秒が返されます。

### @Date:parse(_date_: str): num
日付として解釈可能な文字列から日時を表す数値を生成します。
解釈は[JavaScriptのDateコンストラクター](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)に依存します。
引数が日付として解釈可能でない場合、エラー型の値(`name`=`'not_date'`)を返します。


### @Date:to_iso_str(_date_?: num, _time_offset_?: num): str
_date_ を拡張表記のISO形式にした文字列を返します。
Expand Down
4 changes: 3 additions & 1 deletion src/interpreter/lib/std.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,9 @@ export const std: Record<string, Value> = {

'Date:parse': FN_NATIVE(([v]) => {
assertString(v);
return NUM(new Date(v.value).getTime());
const res = new Date(v.value).getTime();
// NaN doesn't equal to itself
return (res === res) ? NUM(res) : ERROR('not_date');
}),

'Date:to_iso_str': FN_NATIVE(([v, ofs]) => {
Expand Down
17 changes: 17 additions & 0 deletions test/std.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,4 +420,21 @@ describe('Date', () => {
eq(res.value[0], res.value[1]);
eq(res.value[2], STR("2024-04-11T11:29:46.021-05:18"));
});

test.concurrent('parse', async () => {
eq(await exe(`<: [
'01 Jan 1970 00:00:00 GMT'
'1970-01-01'
'1970-01-01T00:00:00.000Z'
'1970-01-01T00:00:00.000+00:00'
'hoge'
].map(Date:parse)`), ARR([
NUM(0),
NUM(0),
NUM(0),
NUM(0),
ERROR('not_date')
]));
});
});
});
1 change: 1 addition & 0 deletions unreleased/date-parse-err.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `Date:parse`がパース失敗時にエラー型の値を返すように

0 comments on commit 90fd542

Please sign in to comment.