Last active
February 24, 2019 19:30
-
-
Save abdullahceylan/f03952a97bd940277983e667d94d33af to your computer and use it in GitHub Desktop.
Balance points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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