Skip to content

Instantly share code, notes, and snippets.

@MVAodhan
Last active August 8, 2022 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MVAodhan/93bf7a33be89ce33821a7c7ea1ded833 to your computer and use it in GitHub Desktop.
Save MVAodhan/93bf7a33be89ce33821a7c7ea1ded833 to your computer and use it in GitHub Desktop.
// 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