Skip to content

Instantly share code, notes, and snippets.

@tvolk131
Created August 31, 2017 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvolk131/ff815ef94b2cae2c3f877b0ba48efc81 to your computer and use it in GitHub Desktop.
Save tvolk131/ff815ef94b2cae2c3f877b0ba48efc81 to your computer and use it in GitHub Desktop.
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
let products = [];
let product = 1;
nums.forEach((num, i) => {
products[i] = product;
product *= num;
});
product = 1;
for (let i = nums.length - 1; i >= 0; i--) {
products[i] *= product;
product *= nums[i];
}
return products;
};
class Tests {
constructor () {
this.passed = 0;
this.failed = 0;
}
test (val1, val2, name) {
if (JSON.stringify(val1) === JSON.stringify(val2)) {
this.passed++;
} else {
this.failed++;
console.error('Failed: ' + name + ', expected ' + val1 + ' to equal ' + val2);
}
}
report () {
console.log('Passed ' + this.passed + ' tests');
console.log('Failed ' + this.failed + ' tests');
}
run () {
this.test(productExceptSelf([1, 2, 3]), [6, 3, 2], 'foo');
this.test(productExceptSelf([2, 3, 4]), [12, 8, 6], 'foo');
this.test(productExceptSelf([2, 3, 4, 0]), [0, 0, 0, 24], 'foo');
this.test(productExceptSelf([1, 3, 4, 0]), [0, 0, 0, 12], 'foo');
this.test(productExceptSelf([24, 31, 5, 13, 7, 433]), [6107465, 4728360, 29315832, 11275320, 20939880, 338520], 'foo');
this.test(productExceptSelf([-3, 6, -2, 5, 5, 7]), [-2100, 1050, -3150, 1260, 1260, 900], 'Should handle negative numbers');
this.report();
}
}
new Tests().run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment