Skip to content

Commit 46e6e5f

Browse files
committed
Add panic changes to try
1 parent d88c179 commit 46e6e5f

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

defaultMethods.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ const defaultMethods = {
290290
lazy: true
291291
},
292292
'??': defineCoalesce(),
293-
try: defineCoalesce(downgrade),
293+
try: defineCoalesce(downgrade, true),
294294
and: {
295295
[Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
296296
method: (arr, _1, _2, engine) => {
@@ -715,7 +715,7 @@ const defaultMethods = {
715715
/**
716716
* Defines separate coalesce methods
717717
*/
718-
function defineCoalesce (func) {
718+
function defineCoalesce (func, panic) {
719719
let downgrade
720720
if (func) downgrade = func
721721
else downgrade = (a) => a
@@ -734,6 +734,7 @@ function defineCoalesce (func) {
734734
}
735735

736736
if (item === undefined) return null
737+
if (panic) throw item
737738
return item
738739
},
739740
asyncMethod: async (arr, _1, _2, engine) => {
@@ -748,6 +749,7 @@ function defineCoalesce (func) {
748749
}
749750

750751
if (item === undefined) return null
752+
if (panic) throw item
751753
return item
752754
},
753755
deterministic: (data, buildState) => isDeterministic(data, buildState.engine, buildState),
@@ -756,8 +758,10 @@ function defineCoalesce (func) {
756758
const funcCall = func ? 'downgrade' : ''
757759
if (Array.isArray(data) && data.length) {
758760
return `(${data.map((i, x) => {
759-
if (Array.isArray(i) || !i || typeof i !== 'object' || x === data.length - 1) return buildString(i, buildState)
760-
return `${funcCall}(` + buildString(i, buildState) + ')'
761+
const built = buildString(i, buildState)
762+
if (panic && x === data.length - 1) return `(typeof ((prev = ${built}) || 0).error !== 'undefined' || Number.isNaN(prev) ? (() => { throw prev.error })() : prev)`
763+
if (Array.isArray(i) || !i || typeof i !== 'object' || x === data.length - 1) return built
764+
return `${funcCall}(` + built + ')'
761765
}).join(' ?? ')})`
762766
}
763767
return `(${buildString(data, buildState)}).reduce((a,b) => ${funcCall}(a) ?? b, null)`

suites/try.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,17 @@
1717
"rule": { "try": [{ "val": "x" }, 1]},
1818
"data": { "x": { "error": "Some error" }},
1919
"result": 1
20+
},
21+
{
22+
"description": "Panics if none of the values are valid",
23+
"rule": { "try": [{ "error": "Some error" }, { "error": "Some other error" }] },
24+
"error": true,
25+
"data": null
26+
},
27+
{
28+
"description": "Panics if none of the values are valid (2)",
29+
"rule": { "try": [{ "error": "Some error" }, { "/": [0, 0] }] },
30+
"error": true,
31+
"data": null
2032
}
2133
]

0 commit comments

Comments
 (0)