Cumulative standard deviation: Difference between revisions

→‎JS :: functional (ES 6): Added an ES6 draft
(→‎JS :: functional (ES 6): Added an ES6 draft)
Line 2,132:
<pre>0, 1, 0.942809041582063, 0.866025403784439, 0.979795897113273, 1, 1.39970842444753, 2</pre>
 
===Functional (ES 5)===
====ES5====
 
Accumulating across a fold
 
Line 2,162:
<lang JavaScript>[0, 1, 0.9428090415820626, 0.8660254037844386,
0.9797958971132716, 1, 1.3997084244475297, 2]</lang>
 
====ES6====
 
As a map-accumulation:
<lang javascript>(() => {
'use strict';
 
// ---------- CUMULATIVE STANDARD DEVIATION ----------
 
// cumulativeStdDevns :: [Float] -> [Float]
const cumulativeStdDevns = ns => {
const go = ([s, q]) =>
([i, x]) => {
const
_s = s + x,
_q = q + (x * x),
j = 1 + i;
return [
[_s, _q],
Math.sqrt(
(_q / j) - Math.pow(_s / j, 2)
)
];
};
return mapAccumL(go)([0, 0])(ns)[1];
};
 
// ---------------------- TEST -----------------------
const main = () =>
showLog(
cumulativeStdDevns([
2, 4, 4, 4, 5, 5, 7, 9
])
);
 
// --------------------- GENERIC ---------------------
 
// mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
const mapAccumL = f =>
// A tuple of an accumulation and a list
// obtained by a combined map and fold,
// with accumulation from left to right.
acc => xs => [...xs].reduce((a, x, i) => {
const pair = f(a[0])([i, x]);
return [pair[0], a[1].concat(pair[1])];
}, [acc, []]);
 
 
// showLog :: a -> IO ()
const showLog = (...args) =>
console.log(
args
.map(x => JSON.stringify(x, null, 2))
.join(' -> ')
);
 
// MAIN ---
return main();
})();</lang>
{{Out}}
<pre>[
0,
1,
0.9428090415820626,
0.8660254037844386,
0.9797958971132716,
1,
1.3997084244475297,
2
]</pre>
 
=={{header|jq}}==
9,655

edits