Repository navigation
Expand file tree
/
Copy pathfunctions.smash
More file actions
106 lines (86 loc) · 2.37 KB
/
Copy pathfunctions.smash
File metadata and controls
106 lines (86 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// SmashLang Functions Examples
// Basic function declaration
fn greet(name) {
return "Hello, " + name + "!";
}
// Function call
let greeting = greet("World");
print(greeting); // Output: Hello, World!
// Function with default parameters
fn greetWithDefault(name = "Guest") {
return "Hello, " + name + "!";
}
print(greetWithDefault()); // Output: Hello, Guest!
print(greetWithDefault("John")); // Output: Hello, John!
// Function with multiple parameters
fn add(a, b) {
return a + b;
}
print("Sum: " + add(5, 3)); // Output: Sum: 8
// Function with rest parameters
fn sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
print("Sum of 1, 2, 3: " + sum(1, 2, 3)); // Output: Sum of 1, 2, 3: 6
print("Sum of 5, 10, 15, 20: " + sum(5, 10, 15, 20)); // Output: Sum of 5, 10, 15, 20: 50
// Arrow functions
const multiply = (a, b) => a * b;
print("5 * 3 = " + multiply(5, 3)); // Output: 5 * 3 = 15
// Arrow function with block body
const square = (x) => {
let result = x * x;
return result;
};
print("Square of 4: " + square(4)); // Output: Square of 4: 16
// Higher-order functions
fn operate(a, b, operation) {
return operation(a, b);
}
print("Addition: " + operate(5, 3, add)); // Output: Addition: 8
print("Multiplication: " + operate(5, 3, multiply)); // Output: Multiplication: 15
// Closures
fn createCounter() {
let count = 0;
return fn() {
count += 1;
return count;
};
}
const counter = createCounter();
print(counter()); // Output: 1
print(counter()); // Output: 2
print(counter()); // Output: 3
// Immediately Invoked Function Expression (IIFE)
const result = (fn() {
let x = 10;
let y = 20;
return x + y;
})();
print("IIFE result: " + result); // Output: IIFE result: 30
// Recursive functions
fn factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
print("Factorial of 5: " + factorial(5)); // Output: Factorial of 5: 120
// Async functions
async fn fetchData() {
// Simulate async operation
await new Promise(resolve => setTimeout(resolve, 1000));
return "Data fetched";
}
// Using async function
async fn processData() {
print("Fetching data...");
const data = await fetchData();
print(data);
return "Processing complete";
}
// Call async function
processData().then(result => print(result));