-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrest_parameters.js
More file actions
89 lines (69 loc) · 1.7 KB
/
rest_parameters.js
File metadata and controls
89 lines (69 loc) · 1.7 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
/**
*
* @param {...any} args
* @returns
*/
function sum(...args) {
let total = 0;
for (const a of args) {
total += a;
}
return total;
}
console.log(sum(1, 2, 3, 4, 5)); // 15
/**
* pass arguments with various kinds of data types
*/
// example 1
function add(...args) {
return args
.filter(function (e) {
return typeof e === 'number';
})
.reduce(function (a, b) {
return a + b;
});
}
let result = add(20, 'hello', undefined, undefined, 40);
console.log(result); // 60
// example 2
function multiplication() {
return Array.prototype.filter
.call(arguments, function (e) {
return typeof e === 'number';
})
.reduce(function (a, b) {
return a * b;
});
}
let ans = multiplication(20, 'hello', undefined, undefined, 40);
console.log(ans); // 800
// example 3
function filterByType(type, ...args) {
return args.filter(function (e) {
return typeof e === type;
});
}
let filteredTypes = filterByType('string', 'hello', undefined, undefined, 40);
console.log(filteredTypes); // hello
/**
* JavaScript rest parameters and arrow function
*/
const combineString = (...args) => {
return args.reduce(function (cur, prev) {
return cur + ' ' + prev;
});
};
let message = combineString('JavaScript', 'Rest', 'Parameters'); // =>
console.log(message); // JavaScript Rest Parameters
const logStuff = (arg1, arg2, ...args) => {
console.log('arg1 = ', arg1);
console.log('arg2 = ', arg2);
console.log('args = ', args);
};
logStuff('chicken', 'tuna', 'chips', 'cookie', 'soda', 'delicious');
/**
* JavaScript rest parameter in a dynamic function
*/
const showNumbers = new Function('...numbers', 'console.log(numbers)');
showNumbers(1, 2, 3);