Skip to main content

nanvm_lib/vm/any/
conditional.rs

1use crate::vm::{Any, IVm};
2
3impl<A: IVm> Any<A> {
4    /// `?:`. Not a `core::ops` trait — Rust has no operator for a ternary
5    /// conditional (`if`/`else` takes a `bool`, not an `Any<A>`) — so this
6    /// is a plain method over the native VM's values.
7    ///
8    /// Coerces `self` via `ToBoolean`, establishes the arm that selects —
9    /// `consequent` or `alternate` — and returns its value. The arms are
10    /// thunks because JavaScript establishes exactly one of them:
11    /// `true ? 1 : (1n / 0n)` is `1`, not a throw. `FnOnce`, since an arm is
12    /// established at most once; a `Result`, since establishing it may
13    /// throw, and that throw is this operation's.
14    /// <https://tc39.es/ecma262/#sec-conditional-operator>
15    pub fn conditional(
16        self,
17        consequent: impl FnOnce() -> Result<Self, Self>,
18        alternate: impl FnOnce() -> Result<Self, Self>,
19    ) -> Result<Self, Self> {
20        if self.to_boolean() {
21            consequent()
22        } else {
23            alternate()
24        }
25    }
26}