Skip to content

Latest commit

 

History

History
92 lines (69 loc) · 1.78 KB

03_pairs.org

File metadata and controls

92 lines (69 loc) · 1.78 KB

Solutions for pairs

@cyborg_ean

Decided to do a prototypal solution, just for the heck of it.

const options = {
  YouTube: ['Saved'],
  AppleMusic: ['Saved', 'Played', 'Skipped'],
  Spotify: ['Saved', 'Played'],
  Napster: ['Saved', 'Skipped']
}

Object.prototype.pairMap = function(){
    const result = [];
    const list   = Object.keys(this);
    list.forEach((x) => {
        this[x].forEach((pair) => {
            result.push([x, pair]);
        })
    });

    return result
}

const result = options.pairMap();
console.log(result);

@sibiar600

https://repl.it/@JamesPascual/ltcjs-challenge-pair-options

@lou

result = [(kv[0], el) for kv in options.iteritems() for el in kv[1]]

@jyamad

python

[(k,x) for k,xs in options.items() for x in xs]

more explanatory names (and as a generator expression)

((key, action)
  for key, actions in options.items()
  for action in actions)

javascript

flattenPairs(options)

function flattenPairs(obj) {
    const pairs = ([k, vs]) => vs.map(v => [k,v])
    return [].concat(...Object.entries(obj).map(pairs))
}
Object.keys(options)
     .map(key => options[key]
          .map(action => [key, action]))
     .reduce((acc, a) => [...acc, ...a])

Haskell

The first line here is unnecessary, but acts as documentation:

flattenPairs :: [(a, [b])] -> [(a, b)]
flattenPairs xs = [(a, b) | (a, bs) <- xs, b <- bs]

More obscure Haskell:

flattenPairs2 = foldMap $ \(a, bs) -> (,) a <$> bs
{-# LANGUAGE: TupleSections #-}
flattenPairs3 = foldMap pairs
  where pairs (t, bs) = fmap (t,) bs