Skip to content

Instantly share code, notes, and snippets.

@Aryaman1706
Created November 16, 2021 14:10
Show Gist options
  • Save Aryaman1706/0217d4b6c69e4b1689f150c74d98c601 to your computer and use it in GitHub Desktop.
Save Aryaman1706/0217d4b6c69e4b1689f150c74d98c601 to your computer and use it in GitHub Desktop.
// const arr: number[] = [1, 3, 2, 5, 0];
const findProductOfArr = (arr: number[]): number => {
let product: number = 1;
arr.forEach(num => {
if(num !== 0) product = product * num;
});
return product;
};
const getIdxsOfZeros = (arr: number[]): number[] | null => {
const idxsOfZeros: number[] = [];
arr.forEach((num, idx) => {
if(num === 0) idxsOfZeros.push(idx)
});
return idxsOfZeros.length > 0 ? idxsOfZeros : null;
};
const fn: () => void = () => {
const arr: number[] = [1, 2, 0, 4, 0];
let resultArr: number[] = arr;
const wholeArrProduct = findProductOfArr(arr);
const zeroIdxs = getIdxsOfZeros(arr);
if(zeroIdxs){
resultArr = resultArr.fill(0);
zeroIdxs.forEach(idx => {
resultArr[idx] = wholeArrProduct;
});
} else {
resultArr = arr.map(num => wholeArrProduct/num);
}
console.log(JSON.stringify(resultArr));
};
fn();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment