Skip to content

Commit b4e17b1

Browse files
authored
Merge pull request #4439 from nlarrea/js-24
#24 - javascript
2 parents 6fa8169 + 21162cc commit b4e17b1

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/**
2+
* EJERCICIO:
3+
* Explora el concepto de "decorador" y muestra cómo crearlo
4+
* con un ejemplo genérico.
5+
*
6+
* DIFICULTAD EXTRA (opcional):
7+
* Crea un decorador que sea capaz de contabilizar cuántas veces
8+
* se ha llamado a una función y aplícalo a una función de tu elección.
9+
*/
10+
11+
function measureTime(func) {
12+
return function (...args) {
13+
const start = performance.now();
14+
const result = func(...args);
15+
const end = performance.now();
16+
console.log(`Required time: ${Math.round(((end - start) / 1000 * 100) / 100)} seconds`);
17+
18+
return result;
19+
}
20+
}
21+
22+
23+
function sumTwoValues(numOne, numTwo) {
24+
const wait = ms => {
25+
const start = new Date().getTime();
26+
let end = start;
27+
28+
while (end <= start + ms) {
29+
end = new Date().getTime();
30+
}
31+
}
32+
33+
wait(3000);
34+
return numOne + numTwo;
35+
}
36+
// Decorate function
37+
const decoratedSumTwoValues = measureTime(sumTwoValues);
38+
39+
console.log(decoratedSumTwoValues(10, 5));
40+
/** This call prints:
41+
* Required time: 3 seconds
42+
* 15
43+
*/
44+
45+
46+
/**
47+
* DIFICULTAD EXTRA (opcional):
48+
* Crea un decorador que sea capaz de contabilizar cuántas veces
49+
* se ha llamado a una función y aplícalo a una función de tu elección.
50+
*/
51+
52+
function callCounter(func) {
53+
function wrapper(...args) {
54+
wrapper.counter++;
55+
const result = func(...args);
56+
console.log(
57+
`Calls number for function "${func.name}": ${wrapper.counter}`
58+
);
59+
60+
return result;
61+
}
62+
63+
wrapper.counter = 0;
64+
return wrapper;
65+
}
66+
67+
68+
// First function to test
69+
function printMessage(message = 'Hello there!') {
70+
console.log(message);
71+
}
72+
// Decorate the new function
73+
const decoratedPrintMessage = callCounter(printMessage);
74+
75+
76+
// Second function to test
77+
function multiply(a, b) {
78+
return a * b;
79+
}
80+
const decoratedMultiply = callCounter(multiply);
81+
82+
decoratedPrintMessage('Hello JS'); // 1
83+
decoratedPrintMessage(); // 2
84+
decoratedMultiply(3, 2); // 1
85+
decoratedPrintMessage('Hello JavaScript'); // 3
86+
decoratedMultiply(10, 10); // 2
87+
/** All of this calls print:
88+
* Hello JS
89+
* Calls number for function "printMessage": 1
90+
* Hello there!
91+
* Calls number for function "printMessage": 2
92+
* Calls number for function "multiply": 1
93+
* Hello JavaScript
94+
* Calls number for function "printMessage": 3
95+
* Calls number for function "multiply": 2
96+
*/

0 commit comments

Comments
 (0)