Skip to content

Commit a8e26ce

Browse files
committed
Section 04 :Promises and Time - Part 02 - Done
1 parent 5fdacdb commit a8e26ce

File tree

4 files changed

+66
-0
lines changed

4 files changed

+66
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
var timeLimit = function (fn, t) {
2+
return async function (...args) {
3+
return new Promise((resolve, reject) => {
4+
const timeout = setTimeout(() => {
5+
reject('Time Limit Exceeded')
6+
}, t)
7+
fn(...args)
8+
.then(resolve)
9+
.catch(reject)
10+
.finally(() => clearTimeout(timeout))
11+
})
12+
}
13+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
var TimeLimitedCache = function () {
2+
this.cache = new Map()
3+
}
4+
5+
TimeLimitedCache.prototype.set = function (key, value, duration) {
6+
const valueInCache = this.cache.get(key)
7+
if (valueInCache) {
8+
clearTimeout(valueInCache.timeout)
9+
}
10+
const timeout = setTimeout(() => this.cache.delete(key), duration)
11+
this.cache.set(key, { value, timeout })
12+
return Boolean(valueInCache)
13+
}
14+
15+
TimeLimitedCache.prototype.get = function (key) {
16+
return this.cache.has(key) ? this.cache.get(key).value : -1
17+
}
18+
19+
TimeLimitedCache.prototype.count = function () {
20+
return this.cache.size
21+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
var debounce = function (fn, t) {
2+
let id
3+
return function (...args) {
4+
clearTimeout(id)
5+
id = setTimeout(() => fn(...args), t)
6+
}
7+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function promiseAll(functions) {
2+
// Keep track of resolved values, rejections, and the number of pending promises
3+
const resolvedValues = []
4+
let rejections = null
5+
let pending = functions.length
6+
7+
return new Promise((resolve, reject) => {
8+
functions.forEach((func, index) => {
9+
func()
10+
.then((value) => {
11+
resolvedValues[index] = value
12+
pending--
13+
if (pending === 0 && !rejections) {
14+
resolve(resolvedValues) // All promises resolved
15+
}
16+
})
17+
.catch((error) => {
18+
if (!rejections) {
19+
rejections = error // Store the first rejection
20+
reject(error) // Reject the main promise
21+
}
22+
})
23+
})
24+
})
25+
}

0 commit comments

Comments
 (0)