Skip to content

Instantly share code, notes, and snippets.

@vignesh865
Last active December 3, 2020 04:35
Show Gist options
  • Save vignesh865/a2cd9cb5d96571ada31538a5369d227e to your computer and use it in GitHub Desktop.
Save vignesh865/a2cd9cb5d96571ada31538a5369d227e to your computer and use it in GitHub Desktop.
The function the that flips the given argument.
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)
@vignesh865
Copy link
Author

Use case:
Basically, All the places where same action to be executed on the reversed args too.
Example:

  1. Playing Video/Audio bits in the reverse(Playing video in the reverse)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment