Pascal's triangle: Difference between revisions
→Functional (ES5): Simpler Pascal function (translating one of the Haskell versions)
(→Functional (ES5): Simpler Pascal function (translating one of the Haskell versions)) |
|||
Line 2,167:
===Functional (ES5)===
{{Trans|Haskell}}
<lang JavaScript>(function (n) {
'use strict';
// A Pascal triangle of n rows
function pascalTriangle(n) {▼
//
return range(1, n - 1)
function pairSums(lst) {▼
.concat(
[zipWith(
return a + b
}, [0].concat(lstPreviousRow),
lstPreviousRow.concat(0)
)]
}, [[1]]);
}
// GENERIC FUNCTIONS
return lst.length ? [1].concat(▼
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
▲ pairSums(lst)
xs.map(function (x, i) {
return f(x, ys[i]);
) : undefined;
}
//
});
}
// TEST
var lstTriangle =
// FORMAT OUTPUT AS WIKI TABLE
// [[a]] -> bool -> s -> s
function wikiTable(lstRows, blnHeaderRow, strStyle) {
return '{| class="wikitable" ' + (
strStyle ? 'style="' + strStyle + '"' : ''
) + lstRows.map(function (lstRow, iRow) {
var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');
return '\n|-\n' + strDelim + ' ' + lstRow.map(function (
return typeof v === 'undefined' ? ' ' : v;
}).join(' ' + strDelim + strDelim + ' ');▼
})
}).join('') + '\n|}';▼
}▼
▲ }
var lstLastLine = lstTriangle.slice(-1)[0],
lngBase = (lstLastLine.length * 2) - 1,
nWidth = lstLastLine.reduce(function (a, x) {
var d = x.toString()
}, 1) * lngBase;
return [
wikiTable(
lstTriangle.map(function (lst) {
return lst.join(';;')
.split(';');
▲ }).map(function (line, i) {
var lstPad = Array((lngBase - line.length) / 2);
▲ }),
return lstPad.concat(line)
▲ false,
.concat(lstPad);
'text-align:center;width:' + nWidth + 'em;height:' + nWidth +▼
}),
'em;table-layout:fixed;'▼
false,
▲ 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
▲ 'em;table-layout:fixed;'
),
|