-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy path21 Bonfire Arguments Optional.js
More file actions
67 lines (56 loc) · 1.93 KB
/
21 Bonfire Arguments Optional.js
File metadata and controls
67 lines (56 loc) · 1.93 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
/* Bonfire: Arguments Optional
Difficulty: 2/5
Create a function that sums two arguments together. If only one argument is provided, return a
function that expects one additional argument and will return the sum.
For example, add(2, 3) should return 5, and add(2) should return a function that is waiting for an
argument so that var sum2And = add(2); return sum2And(3); // 5
If either argument isn't a valid number, return undefined.
Remember to use RSAP if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Global Function Object
Arguments object
Code by Rafael Rodriguez & https://github.com/mildused & https://github.com/ozydesign
rafase282@gmail.com
http://www.freecodecamp.com/rafase282
*/
function add() {
// Function to check if a number is actually a number
// and return undefined otherwise.
var checkNum = function(num) {
if (typeof num !== 'number') {
return undefined;
} else
return num;
};
// Check if we have two parameters, check if they are numbers
// handle the case where one is not
// returns the addition.
if (arguments.length > 1) {
var a = checkNum(arguments[0]);
var b = checkNum(arguments[1]);
if (a === undefined || b === undefined) {
return undefined;
} else {
return a + b;
}
} else {
// If only one parameter was found, returns a new function that expects two
// Store first argument before entering the new function scope
var c = arguments[0];
// Check the number again, must be outside the function to about returning an object
// instead of undefined.
if (checkNum(c)) {
// Return function that expect a second argument.
return function(arg2) {
// Check for non-numbers
if (c === undefined || checkNum(arg2) === undefined) {
return undefined;
} else {
// if numbers then add them.
return c + arg2;
}
};
}
}
}
add(2, 3);