Symmetric difference: Difference between revisions
Content deleted Content added
→{{header|Elixir}}: change HashSet(deprecated) -> MapSet |
→{{header|JavaScript}}: ES6 - by composition of functional primitives |
||
Line 1,137: | Line 1,137: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
|||
====Iterative==== |
|||
{{works with|JavaScript|1.6}} |
{{works with|JavaScript|1.6}} |
||
{{works with|Firefox|1.5}} |
{{works with|Firefox|1.5}} |
||
Line 1,194: | Line 1,198: | ||
SymmetricDifference(A,B); // 'Serena','Jim' |
SymmetricDifference(A,B); // 'Serena','Jim' |
||
*/</lang> |
*/</lang> |
||
===ES6=== |
|||
====Functional==== |
|||
By composition of functional primitives: |
|||
<lang JavaScript>(function (a, b) { |
|||
'use strict'; |
|||
let // UNION AND DIFFERENCE |
|||
// union :: [a] -> [a] -> [a] |
|||
union = (xs, ys) => unionBy((a, b) => a === b, xs, ys), |
|||
// difference :: [a] -> [a] -> [a] |
|||
difference = (xs, ys) => |
|||
ys.reduce((a, y) => |
|||
a.indexOf(y) !== -1 ? ( |
|||
delete_(y, a) |
|||
) : a.concat(y), xs), |
|||
// GENERAL PRIMITIVES |
|||
// unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] |
|||
unionBy = (fnEq, xs, ys) => { |
|||
let sx = unique(xs), |
|||
sy = unique(ys); |
|||
return sx.concat( |
|||
sx |
|||
.reduce((a, x) => deleteBy(fnEq, x, a), |
|||
nubBy(fnEq, sy) |
|||
) |
|||
) |
|||
}, |
|||
// unique :: [a] -> [a] |
|||
unique = xs => { |
|||
let dct = xs.reduce( |
|||
(a, x) => (a[x.toString()] = x, a), {} |
|||
); |
|||
return Object.keys(dct) |
|||
.map(k => dct[k]); |
|||
}, |
|||
// deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] |
|||
deleteBy = (fnEq, x, xs) => |
|||
xs.reduce((a, y) => ( |
|||
fnEq(x, y) || a.push(y), |
|||
a |
|||
), []), |
|||
// delete_ :: a -> [a] -> [a] |
|||
delete_ = (x, xs) => |
|||
deleteBy((a, b) => a === b, x, xs), |
|||
// nubBy :: (a -> a -> Bool) -> [a] -> [a] |
|||
nubBy = (fnEq, xs) => { |
|||
let x = (xs.length ? xs[0] : undefined); |
|||
return x !== undefined ? [x].concat( |
|||
nubBy(fnEq, xs.slice(1) |
|||
.filter(y => !fnEq(x, y)) |
|||
) |
|||
) : []; |
|||
}; |
|||
// 'SYMMETRICAL DIFFERENCE' |
|||
return union( |
|||
difference(a, b), |
|||
difference(b, a) |
|||
); |
|||
})( |
|||
["John", "Serena", "Bob", "Mary", "Serena"], |
|||
["Jim", "Mary", "John", "Jim", "Bob"] |
|||
);</lang> |
|||
{{Out}} |
|||
<lang JavaScript>["Serena", "Jim"]</lang> |
|||
=={{header|jq}}== |
=={{header|jq}}== |