I was going about solving some algos on binarysearch.io and came across this problem:
I solved it using JS as follows:
class Solution {
solve(nums) {
const Hash = {};
const Cache = {};
for (let val of nums) {
if (!Hash[val]) {
Hash[val] = 0;
}
Hash[val]++; //implicit else
}
const result = Object.values(Hash).reduce((accum, curr) => {
if (accum && Cache[curr] !== 'unique') {
Cache[curr] = 'unique';
return true
}
return false;
}, true);
return result;
}
}
However, when I tried to solve it with TypeScript, which I'm fairly new to, and I had compilation errors likely caused by the .reduce() method:
class Solution {
solve(nums: Array<number>): boolean {
const Hash = {};
const Cache = {};
for (let val of nums) {
if (!Hash[val]) {
Hash[val] = 0;
}
Hash[val]++; //implicit else
}
const val_arr = Object.values(Hash);
return val_arr.reduce((accum, curr) => {
if (accum && Cache[curr] !== 'unique') {
Cache[curr] = 'unique';
return true;
}
return false;
}, true);
}
}
I'm not certain how to provide the .reduce() method a return type for the seeded initial value. I've tried changing the initial value to have a boolean type, but I still have a compilation error:
return val_arr.reduce((accum, curr) => {
if (accum && Cache[curr] !== 'unique') {
Cache[curr] = 'unique';
return true;
}
return false;
}, true as boolean);
I tried searching if anyone else has this problem, but most posts I've found have objects as the initial value, so I couldn't quite figure it out. It almost appears like the easiest solution is to solve this is to refactor to solve this without using .reduce(), but I simply want to know how to create a TS 'equivalent' to the aforementioned JS solution.
