BarefootJS

 view release on metacpan or  search on metacpan

t/template_primitives.t  view on Meta::CPAN

    is $bf->json([$neg_zero, 1]), '[0,1]', 'a negative zero inside an array';
    is $bf->json({ a => [$neg_zero, 1], b => $neg_zero }), '{"a":[0,1],"b":0}', 'inside a hash';
    is $bf->json([-4 / 2, -4 / 8]), '[-2,-0.5]', 'integral and fractional quotients';
    is $bf->json([-4e-8, -4e20, -4e21, -1e-6, -1e-7]),
        '[-4e-8,-400000000000000000000,-4e+21,-0.000001,-1e-7]', 'JS exponent notation';
    # Inexact inputs are computed by the evaluator, which works in doubles
    # as JS does: on a perl built with -Duselongdouble / -Dusequadmath a
    # bare `0.1 + 0.2` is the wider NV nearest 0.3, which rounds to the
    # double 0.3 -- a different input, not a json bug (#3445, #3872).
    my $calc = \&BarefootJS::Evaluator::_binary;
    is $bf->json([$calc->('+', 0.1, 0.2), $calc->('/', -4, 3)]),
        '[0.30000000000000004,-1.3333333333333333]', 'shortest round-trip digits';
    is $bf->json(-$inf), 'null', 'top-level -Infinity is null';
    is $bf->json([-$inf, $inf, $inf - $inf, [-$inf]]), '[null,null,null,[null]]', 'non-finite at any depth';
    is $bf->json(['-0', '0.0', '-Inf', '1e5']), '["-0","0.0","-Inf","1e5"]', 'strings stay strings';
    is $bf->json([JSON::PP::true, JSON::PP::false, undef]), '[true,false,null]', 'booleans and undef';
    # A JSON string keeps its quotes after a numeric comparison caches a
    # number on it (`"1e5" < 0` sets IOK/NOK next to POK); a number that
    # was only interpolated stays a number.
    my $str = JSON::PP->new->allow_nonref->decode('"1e5"');
    my $cmp = $str < 0;
    is $bf->json($str), '"1e5"', 'a compared string stays a string';
    is $bf->json([$str, "007"]), '["1e5","007"]', 'inside an array';
    my $num = $calc->('+', 0.1, 0.2);
    my $interp = "$num";
    is $bf->json($num), '0.30000000000000004', 'an interpolated number stays a number';
    my $input = [$neg_zero];
    $bf->json($input);
    is sprintf('%g', $input->[0]), '-0', 'the argument is not mutated';
};

subtest 'boolean — a JS boolean the JSON encoder writes as true / false' => sub {
    is $bf->json([$bf->boolean(1), $bf->boolean(0), $bf->boolean(''), $bf->boolean(2 > 1)]),
        '[true,false,false,true]', 'booleans inside an array';
    is $bf->json({ ok => $bf->boolean(1 == 2) }), '{"ok":false}', 'a boolean inside an object';
    is $bf->string($bf->boolean(1)), 'true', 'prints as JS String(true)';
    ok !$bf->boolean(0), 'false stays falsy';
};

subtest 'display — a JSX text child renders nothing for a boolean' => sub {
    is $bf->display($bf->boolean(1)), '', 'JS true';
    is $bf->display($bf->boolean(0)), '', 'JS false';
    is $bf->display(JSON::PP::false), '', 'a decoded JSON boolean';
    is $bf->display('none'), 'none', 'a string passes through';
    is $bf->display(0), 0, 'a number passes through';
    ok !defined $bf->display(undef), 'nil passes through';
};

subtest 'string — JS String(v) mirror' => sub {
    is $bf->string(42),    '42', 'int';
    is $bf->string('hi'),  'hi', 'string passthrough';
    # Documented divergence from JS String(null) === "null".
    is $bf->string(undef), '',   'undef → "" (intentional divergence)';
    is $bf->string(JSON::PP::true),  'true',  'JSON true → "true" (#3440)';
    is $bf->string(JSON::PP::false), 'false', 'JSON false → "false" (#3440)';
    is $bf->bool_str('false'), 'false', 'bool_str keeps a stringified false (#3440)';
    is $bf->bool_str('true'),  'true',  'bool_str keeps a stringified true';
    is $bf->bool_str(0),       'false', 'bool_str of a Perl false';
};

# Real numeric NaN is the only float for which `$x != $x` holds.
# Tests check for it directly rather than string-comparing against
# "NaN", which stringifies platform-dependently.
sub is_nan { my $n = shift; return $n != $n }

subtest 'number — JS Number(v) mirror; NaN on parse failure' => sub {
    is $bf->number('3.14'), 3.14, 'numeric string';
    is $bf->number(42),     42,   'integer passthrough';
    ok is_nan($bf->number('not a num')), 'non-numeric → NaN';
    ok is_nan($bf->number(undef)),       'undef → NaN';
};

subtest 'floor / ceil / round — Math.* mirrors; propagate NaN' => sub {
    is $bf->floor(3.7),    3, '3.7 → 3';
    is $bf->floor(-3.2),  -4, '-3.2 → -4';
    ok is_nan($bf->floor('not')), 'floor: NaN propagates';

    is $bf->ceil(3.1),     4, '3.1 → 4';
    is $bf->ceil(-3.7),   -3, '-3.7 → -3';
    ok is_nan($bf->ceil('not')), 'ceil: NaN propagates';

    is $bf->round(3.5),    4, '3.5 → 4';
    is $bf->round(3.4),    3, '3.4 → 3';
    # JS `Math.round` ties go toward +Infinity, NOT away from zero —
    # so -1.5 rounds to -1 (not -2). Pin both halves of the negative
    # tie-break so a future POSIX::floor swap doesn't silently
    # regress the JS-compat contract.
    is $bf->round(-1.5),  -1, '-1.5 → -1 (JS half-toward-+Inf, not half-away-from-zero)';
    is $bf->round(-1.6),  -2, '-1.6 → -2';
    ok is_nan($bf->round('not')), 'round: NaN propagates';
};

# `Math.min(a, b)` / `Math.max(a, b)` (two-arg forms only) and
# `Math.abs()` (#2168 math-methods). JS returns NaN if EITHER min/max
# operand is NaN.
subtest 'min / max / abs — Math.* mirrors; propagate NaN' => sub {
    is $bf->min(3, 7),    3, 'min(3, 7) → 3';
    is $bf->min(7, 3),    3, 'min(7, 3) → 3 (order-independent)';
    is $bf->min(-2, -5), -5, 'min(-2, -5) → -5';
    ok is_nan($bf->min('not', 5)), 'min: NaN in first arg propagates';
    ok is_nan($bf->min(5, 'not')), 'min: NaN in second arg propagates';

    is $bf->max(3, 7),    7, 'max(3, 7) → 7';
    is $bf->max(7, 3),    7, 'max(7, 3) → 7 (order-independent)';
    is $bf->max(-2, -5), -2, 'max(-2, -5) → -2';
    ok is_nan($bf->max('not', 5)), 'max: NaN in first arg propagates';
    ok is_nan($bf->max(5, 'not')), 'max: NaN in second arg propagates';

    # The helpers answer a double, as JS does; on a perl built with
    # -Duselongdouble a bare `7.6` is the wider NV, so compare both as
    # doubles (#3445, #3872).
    my $double = \&BarefootJS::Evaluator::_double;
    is $double->($bf->abs(-7.6)), $double->(7.6), 'abs(-7.6) → 7.6';
    is $double->($bf->abs(7.6)),  $double->(7.6), 'abs(7.6) → 7.6 (no-op)';
    is $bf->abs(0),    0,   'abs(0) → 0';
    ok is_nan($bf->abs('not')), 'abs: NaN propagates';
};

# `Array.prototype.includes(x)` + `String.prototype.includes(sub)` lower
# to the same `$bf->includes($recv, $elem)` shape — see #1448 Tier A.
# The Perl helper dispatches on `ref()`: ARRAY ref scans elements with
# `BarefootJS::Evaluator::_same_value_zero` (SameValueZero — no cross-type
# coercion, NaN matches NaN), matching the evaluator's serialized-callback
# `.includes` path so both positions agree; scalar falls back to
# `index(..., ...) != -1`. Anything else (HASH ref, code ref) returns
# false to match the JS semantic that `.includes` is only defined on
# Array / TypedArray / String.
subtest 'includes — array + string + non-array/string dispatch' => sub {
    # Array receiver: SameValueZero element search (handles defined/undef
    # parity, and no numeric/string coercion — see the cross-type cases
    # below).
    ok  $bf->includes(['a', 'b', 'c'], 'b'), 'array contains element → 1';
    ok !$bf->includes(['a', 'b', 'c'], 'z'), 'array does not contain → 0';
    ok  $bf->includes([1, 2, 3], 2),         'numeric element';
    ok !$bf->includes([], 'a'),              'empty array → 0';
    ok  $bf->includes([undef, 'a'], undef),  'undef element matches undef needle';
    ok !$bf->includes(['a', 'b'], undef),    'undef needle, no undef element → 0';

    # SameValueZero never coerces across types — pins the divergence from
    # the old stringy `eq` scan (where `[2].includes("2")` was true).
    ok !$bf->includes([2], '2'),   '[2].includes("2") → 0 (no numeric→string coercion)';
    ok  $bf->includes([2], 2),     '[2].includes(2) → 1';
    ok  $bf->includes(['2'], '2'), '["2"].includes("2") → 1 (string vs string still matches)';

    # String receiver: substring search.
    ok  $bf->includes('hello world', 'world'), 'substring present → 1';
    ok !$bf->includes('hello world', 'earth'), 'substring absent → 0';
    ok  $bf->includes('hello', ''),            'empty needle → 1 (JS-compat)';
    ok !$bf->includes('', 'x'),                'empty receiver, non-empty needle → 0';
    ok !$bf->includes(undef, 'x'),             'undef receiver → 0';

    # Anything else (HASH ref, code ref) → 0; pin so a future
    # refactor doesn't accidentally match HASH keys.
    ok !$bf->includes({a => 1}, 'a'),    'hash ref → 0 (.includes undefined on Object)';
    ok !$bf->includes(sub {}, 'x'),      'code ref → 0';
};

# JS `===` between operands whose type the compiler cannot see. Perl's
# numeric `==` reads two non-numeric strings as `0 == 0`; `eq` reads `1` and
# `1.0` as different. The comparison goes by the operands' JS types instead.
subtest 'strict_eq — JS === by type and value' => sub {
    ok !$bf->strict_eq('p', 'q'), 'different non-numeric strings are not equal';
    ok $bf->strict_eq('p', 'p'), 'equal strings are equal';
    ok !$bf->strict_eq('', 'a'), 'empty string vs non-empty string';
    ok !$bf->strict_eq('001', '1'), 'numeric-looking strings compare by content';
    ok $bf->strict_eq(1, 1.0), 'numbers compare by value';
    ok $bf->strict_eq(0, -0.0), '0 === -0';
    ok $bf->strict_eq(1e3, 1000), 'exponent notation is the same number';
    ok !$bf->strict_eq(0.5, 1), 'different numbers are not equal';
    ok !$bf->strict_eq(1, '1'), 'number vs string of the same digits';
    ok !$bf->strict_eq('abc', 0), 'non-numeric string vs 0';
    my $nan = 0 + 'nan';
    ok !$bf->strict_eq($nan, $nan), 'NaN !== NaN';
    ok $bf->strict_eq(undef, undef), 'undef === undef';
    ok !$bf->strict_eq(undef, 0), 'undef vs 0';
    ok !$bf->strict_eq(undef, ''), 'undef vs empty string';
    ok $bf->strict_eq(JSON::PP::true(), JSON::PP::true()), 'true === true';
    ok !$bf->strict_eq(JSON::PP::true(), JSON::PP::false()), 'true !== false';
    ok !$bf->strict_eq(JSON::PP::true(), 1), 'true !== 1';
    my ($obj, $arr) = ({ id => 1 }, [1]);
    ok $bf->strict_eq($obj, $obj), 'the same hash ref is equal to itself';
    ok $bf->strict_eq($arr, $arr), 'the same array ref is equal to itself';
    ok !$bf->strict_eq({ id => 1 }, { id => 1 }), 'distinct hashes with equal contents are not equal';
    ok !$bf->strict_eq([1], [1]), 'distinct arrays with equal contents are not equal';
    ok !$bf->strict_eq($obj, $arr), 'a hash is not an array';
    ok !$bf->strict_eq($arr, '1'), 'an array is not its string form';
    ok !$bf->strict_eq($obj, undef), 'a hash is not undef';
    ok $bf->includes([$obj, $arr], $arr), 'includes finds the same reference';
    ok !$bf->includes([{ id => 1 }], $obj), 'includes misses a distinct equal hash';
};

# `Array.prototype.indexOf(x)` / `Array.prototype.lastIndexOf(x)`
# value-equality search (#1448 Tier A). Non-array receivers return -1.
# Duplicated-value coverage is the disambiguator between indexOf
# (forward) and lastIndexOf (backward); pinning a non-final last-match
# position makes a misdirected walk impossible to hide.
subtest 'index_of / last_index_of — array value-equality search' => sub {
    my $arr = ['a', 'b', 'c', 'b', 'd'];

    is $bf->index_of($arr, 'a'),          0,  'first element';
    is $bf->index_of($arr, 'b'),          1,  'duplicated value: first match';
    is $bf->index_of($arr, 'd'),          4,  'last element';
    is $bf->index_of($arr, 'z'),         -1,  'absent → -1';
    is $bf->index_of([], 'a'),           -1,  'empty array → -1';
    is $bf->index_of({a => 1}, 'a'),     -1,  'hash ref → -1';

    is $bf->last_index_of($arr, 'b'),     3,  'duplicated value: LAST match (non-final position)';
    is $bf->last_index_of($arr, 'a'),     0,  'unique value still found';
    is $bf->last_index_of($arr, 'z'),    -1,  'absent → -1';
    is $bf->last_index_of([], 'a'),      -1,  'empty array → -1';

    # undef parity matches the `includes` helper above.
    is $bf->index_of([undef, 'x', undef], undef), 0, 'undef matches undef (forward)';
    is $bf->last_index_of([undef, 'x', undef], undef), 2, 'undef matches undef (backward)';
};

# `Array.prototype.at(i)` — supports negative indices; out-of-bounds
# returns JS `undefined`. Non-array receivers return `undefined`. Mirrors the Go
# `bf_at` arithmetic so adapter output stays symmetric.
subtest 'at — array indexed access with negative-index support' => sub {
    my $arr = ['a', 'b', 'c'];

    is $bf->at($arr,  0),  'a',  'first element';
    is $bf->at($arr,  2),  'c',  'last element via positive index';
    is $bf->at($arr, -1),  'c',  'last element via -1';
    is $bf->at($arr, -3),  'a',  'first element via -3 (length - 3)';

    ok BarefootJS::Undefined::is_undefined($bf->at($arr,  3)), 'out of bounds (positive) → undefined';
    ok BarefootJS::Undefined::is_undefined($bf->at($arr, -4)), 'out of bounds (negative) → undefined';
    ok BarefootJS::Undefined::is_undefined($bf->at([],    0)), 'empty array → undefined';
    ok BarefootJS::Undefined::is_undefined($bf->at(undef, 0)), 'undef receiver → undefined';
    ok BarefootJS::Undefined::is_undefined($bf->at({a => 1},   0)), 'hash ref receiver → undefined';
};

# String receivers (#3613) count UTF-16 code units, like JS: '本' is one
# unit, '😀' is two.
subtest 'string index methods count UTF-16 code units' => sub {
    is $bf->index_of('banana', 'an'),      1,  'indexOf ascii';
    is $bf->index_of('日本語', '本'),       1,  'indexOf BMP';
    is $bf->index_of('a😀b', 'b'),          3,  'indexOf after astral';
    is $bf->index_of('abc', 'z'),          -1,  'indexOf missing';
    is $bf->index_of('abc', ''),            0,  'indexOf empty needle';
    is $bf->index_of('ab', 'abc'),         -1,  'indexOf needle longer than receiver';
    is $bf->last_index_of('banana', 'an'),  3,  'lastIndexOf ascii';
    is $bf->last_index_of('a😀b😀', '😀'),   4,  'lastIndexOf astral';
    is $bf->last_index_of('abc', ''),       3,  'lastIndexOf empty needle';
    is $bf->last_index_of('aaa', 'aa'),     1,  'lastIndexOf overlapping';
    is $bf->at('日本語', -1), '語',  'at BMP';
    is $bf->at('a😀b', -1),   'b',   'at after astral (negative)';
    is $bf->at('a😀b', 3),    'b',   'at after astral (positive)';
    ok BarefootJS::Undefined::is_undefined($bf->at('abc', 3)), 'at out of range';
    ok BarefootJS::Undefined::is_undefined($bf->at('', 0)), 'at empty string';
    is $bf->at('a😀b', 1),    "\x{FFFD}", 'at half of a surrogate pair → U+FFFD';
    ok  $bf->starts_with('日本語', '本', 1), 'startsWith BMP position';
    ok  $bf->starts_with('a😀b', 'b', 3),   'startsWith position after astral';
    ok !$bf->starts_with('a😀b', 'b', 2),   'startsWith position inside pair';
    ok  $bf->ends_with('日本語', '本', 2),   'endsWith BMP endPosition';
    ok  $bf->ends_with('a😀b', '😀', 3),     'endsWith astral endPosition';
    ok !$bf->ends_with('a😀b', 'a', 2),     'endsWith endPosition inside pair';
};

# ToIntegerOrInfinity for the string index paths (#3613): NaN is 0,
# ±Infinity is out of range, fractions truncate toward zero.
subtest 'string index methods read non-finite positions as ToIntegerOrInfinity' => sub {
    my $inf = 9**9**9;
    my $nan = $inf - $inf;
    is $bf->at('abc', $nan),   'a',   'at(NaN) is at(0)';
    ok BarefootJS::Undefined::is_undefined($bf->at('abc', $inf)), 'at(Infinity) is out of range';
    ok BarefootJS::Undefined::is_undefined($bf->at('abc', -$inf)), 'at(-Infinity) is out of range';
    is $bf->at('abc', 1.9),    'b',   'at(1.9) truncates';
    is $bf->at('abc', -1.5),   'c',   'at(-1.5) truncates toward zero';
    ok  $bf->starts_with('abc', 'a', $nan), 'startsWith NaN position is 0';
    ok  $bf->starts_with('abc', '', $inf),  'startsWith Infinity position clamps';
    ok !$bf->ends_with('abc', 'c', $nan),   'endsWith NaN endPosition is 0';
    ok  $bf->ends_with('abc', 'c', $inf),   'endsWith Infinity endPosition clamps';
};

# `Array.prototype.concat(other)` — merges two arrays in order
# into a new ARRAY ref (#1448 Tier A). Non-array operands collapse
# to empty (matches the Go `bf_concat` semantic); the result must
# compose with `.join(...)` etc., hence the ARRAY ref return type.
subtest 'concat — merges two arrays into a new array ref' => sub {
    is $bf->concat(['a','b'], ['c','d']),    ['a','b','c','d'],     'two non-empty arrays';
    is $bf->concat([],         ['a']),       ['a'],                 'empty + non-empty';
    is $bf->concat(['a'],      []),          ['a'],                 'non-empty + empty';
    is $bf->concat([],         []),          [],                    'empty + empty';

    is $bf->concat(undef,      ['a']),       ['a'],                 'undef left → treats as empty';
    is $bf->concat(['a'],      undef),       ['a'],                 'undef right → treats as empty';
    is $bf->concat('not an array', ['a']),   ['a'],                 'scalar left → treats as empty';
    is $bf->concat({a=>1},     ['a']),       ['a'],                 'hash ref left → treats as empty';

    # Mutation isolation: caller's source arrays must not be modified.
    my $left  = ['a', 'b'];
    my $right = ['c', 'd'];
    my $out   = $bf->concat($left, $right);
    push @$out, 'mutated';
    is $left,  ['a', 'b'], 'left source unchanged after mutating result';
    is $right, ['c', 'd'], 'right source unchanged after mutating result';
};

# `Array.prototype.slice(start, end?)` — carves out a sub-range
# into a new ARRAY ref (#1448 Tier A). Mirrors the Go `bf_slice`
# JS-compat semantics: negative-index normalisation, out-of-bounds
# clamping, `start >= end` returns empty, an omitted or `undefined` `end`
# means "to length". Non-array, non-string receivers return an empty ARRAY ref.
subtest 'slice — array sub-range with negative-index + clamping' => sub {
    my $arr = ['a', 'b', 'c', 'd', 'e'];

    # 2-arg form.
    is $bf->slice($arr, 1, 3),     ['b', 'c'],             'start+end carves middle';

    # 1-arg form (an `undefined` end, as the adapters pass an omitted one,
    # is "to length"; a `null` end is 0).
    is $bf->slice($arr, 2, $U), ['c', 'd', 'e'],        'undefined end → to length';
    is $bf->slice($arr, 0, $U), ['a', 'b', 'c', 'd', 'e'], 'start 0, undefined end → full copy';

    # Negative-index normalisation.
    is $bf->slice($arr, -2, $U),['d', 'e'],             '-2 start → last two';
    is $bf->slice($arr, 2),        ['c', 'd', 'e'],        'omitted end → to length';
    is $bf->slice($arr, 2, undef), [],                     'null end → 0 → empty';
    is $bf->slice($arr,  0, -1),   ['a', 'b', 'c', 'd'],   '-1 end → drop last';
    is $bf->slice($arr, -3, -1),   ['c', 'd'],             'both negative';

    # Clamping (out of bounds + start >= end).
    is $bf->slice($arr, 100, $U), [],                   'start past end → empty';
    is $bf->slice($arr,   3,   1),   [],                   'start > end → empty';
    is $bf->slice($arr,   0,   0),   [],                   'start == end → empty';

    # Edge cases.
    is $bf->slice([],     0, $U), [],                   'empty array → empty';
    is $bf->slice(undef,  0, $U), [],                   'undef receiver → empty';
    is $bf->slice({foo => 1}, 0, $U), [],                'hashref receiver → empty (not array, not string)';



( run in 1.189 second using v1.01-cache-2.11-cpan-60884a8df76 )