Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DmitryOlkhovoi/8d0aade90b0288a711e1500b2cd745d6 to your computer and use it in GitHub Desktop.
Save DmitryOlkhovoi/8d0aade90b0288a711e1500b2cd745d6 to your computer and use it in GitHub Desktop.
eloquent javascript The sum of a range
function sum(numbers) {
return numbers.reduce((acc, current) => acc + current, 0)
}
function range(start, end, step = 1) {
const rangeArray = []
const direction = end > start
for(let i = start; (direction ? (i <= end) : (i >= end)); i += step) {
rangeArray.push(i)
}
return rangeArray
}
console.log(range(1, 10))
console.log(range(2, 5))
console.log(range(1, 10, 2))
console.log(range(5, 2, -1))
console.log(sum(range(1, 2)))
console.log(sum(range(10, -20, -1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment