cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Looking for quick-add? Try the external resource search, it's quicker and gives you access to the most recent version of thousands of libraries. ☝️

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <!DOCTYPE html>
<html>
<head>
	<title>Pascal's Triangle</title>
</head>
<body>
	<h1>Pascal's Triangle</h1>
  <strong>Code:</strong>
  <code>pascal(8, 3,'|','pascal-container')</code>
  <p><strong>Result:</strong></p>
	<div id="pascal-container"></div>
</body>
</html>
            
          
!
            
              /**
 * Pascal’s Triangle
 * @author Arthur Khachatryan <arthurk55@gmail.com>
 * @version 1.0.0
 * @description Function that takes in number of rows, the number to use, the empty character and DOM container (if results are to be output on page) and returns an instance of Pascal’s Triangle.
 * @param {number}		rows 			the number of rows to display
 * @param {number} 		numToUse 		the base number to be used in triangle
 * @param {[string]} 	emptyChar 		the empty character to use (for console only, not relevant for use on page)
 * @param {[string]} 	DOMContainer 	the element ID of the container to be used to display the triangle on the page 
 */
function pascal(rows, numToUse, emptyChar, DOMContainer) {
	var aRows = []
      , aCols = []
	  , iR = 0
	  , iC = 0
	  , num = numToUse || 1
	  , ins = null
	  , empty = emptyChar || null
	  , columns = rows + (rows - 1)
	  , startCol = Math.floor(columns / 2)
	  , topLeft
	  , topRight
	;

	// builds rows
	for (; iR < rows; iR++) {
		// build columns
		for (; iC < columns; iC++) {

			// if first row, we need a starting position (middle of table)
			if (iR === 0) {
				if (iC === startCol) {
					ins = num;
				} else {
					ins = null;
				}

			// not first row
			} else {
					topLeft = aRows[iR - 1][iC - 1];
					topRight = aRows[iR - 1][iC + 1];

					// checkered null cell
					if (topLeft == null && topRight == null) {
						ins = null;
					// right side cell with 1-sided value
					} else if (topLeft == null && topRight != null) {
						ins = topRight;
					// left side cell with 1-sided value
					} else if (topLeft != null && topRight == null) {
						ins = topLeft;
					// inside cell with value
					} else {
						ins = topLeft + topRight;
					}
			}
			aCols.push(ins);
		}

		aRows.push(aCols);

		// clear column data for new row
		aCols = [];
        iC = 0;
	}

	iR = 0;
	iC = 0;

	// loop through again and replace null with prescribed empty char
	for (; iR < rows; iR++) {
		for (; iC < columns; iC++) {
			if (aRows[iR][iC] == null) {
				aRows[iR][iC] = empty;
			}
		}
		iC = 0;
	}

	// if a DOM container is passed in use it to constrct an HTML table inside
	if (DOMContainer) {
		iR = 0;
		iC = 0;

		//var container = document.getElementById(DOMContainer);

		var container = document.getElementById(DOMContainer)
			, tr
			, td
			, tdVal
			, table = _appendChild({
	            elParent: container,
	            newTag:   'table',
	            newElID:  'pascal-table',
	            attribs: [
                    { aName: 'border', aVal: '0' },
                    { aName: 'cellspacing', aVal: '1' },
                    { aName: 'cellpadding', aVal: '3' }
                ]
	        })
	    ;

		// loop through again and replace null with prescribed empty char
		for (; iR < rows; iR++) {
			tr = _appendChild({
	            elParent: table,
	            newTag:   'tr',
	            newElID:  'pascal-tr-' + iR
	        });
			for (; iC < columns; iC++) {
				if (aRows[iR][iC] == empty) {
					aRows[iR][iC] = '';
				}
				td = _appendChild({
		            elParent: tr,
		            newTag:   'td',
		            newElID:  'pascal-td-' + iC,
		            attribs: [
	                    { aName: 'align', aVal: 'center' }
	                ],
		            sText:    aRows[iR][iC]
		        });
			}
			iC = 0;
		}

	}
  
    console.table(aRows);

    /**
     * Append DOM element with its own features to parent element
     * @param       {object}        args                the arguments object
     * @property    {DOMElement}    args.elParent       the parent DOM element   
     * @property    {string}        args.newTag         the new HTML tag to be created  
     * @property    {string}        args.newElID        the new ID to be applied to the element being created  
     * @property    {array}         args.newElClasses   the list of classes to be added to the element being created 
     * @property    {array}         args.attribs        the list of attribute object for name and value to be added to the element being created
     * @property    {string}        args.sText          the text to be added to the DOM node 
     * @return      {DOMElement}                        the newly created DOM element 
     */
    function _appendChild (args) {
        var elParent       = args.elParent
            , newTag       = args.newTag
            , newElID      = args.newElID
            , newEl        = document.createElement(newTag)
            , newElClasses = args.elClasses
            , newElAttr    = args.attribs || null
            , i = 0
        ;

        newEl.id = newElID;

        if (args.sText) {
            var newContent = document.createTextNode(args.sText);
            //add the text node to the newly created div.
            newEl.appendChild(newContent);
        }
        if (newElClasses) {
            newEl.className = newElClasses;
        }

        // if attribute(s), iterate and add all
        if (newElAttr) {
            var newAttr
                , newElAttrLen = newElAttr.length
            ;

            for (; i < newElAttrLen; i++) {
                newAttr = document.createAttribute(newElAttr[i].aName);
                newAttr.value = newElAttr[i].aVal;
                newEl.setAttributeNode(newAttr); // set attribute
            }
        }

        elParent.appendChild(newEl);
        
        return newEl;
    }

}

// run function and embed results onto page
pascal(8, 3,'|','pascal-container')
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console