Skip to content

Instantly share code, notes, and snippets.

@wopian
Created May 17, 2017 14:48
Show Gist options
  • Save wopian/883c46f00226a6b34996d8349408fe02 to your computer and use it in GitHub Desktop.
Save wopian/883c46f00226a6b34996d8349408fe02 to your computer and use it in GitHub Desktop.
function pivot (array) {
let total = array.reduce((accumulator, value) => accumulator + value, 0)
let left = 0
// Iterate over each item in array
for (let i = 0; i < array.length; i++) {
// Subtract its value from the total
total -= array[i]
// If current total is equal to the left total, then
// we've hit the index we need, returns the index
if (total === left) return i
// Otherwise we carry on and increment the left total
left += array[i]
}
// No such index exists
return -1
}
// Barebones unit testing
function check (input, expected) {
if (pivot(input) === expected) return true
return false
}
[
{arr: [1,4,6,3,2], exp: 2},
{arr: [1,4,1,5,3,3], exp: 3},
{arr: [8,1,3,4,1], exp: 1},
{arr: [2,4,4,2,9], exp: -1}
].forEach(test => {
console.log(`${test.arr} should return ${test.exp}: ${check(test.arr, test.exp)}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment