Last active
August 8, 2022 12:50
-
-
Save MVAodhan/93bf7a33be89ce33821a7c7ea1ded833 to your computer and use it in GitHub Desktop.
This file contains 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
// This week’s question: | |
// Given a list, swap every two adjacent nodes. Something to think about: How would your code change if this were a linked list, versus an array? | |
const args = [2, 1, 4, 3]; | |
const swapPairs = (args) => { | |
let secondInPair = []; | |
let firstInPair = []; | |
let swapedPairs = []; | |
let error = 'Input Array not even, please provide an array with an even number of children' | |
if (args.length % 2 !== 0) return error; | |
for (const item in args) { | |
if (args[item] % 2 !== 0) { | |
secondInPair = [...secondInPair, args[item]]; | |
} else { | |
firstInPair = [...firstInPair, args[item]]; | |
} | |
} | |
for (let item in secondInPair) { | |
let newPair = [secondInPair[item], firstInPair[item]]; | |
swapedPairs = [...swapedPairs, ...newPair]; | |
} | |
return swapedPairs; | |
}; | |
const swapedPairs = swapPairs(args); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment