MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1import { test, summary } from './helpers.js';
2
3console.log('Function Tests\n');
4
5function add(a, b) {
6 return a + b;
7}
8test('function declaration', add(2, 3), 5);
9
10const multiply = function(a, b) {
11 return a * b;
12};
13test('function expression', multiply(3, 4), 12);
14
15const arrow = (a, b) => a - b;
16test('arrow function', arrow(10, 3), 7);
17
18const arrowSingle = x => x * 2;
19test('arrow single param', arrowSingle(5), 10);
20
21const arrowBlock = (a, b) => {
22 const sum = a + b;
23 return sum * 2;
24};
25test('arrow block body', arrowBlock(2, 3), 10);
26
27function defaultParam(a, b = 10) {
28 return a + b;
29}
30test('default param used', defaultParam(5), 15);
31test('default param overridden', defaultParam(5, 3), 8);
32
33function restParams(first, ...rest) {
34 return first + rest.length;
35}
36test('rest params', restParams(1, 2, 3, 4), 4);
37
38function spreadCall(a, b, c) {
39 return a + b + c;
40}
41test('spread in call', spreadCall(...[1, 2, 3]), 6);
42
43const obj = {
44 value: 100,
45 getValue() {
46 return this.value;
47 }
48};
49test('method this', obj.getValue(), 100);
50
51const arrowThis = {
52 value: 50,
53 getArrow() {
54 return (() => this.value)();
55 }
56};
57test('arrow this binding', arrowThis.getArrow(), 50);
58
59function outer() {
60 let x = 10;
61 return function inner() {
62 return x;
63 };
64}
65test('closure', outer()(), 10);
66
67const counter = (() => {
68 let count = 0;
69 return {
70 inc() { return ++count; },
71 get() { return count; }
72 };
73})();
74test('iife closure inc', counter.inc(), 1);
75test('iife closure get', counter.get(), 1);
76
77function factorial(n) {
78 if (n <= 1) return 1;
79 return n * factorial(n - 1);
80}
81test('recursion', factorial(5), 120);
82
83test('function name', add.name, 'add');
84test('function length', add.length, 2);
85
86function bindTest(greeting) {
87 return greeting + ' ' + this.name;
88}
89const boundFn = bindTest.bind({ name: 'World' });
90test('bind', boundFn('Hello'), 'Hello World');
91
92test('call', bindTest.call({ name: 'Call' }, 'Hi'), 'Hi Call');
93test('apply', bindTest.apply({ name: 'Apply' }, ['Hey']), 'Hey Apply');
94
95const gen = (function() {
96 const fns = [];
97 for (let i = 0; i < 3; i++) {
98 fns.push(() => i);
99 }
100 return fns;
101})();
102test('closure in loop 0', gen[0](), 0);
103test('closure in loop 1', gen[1](), 1);
104test('closure in loop 2', gen[2](), 2);
105
106summary();