I'm not good at determining time complexities and memory complexities and would appreciate it if someone could help me out.
I have an algorithm that returns data from cache or fetch data if it's not in cache, I am not sure what its time and memory complexities would be.
What I am trying to figure out ?
What is its time and memory complexity and why.
What have I done before posting a question on SO ?
I have read this, this, this and many more links.
What I have done so far ?
As I understood from all articles and questions that I read, all my operations with loops are linear. I have 3 loops so it's N+N+N
complexity and we can write it as N
. I think that complexity of getData
is O(n)
. Space complexity is more complex, as I understand it's often equal to time complexity for simple data structures so I think space complexity is also N
but I have cache
object (Hash Table) that save every response from fetchData
, so I don't understand how to calculate it as space complexity.
Function
https://jsfiddle.net/30k42hrf/9/
or
const cache = {};
const fetchData = (key, arrayOfKeys) => {
const result = [];
for (let i = 0; i < arrayOfKeys.length; i++) {
result.push({
isin: arrayOfKeys[i],
data: Math.random()
});
}
return result;
}
const getData = (key, arrayOfKeys) => {
if (arrayOfKeys.length < 1) return null;
const result = [];
const keysToFetch = [];
for (let i = 0; i < arrayOfKeys.length; i++) {
const isin = arrayOfKeys[i];
if (key in cache && isin in cache[key]) {
result.push({
isin,
data: cache[key][isin]
});
} else {
keysToFetch.push(isin);
}
}
if (keysToFetch.length > 0) {
const response = fetchData(key, keysToFetch);
for (let i = 0; i < response.length; i++) {
const { isin, data } = response[i];
if (cache[key]) {
cache[key][isin] = data;
} else {
cache[key] = { [isin]: data }
}
}
return [...result, ...response];
}
return result;
}
// getData('123', ['a', 'b'])
Thanks