Last active
November 7, 2022 15:56
-
-
Save anvk/5da2fa0a5d550db4c8622cebb6aeebed to your computer and use it in GitHub Desktop.
Fun TypeScript challenge
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
/* | |
* TypeScript challenge for anyone to flex their TS dev skills | |
* | |
* Write a function wrapper that accepts any arbitrary function with arbitrary arguments. | |
* This wrapper should output a new function that is a modified version of the original one. | |
* This new function should have an extra argument which is last in the list of arguments. This argument is boolean and optional, named "verbose". | |
* This new function works exactly like the original one, with the exception that it should output "verobse is on!" when | |
* "verbose" argument is set to true. | |
*/ | |
// Solution is down below | |
// Answer function | |
function extend<T extends unknown[], R extends any>( | |
fn: (...args: T) => R | |
) { | |
return (...params: [...args: T, verbose?: boolean]) => { | |
const hasVerboseParam = params.length === fn.length + 1; | |
if (hasVerboseParam) { | |
const verbose = params[params.length - 1]; | |
if (verbose) console.log('verbose is on!'); | |
return fn(...(params.slice(0, -1) as T)); | |
} | |
return fn(...(params as unknown as T)); | |
}; | |
} | |
// Test function to wrap | |
const meow = (n: number, s?: string) => { | |
let result = n.toString(); | |
if (s) { | |
result += ' ' + s.toUpperCase(); | |
} | |
return result; | |
} | |
const verboseMeow = extend(meow); | |
const CAT_LIVES = 9; | |
let testSuccessful = true; | |
if (testSuccessful) testSuccessful = verboseMeow(CAT_LIVES, 'lives', true) === `${CAT_LIVES} LIVES`; // 1 verbose output | |
if (testSuccessful) testSuccessful = verboseMeow(CAT_LIVES, 'lives') === `${CAT_LIVES} LIVES`; // no verbose output | |
if (testSuccessful) testSuccessful = verboseMeow(CAT_LIVES) === CAT_LIVES.toString(); // no verbose output | |
console.log(testSuccessful ? 'Everything works' : 'There is an error'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment