-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples.js
123 lines (106 loc) · 2.16 KB
/
examples.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/**
* JS Examples
*/
/**
* Closure
*/
function person(name) {
var _name = name;
function fullName() {
console.log(_name);
}
return fullName;
}
person('Miguel');
function person(name) {
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments);
return args.join(' ');
} else {
return function(lastName) {
return name + ' ' + lastName;
};
}
}
person('Miguel', 'Murillo');
person('Miguel')('Murillo');
/**
* add array
* @return {[Number]}
*/
[0, 1, 2, 3, 4].reduce(function(pre, curr) {
return pre + curr;
});
/**
* Singleton
*/
var singletonExample = (function() {
var myInstance;
function createInstance() {
var object = new Object("My Instance");
return object;
}
return {
getInstance: function() {
if (!myInstance) {
myInstance = createInstance();
}
return myInstance;
}
};
})();
var instance = singletonExample.getInstance();
/**
* Sum one or more values
* @param {[Number]}
* @return {[Number]} Sum of arguments
*/
function sum(x) {
if (arguments.length > 1) {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
} else {
return function(y) {
return x + y;
};
}
}
console.log(sum(2, 3)); // Outputs 5
console.log(sum(2)(3)); // Outputs 5
/**
* arguments to Array
* @type {[Array]}
*/
var args = Array.prototype.slice.call(arguments);
/**
* The .bind method from Prototype.js
* @return {[object]}
*/
Function.prototype.bind = Function.prototype.bind || function() {
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
return function() {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
/**
* Repeatify methd
* @param {[Number]} times
* @return {[String]}
*/
String.prototype.repeatify = String.prototype.repeatify || function(times) {
return new Array(times + 1).join(this);
};
String.prototype.repeatify = String.prototype.repeatify || function(times) {
var res = '';
for (var i = 0; i < times; i++) {
res += this;
}
return res;
};
console.log('ab'.repeatify(3));