-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1656_design-an-ordered-stream.js
44 lines (40 loc) · 1.2 KB
/
1656_design-an-ordered-stream.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
/**
* Title: Design an Ordered Stream
* Description: There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.
* Author: Hasibul Islam
* Date: 28/04/2023
*/
/**
* @param {number} n
*/
var OrderedStream = function (n) {
// initialize array
this.arr = [];
// start pointer at index of 0
this.p = 0;
//set array to have length of n
this.arr.length = n;
};
/**
* @param {number} idKey
* @param {string} value
* @return {string[]}
*/
OrderedStream.prototype.insert = function (idKey, value) {
// push the value into array at index of idKey
this.arr[idKey - 1] = value;
// initialize result array
let result = [];
// while the pointer has a value, push that value into the result array and advance the pointer
while (this.arr[this.p]) {
result.push(this.arr[this.p]);
this.p++;
}
// return the result array which will either be empty if the pointer was null, or will have the chunks pushed into it
return result;
};
/**
* Your OrderedStream object will be instantiated and called as such:
* var obj = new OrderedStream(n)
* var param_1 = obj.insert(idKey,value)
*/