RosettaCodeData/Task/Permutations/JavaScript/permutations-6.js

40 lines
956 B
JavaScript
Raw Normal View History

2017-09-23 10:01:46 +02:00
(() => {
2016-12-05 22:15:40 +01:00
'use strict';
2017-09-23 10:01:46 +02:00
// permutations :: [a] -> [[a]]
2019-09-12 10:33:56 -07:00
const permutations = xs => {
const go = xs => xs.length ? (
concatMap(
x => concatMap(
ys => [[x].concat(ys)],
go(delete_(x, xs))), xs
)
) : [[]];
return go(xs);
};
2016-12-05 22:15:40 +01:00
2019-09-12 10:33:56 -07:00
// GENERIC FUNCTIONS ----------------------------------
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
// concatMap :: (a -> [b]) -> [a] -> [b]
2019-09-12 10:33:56 -07:00
const concatMap = (f, xs) =>
xs.reduce((a, x) => a.concat(f(x)), []);
2016-12-05 22:15:40 +01:00
2019-09-12 10:33:56 -07:00
// delete :: Eq a => a -> [a] -> [a]
const delete_ = (x, xs) => {
const go = xs => {
return 0 < xs.length ? (
(x === xs[0]) ? (
xs.slice(1)
) : [xs[0]].concat(go(xs.slice(1)))
) : [];
}
return go(xs);
};
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
// TEST
2019-09-12 10:33:56 -07:00
return JSON.stringify(
permutations(['Aardvarks', 'eat', 'ants'])
);
2017-09-23 10:01:46 +02:00
})();