Last active
May 12, 2017 09:22
-
-
Save christianscott/b105ac64b040a82b3217c874863c595b to your computer and use it in GitHub Desktop.
Python-style destructured for loops in ES6 javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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