Skip to content

Instantly share code, notes, and snippets.

@pablodenadai
Created February 8, 2017 01:10
Show Gist options
  • Select an option

  • Save pablodenadai/b23162b5b581bda9d3e8fb4fbec0d6de to your computer and use it in GitHub Desktop.

Select an option

Save pablodenadai/b23162b5b581bda9d3e8fb4fbec0d6de to your computer and use it in GitHub Desktop.
Implementation of Pascal Triangle using Recursive Function - JavaScript ES6
const pascalTriangleRecursive = (n, arr) => {
if (!arr) arr = [[1]] // Create triangle
if (n < 2) return arr // Exit
const prevLine = arr[arr.length - 1] // Get previous line
const newLine = [1] // Create new line
// Populate new line
prevLine.forEach((item, index) => {
if (index === 0) return
if (index === prevLine.length) return
newLine.push(prevLine[index] + prevLine[index - 1])
})
newLine.push(1) // Finalise new line
arr.push(newLine) // Insert new line to triangle
return pascalTriangleRecursive(n - 1, arr) // Invoke itself passing the counter and array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment