-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
82 lines (73 loc) · 2.1 KB
/
index.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
'use strict';
/**
* Prototype for implementation of debounce concept for any function.
*
* @param {int} [intervalTime=10000] - time interval for debounce.
*/
Function.prototype.debounce = function (intervalTime = 10000) {
const fn = this;
let timer = null;
return async function (...params) {
if (timer) {
clearTimeout(timer);
}
return new Promise((resolve) => {
timer = setTimeout(async () => {
const data = await fn.apply(null, params);
resolve(data);
}, intervalTime);
})
};
}
/**
* Method to make rest api call.
*
* @param {string} url - rest api url.
* @returns {Promise} Response of api in json format.
*/
async function ajexCall(url = "") {
return await (await fetch(url)).json();
}
/**
* Method to get some browser data.
*
* @returns {Object} Object with some browser details.
*/
async function webApis() {
const { protocol, hostname, port, search } = window.location || {};
const { platform, vendor } = window.navigator || {};
return {
protocol,
hostname,
port,
search,
platform,
vendor
};
}
/**
* Method to multiple all elements of array.
*
* @param {Array} arr - list of integer no.
* @returns {int} final result of multiplication
*/
function multiplication(...arr) {
return arr.reduce((result, ele) => result * ele, 1);
}
// get debounce instance of functions.
const getIpAddress = ajexCall.debounce(1000);
const getBrowserInfo = webApis.debounce(2000);
const multiplyAll = multiplication.debounce(500);
async function fnForAsyncCall() {
const apiRes = await getIpAddress("https://api.ipify.org?format=json");
const calcResult = await multiplyAll(5, 10, 2);
console.log(" using async/await : apiRes > ", apiRes);
console.log(" using async/await : calcResult > ", calcResult);
}
function fnForSyncCall() {
getBrowserInfo().then((result) => {
console.log(" using sync : browserDetail > ", result);
}).catch((err) => {
console.error(" using sync : browserDetail > ", err);
});
}