Two sum: Difference between revisions

Content added Content deleted
(→‎JS ES6: Added comments on access to indices, and skipping the 'lower triangle' of a cartesian grid (where iy < ix))
Line 189: Line 189:


=={{header|JavaScript}}==
=={{header|JavaScript}}==

===ES5===

Nested calls to concatMap yield the cartesian product of the list with itself, and
functions passed to Array.map() have access to the array index in their second argument.
Returning [] where the y index is lower than then x index ignores the 'lower triangle' of the cartesian grid,
so mirror-image number pairs are not considered.
Returning [] where the sum is not that required similarly acts as a filter – all of the empty lists
in the map are eliminated by the concat.

<lang JavaScript>(function () {
var concatMap = function (f, a) {
return [].concat.apply([], a.map(f))
};

return function (n, xs) {
return concatMap(function (x, ix) {
return concatMap(function (y, iy) {
return iy < ix ? [] : x + y === n ? [
[ix, iy]
] : []
}, xs)
}, xs)
}(21, [0, 2, 11, 19, 90]);
})();
</lang>

{{Out}}
<lang JavaScript>[[1,3]]</lang>


===ES6===
===ES6===