pairwise(list, options)
Given a list, return a list of all pairs in that list via Array.reduce()
Optionally filter and transform (map) the pairs based on items and indices.
Arguments:
list
(required): The input arrayoptions
(optional) -- See "Options" section for more detailsfilter
: function to match pairsmap
: function to transform pairslimit
: integer limit of pairs, or0
for unlimited (default0
)allowSelfPairs
: boolean whether to allow self pairs (defaultfalse
)
-
Two-Sum from LeetCode: Find all pairs where left + right === target
-
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
-
You may assume that each input would have exactly one solution, and you may not use the same element twice.
const twoSum = (nums, target) => pairwise(nums, { filter: ({ left, right }) => left + right === target, map: ({ leftIdx, rightIdx }) => [leftIdx, rightIdx], limit: 1, allowSelfPairs: false })[0]
{
// filter: function({ left, right, leftIdx, rightIdx })
// Determine which pairs to include in output
//
// Given a pair { left, right, leftIdx, rightIdx }
// Return true to include in output, false to exclude
//
// Default:
filter = ({ left, right, leftIdx, rightIdx }) => true,
// map: function({ left, right, leftIdx, rightIdx })
// Apply transformation to pairs before output
//
// Given a pair { left, right, leftIdx, rightIdx }
// Return a transformed item for the output list
//
// Default:
map = ({ left, right, leftIdx, rightIdx }) => ({
left,
right,
leftIdx,
rightIdx
}),
// limit: integer
// The maximum number of pairs to include, or 0 for no limit
//
// Default:
limit = 0,
// allowSelfPairs: boolean
// Whether to allow self pairs e.g. [1, 2, 3] -> (1,1), (2,2), ...
//
// Default:
allowSelfPairs = false
}