Why output is different in following:
- 1st scenario: prints
https://appmagic.io/modern/1
https://appmagic.io/modern/1
let urlHash = {};
const rootURL = 'http://tinyurl.com/';
var encode = function(longUrl) {
let hash = Date.now().toString(36);
urlHash[hash] = longUrl;
return `${rootURL}${hash}`
};
var decode = function(shortUrl) {
return urlHash[shortUrl.substring(rootURL.length)]
};
let url1 = encode("https://appmagic.io/classic/1");
let url2 = encode("https://appmagic.io/modern/1");
console.log(decode(url1));
console.log(decode(url2));
- 2nd scenario: prints
https://appmagic.io/classic/1
https://appmagic.io/modern/1
let urlHash = {};
const rootURL = 'http://tinyurl.com/';
var encode = function(longUrl) {
let hash = Date.now().toString(36);
console.log({hash}); // difference in code
console.log({hash}); // difference in code
urlHash[hash] = longUrl;
return `${rootURL}${hash}`
};
var decode = function(shortUrl) {
return urlHash[shortUrl.substring(rootURL.length)]
};
let url1 = encode("https://appmagic.io/classic/1");
let url2 = encode("https://appmagic.io/modern/1");
console.log(decode(url1));
console.log(decode(url2));
My guess is:
Since
Date.now()
gives values in milisecond, without console (IO operation i.e. time consuming sync operations) they get evaluate in nano-second and hash remains same, So the similar output in 1st scenarioBut if we are adding console (IO operation i.e. time consuming sync operations) it delay operation for more than millisecond and different output comes in 2nd scenario.
I'm not sure if my perception is correct. Can any-one provide better/correct explanation.
If my guess is right, how can I create collision free fast hash,
thinking to use
window.performance.now()
but it is also not available in all browsers