` ````
<div id="container"></div>
```

` ````
span {
display: inline-block;
text-align: center;
}
#container>div {
padding-top: 5px
}
```

` ````
/**
* A Pascal Triangle in ES6.
* (https://en.wikipedia.org/wiki/Pascal%27s_triangle)
*
* Use: scroll down to the instantiation and add the desired
* number of lines
*
* Author: Jean-Pierre Sierens
**/
class PascalTriangle {
constructor (levels) {
// the number of levels the triangle will have
this.levels = levels;
}
create () {
this.createLevel(1);
}
createLevel (level, prevNums) {
//get the numbers for this level
let numbers = this.calculateLevelNumbers(level, prevNums);
//log the level
this.logLevel(numbers, level);
//go to the next level (if its not the last)
if (level !== this.levels) return this.createLevel(level+1, numbers);
}
calculateLevelNumbers (level, prevNums) {
let numbers = [];
if (level === 1) {
numbers.push(1);
return numbers;
}
// iterate over each number in the level
for (let i = 0; i < level; i++) {
// if it's the first or last number it's always 1
if (i === 0 || i === level - 1) {
numbers.push(1);
} else {
// the number becomes the sum of the two above him
numbers.push( prevNums[i-1] + prevNums[i] );
}
}
return numbers;
}
logLevel (numbers, level) {
//create empty div where the numbers will go (holder)
let $numbers = $("<div></div>");
//padding for each holder, so that you get a nice triangle
let padding = (this.levels - level) * this.levels*2;
$numbers.css('padding-left', padding);
//for each number append a span with a width, then append it to the numbers holder
//note: arrow function for mantaining lexical scope (fuck yeah)
numbers.forEach( (number, index) => {
$numbers.append(
"<span style='width: "+this.levels*4+"px'>"+number+"</span>"
);
});
$('#container').append($numbers);
}
}
// Instantiation
// change the number to add more or less levels to the triangle
let pt = new PascalTriangle(10);
pt.create();
```

999px

Loading
..................

Alt F
Opt F
Find & Replace

Also see: Tab Triggers