After successfully converting the JavaScript function to Typescript, I encountered an issue with the line
if (!(key * key) in frequencyCounter2) {
. The error message displayed was: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."
I attempted to typecast key as a number to resolve the problem, but unfortunately, it did not work. Is it generally not recommended to perform this operation when working with Typescript?
// The function sameOn accepts two arrays and should return true if every value in the array has its corresponding
// value squared in the second array. The frequency of values must be the same.
function sameOn(arrA: number[], arrB: number[]): boolean {
// complexity O(n): If arr is 1000 lines, this runs 2000 times
if (arrA.length !== arrB.length) {
return false;
}
type CountType = {
[key: number] : number
}
const frequencyCounter1: CountType = {};
const frequencyCounter2: CountType = {};
for (const val of arrA) {
frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1;
}
for (const val of arrB) {
frequencyCounter2[val] = (frequencyCounter2[val] || 0) +1;
}
for (const key in frequencyCounter1) {
if (!(key * key) in frequencyCounter2) {
return false;
}
if (frequencyCounter2[key * key] !== frequencyCounter1[key]) {
return false;
}
}
return true;
}
sameOn([1,2,3,2], [4,1,9,4]) // returns true