Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created January 10, 2020 19:04
Show Gist options
  • Save les-peters/032f9660b7fc49b193ba06ef42c455e1 to your computer and use it in GitHub Desktop.
Save les-peters/032f9660b7fc49b193ba06ef42c455e1 to your computer and use it in GitHub Desktop.
2020-01-07
# Implement array.filter() by hand (or whatever your language of choice uses to do this functionality).
def filter(array, filterFunction):
newArray = []
for item in array:
isFilterTrue, updatedItem = filterFunction(item)
if isFilterTrue:
if updatedItem:
newArray.append(updatedItem)
else:
newArray.append(item)
return newArray
def longerThan6(item):
if len(str(item)) > 6:
return True, item
else:
return False, item
print("using Array.prototype.filter() web page for examples")
def over10(item):
if item >= 10:
return True, item
else:
return False, item
print("")
print("filter on values >= 10")
a = [12, 5, 8, 130, 44]
print("input: ", a)
b = filter(a, over10)
print("output: ",b)
print("")
print("filter on strings > 6 characters")
c = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']
print("input: ", c)
d = filter(c, longerThan6)
print("output: ",d)
def apFilter(item):
if item.lower().find('ap') != -1:
return True, item
else:
return False, item
print("")
print("Filter on 'ap'")
e = ['apple', 'banana', 'grapes', 'mango', 'orange']
print("input:", e)
f = filter(e, apFilter)
print("output: ",f)
def doubleValue(item):
doubledItem = 2 * item
return True, doubledItem
print("")
print("Double each input value")
h = [ 1, 2, 3, 4]
print("input: ", h)
j = filter(h, doubleValue)
print("output:" ,j)
print("")
print("Append 'foo' to each word")
def appendFoo(item):
appendedItem = item + "Foo"
return True, appendedItem
print("input: ", e)
k = filter(e, appendFoo)
print("output: ", k)
print("")
print("Demonstrate nested filters: triple each input, then test for being odd")
def tripleValue(item):
tripledItem = 3 * item
return True, tripledItem
def isOdd(item):
if (item % 2) == 1:
return True, item
else:
return False, item
print("input: ", h)
l = filter(filter(h, tripleValue), isOdd)
print("output:", l)
m = [
{ "key": "one", "value": 1},
{ "key": "two", "value": 2},
{ "key": "three", "value": 3},
{ "key": "four", "value": 4},
{ "key": "five", "value": 5}
]
def dictValueIsOdd(item):
if (item["value"] % 2) == 1:
return True, item
else:
return False, item
print("")
print("Filter based on value within dictionary")
print("input:", m)
n = filter(m, dictValueIsOdd)
print("output: ", n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment