Skip to content

Instantly share code, notes, and snippets.

@diogobaltazar
Last active January 20, 2019 17:50
Show Gist options
  • Save diogobaltazar/c6b7974e39f25a039cc1ac5aecc962ad to your computer and use it in GitHub Desktop.
Save diogobaltazar/c6b7974e39f25a039cc1ac5aecc962ad to your computer and use it in GitHub Desktop.
filter | map | reduce
// js

//***************************************************************************
// USE CASE
// 
// SUM first 100 even integers
//***************************************************************************

n = [...Array(100).keys()]      // get indexes starting at 0
        .map(_ => ++_)          // inc
even = n.filter(_ => !(_ % 2))
evenSum = even.reduce((acc, _) => acc + _, 0)

// (element, index) => 
> A = {a: [1, 2], b: ['one', 'two']}
> A.a.map((elem, index) => elem + ';' + A.b[index])
["1;one", "2;two"]

//***************************************************************************
// USE CASE
// 
// Create strings with values concatenated from the different arrays, in that
// the first element of the first array is concatenated with all the elements
// of the second, and so forth.
//***************************************************************************

> A = []
> "abcdefghijklmnopqrstuvwxyz".split('').forEach(char => A.push(char))  // alphabet
> B = [...Array(A.length).keys()].map(_ => ++_)                         // integers 1 to alphabet length
> index = 1
> C.forEach(_ => CD[_] = D[index++])                                    
> A.map(a => 
	B.map(b => 
		id++ + ';' + a + ';' + b
)).reduce((acc, e) => acc.concat(e), [])
["703;a;1", ]
# python

#***************************************************************************
# USE CASE
# 
# SUM first 100 even integers
#***************************************************************************

from functools import reduce
n = map(lambda _ : _, range(100))
even = filter( lambda _ : _ % 2 == 0, n )
evenSum = reduce(lambda x, y : x + y, even)

#***************************************************************************

> B = np.arange(1, 11)
> np.array(list(map(lambda _: _ > 5, B)))
array([False, False, False, False, False,  True,  True,  True,  True,
        True])
> B > 5
array([False, False, False, False, False,  True,  True,  True,  True,
        True])
> B[B > 5]
array([ 6,  7,  8,  9, 10])
> np.array(list(filter(lambda _: _ > 5, B)))
array([ 6,  7,  8,  9, 10])
	
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment