Search code examples
typescriptreturn-type

about sending argument into return that have function type


first of all. I'm sorry that my English is kinda bad. I'm learning about function type and I got stuck on "function that return function" I wrote a code for Typescript exercise. In the type part I'm confused so I just open solution. I use his "createCipher" function code. And now I don't know how to called this and what is use case of return function type.

type Cipher = (character: string) => string;

const cipher: Cipher = (char) => {
    if ((char >= "n" && char <= "z") || (char >= "N" && char <= "Z")) {
        return String.fromCharCode(char.charCodeAt(0) - 13);
    } else if ((char >= "a" && char <= "m") || (char >= "A" && char <= "M"))
        return String.fromCharCode(char.charCodeAt(0) + 13);
    else return char;
};

export function createCipher(cipher: Cipher) {
    return (text: string) => {
        let result = "";

        for (const character of text) {
            result += cipher(character);
        }

        return result;
    };
}

I wonder how to pass argument to parameter "text" here

export function createCipher(cipher: Cipher) {
    return (text: string) => {
        let result = "";

        for (const character of text) {
            result += cipher(character);
        }

        return result;
    };
}

//console.log(createCiher(cipher())=>("hello"))   !!  I don't know how to console.log this

simplify version

function hello() {
  return (text:string) => {
    console.log(text); 
    return ;
    }
}

Solution

  • I already got my answer and looks like this question is duplicate.

    if you interesting. here is link Functions that return a function

    and for more info

    Is it good to make function in function using 'return'?

    really well explain

    function hello() {
      return (text:string) => {
        console.log(text); 
        return ;
        }
    }
    
    hello()("papamama");   //output.Log : "papamama" 
    

    and for createCipher function

    export function createCipher(cipher: Cipher) {
        return (text: string) => {
            let result = "";
    
            for (const character of text) {
                result += cipher(character);
            }
    
            return result;
        };
    }
    
    //console.log(createCiher(cipher)("mysteryCodeHere"))