Skip to content

Instantly share code, notes, and snippets.

@abdullahceylan
Last active February 24, 2019 19:30
Show Gist options
  • Save abdullahceylan/f03952a97bd940277983e667d94d33af to your computer and use it in GitHub Desktop.
Save abdullahceylan/f03952a97bd940277983e667d94d33af to your computer and use it in GitHub Desktop.
Balance points
function sum(a, b) {
return a + b;
}
var BalancePoint = function(input) {
if (!Array.isArray(input)) {
return -1;
}
var totalSum = input.reduce(sum, 0);
var leftSum = 0;
return input.reduce(function(point, current, i) {
if (i > 0) {
leftSum += input[i-1];
}
var rightSum = totalSum - leftSum - current;
if (leftSum === rightSum) {
point = i;
}
return point;
}, -1);
}
BalancePoint([ 2, 7, 4, 5, -3, 8, 9, -1 ]); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment