Last active
December 3, 2020 04:35
-
-
Save vignesh865/a2cd9cb5d96571ada31538a5369d227e to your computer and use it in GitHub Desktop.
The function the that flips the given argument.
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
function flipArgs(func) { | |
return function () { | |
reversedArgs = Object.values(arguments).reverse(); | |
func(...reversedArgs); | |
}; | |
} | |
const flipped = flipArgs(function () { | |
console.log(arguments); | |
}); | |
flipped(4, 5, 6); | |
// Extra - Instead of using reverse function, just made another function: reverse using clousre. | |
// Can be used instead of `Object.values(arguments).reverse()` | |
const reverseUsingClosure = function() { | |
const array = Object.values(arguments); | |
const reversedArray = []; | |
function recursor() { | |
let lastValue = array.pop(); | |
reversedArray.push(lastValue); | |
if (array.length === 0) return lastValue; | |
return recursor(); | |
} | |
recursor(); | |
return reversedArray; | |
} | |
// Test cases | |
// 1. expect(flipped(4, 5, 6)).toBe(6, 5, 4) | |
// 2. expect(flipped()).toBe() | |
// 3. expect(flipped(4)).toBe(4) | |
// 4. expect(flipped(4, undefined, 6)).toBe(6, undefined, 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use case:
Basically, All the places where same action to be executed on the reversed args too.
Example: