Skip to content

Instantly share code, notes, and snippets.

@christianscott
Last active May 12, 2017 09:22
Show Gist options
  • Save christianscott/b105ac64b040a82b3217c874863c595b to your computer and use it in GitHub Desktop.
Save christianscott/b105ac64b040a82b3217c874863c595b to your computer and use it in GitHub Desktop.
Python-style destructured for loops in ES6 javascript
// Write a new zip as we don't have one in js
const zip = (first, second) => {
return [...first].map((x, i) => [x, second[i]])
}
const match = (first, second) => {
const seen = new Map()
const zipped = zip(first, second)
for (let [x, y] of zipped) {
if (seen.has(x)) {
if (seen.get(x) !== y) {
return false
}
} else {
seen.set(x, y)
}
}
return true
}
// Here's the old (arguably much clearer) way of doing this
function matchOld(first, second) {
var seen = {}
for (let i = 0; i < first.length; i++) {
var x = first[i]
var y = second[i]
if (seen[x]) {
if (seen[x] !== y) {
return false
}
} else {
seen[x] = y
}
}
return true
}
# Python equivalent of match()
def match(first, second):
seen = dict()
for x, y in zip(first, second):
if x in seen:
if seen[x] != y:
return False
else:
seen[x] = y
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment