Pascal's triangle: Difference between revisions
→JS ES5 Functional: Updated primitives
m (→JS ES6: ( clearer formatting/commenting of main function )) |
(→JS ES5 Functional: Updated primitives) |
||
Line 2,383:
====Functional====
{{Trans|Haskell}}
<lang JavaScript>(function (n) {
'use strict';
// PASCAL TRIANGLE --------------------------------------------------------
// pascal :: Int -> [[Int]]
function pascal(n) {
return
return append(a,
[1] // Initial seed row
], enumFromTo(1, n - 1));
};▼
▲ return a
▲ );
▲ }, [[1]]);
▲ }
// GENERIC FUNCTIONS ------------------------------------------------------
};▼
// enumFromTo :: Int -> Int -> [Int]
function enumFromTo(m, n) {
length: Math.floor(n - m) + 1
};
// foldl :: (b -> a -> b) -> b -> [a] -> b
function foldl(f, a, xs) {
return xs.reduce(f, a);
};
// foldr (a -> b -> b) -> b -> [a] -> b
function foldr(f, a, xs) {
return xs.reduceRight(f, a);
};
// map :: (a -> b) -> [a] -> [b]
function map(f, xs) {
return xs.map(f);
};
// min :: Ord a => a -> a -> a
function min(a, b) {
};
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
function zipWith(f, xs, ys) {
return
length: min(xs.
}, function
})
};
▲ // range :: Int -> Int -> [Int]
▲ function range(m, n) {
▲ return Array.apply(null, Array(n - m + 1))
▲ .map(function (x, i) {
▲ return m + i;
▲ });
▲ }
// TEST and FORMAT --------------------------------------------------------
var lstTriangle = pascal(n);
// [[a]] -> bool -> s -> s
function wikiTable(lstRows, blnHeaderRow, strStyle) {
return '{| class="wikitable" ' + (strStyle ? 'style="' + strStyle +
return typeof v === 'undefined' ? ' ' : v;
})
Line 2,454 ⟶ 2,468:
var lstLastLine = lstTriangle.slice(-1)[0],
lngBase =
nWidth = lstLastLine.reduce(function (a, x) {
var d = x.toString()
Line 2,461 ⟶ 2,475:
}, 1) * lngBase;
return [wikiTable(lstTriangle.map(function (lst) {
.map(function (line, i)
return lstPad.
▲ return lstPad.concat(line)
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n');▼
▲ }),
▲ false,
▲ 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
▲ ),
▲ JSON.stringify(lstTriangle)
})(7);</lang>
{{Out}}
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;"
|-
Line 2,501 ⟶ 2,505:
<lang JavaScript>[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1],[1,6,15,20,15,6,1]]</lang>
===ES6===
|