Power set: Difference between revisions

Content added Content deleted
Line 1,540: Line 1,540:
=={{header|JavaScript}}==
=={{header|JavaScript}}==


===Imperative===
===ES5===
====Iteration====

Uses a JSON stringifier from http://www.json.org/js.html
Uses a JSON stringifier from http://www.json.org/js.html


Line 1,563: Line 1,563:
<pre>[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3],[4],[1,4],[2,4],[1,2,4],[3,4],[1,3,4],[2,3,4],[1,2,3,4]]</pre>
<pre>[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3],[4],[1,4],[2,4],[1,2,4],[3,4],[1,3,4],[2,3,4],[1,2,3,4]]</pre>



===Functional (ES 5)===
====Functional composition====


{{trans|Haskell}}
{{trans|Haskell}}
Line 1,596: Line 1,597:
"set which contains only the empty set ->":[[], [[]]]
"set which contains only the empty set ->":[[], [[]]]
}</lang>
}</lang>

===ES6===

<lang JavaScript>(() => {
'use strict';

// powerset :: [a] -> [[a]]
const powerset = xs =>
xs.reduceRight((a, x) => a.concat(a.map(y => [x].concat(y))), [
[]
]);


// TEST
return {
'[1,2,3] ->': powerset([1, 2, 3]),
'empty set ->': powerset([]),
'set which contains only the empty set ->': powerset([
[]
])
};
})()</lang>

{{Out}}
<lang JavaScript>{"[1,2,3] ->":[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]],
"empty set ->":[[]],
"set which contains only the empty set ->":[[], [[]]]}</lang>


=={{header|jq}}==
=={{header|jq}}==