forked from SunJieMing/js-minicamp-homework-4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercises.js
89 lines (75 loc) · 1.84 KB
/
exercises.js
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
'use strict';
//Do not change any of the function names
function multiplyArguments() {
if (arguments.length === 0) return 0;
var result = 1;
for (var i = 0; i < arguments.length; i++) {
result = result * arguments[i];
}
return result;
}
function invokeCallback(cb) {
cb();
}
function sumArray(numbers, cb) {
var sum = numbers.reduce(function (prev, curr) {
return prev + curr;
});
cb(sum);
}
function forEach(arr, cb) {
arr.forEach(cb);
}
function map(arr, cb) {
return arr.map(cb);
}
function getUserConstructor() {
var User = function (options) {
this.username = options.username;
this.name = options.name;
this.email = options.email;
this.password = options.password;
};
return User;
}
function addPrototypeMethod(Constructor) {
Constructor.prototype.sayHi = function(){
return 'Hello World!';
};
}
function addReverseString() {
String.prototype.reverse = function(){
return this.split('').reverse().join('');
};
}
function nFactorial(n) {
if(n === 2) return 2;
return n * nFactorial(n-1);
}
function cacheFunction(cb) {
var argCache = {};
return function() {
var inArg = arguments[0];
if(argCache.hasOwnProperty(inArg)) {
return argCache[inArg];
}
else {
argCache[inArg] = cb(inArg);
return argCache[inArg];
}
};
}
//Do not modify code below this line.
////--------------------------------
module.exports = {
multiplyArguments: multiplyArguments,
invokeCallback: invokeCallback,
sumArray: sumArray,
forEach: forEach,
map: map,
getUserConstructor: getUserConstructor,
addPrototypeMethod: addPrototypeMethod,
addReverseString: addReverseString,
nFactorial: nFactorial,
cacheFunction: cacheFunction
};