mhahaha / js-snippets

Daily JS Snippets
0 stars 0 forks source link

关于 Goo....oogle 的函数实现 @method go()()()('gle') #2

Open mhahaha opened 5 years ago

mhahaha commented 5 years ago

实现一个 go 函数: 执行go函数,遇到参数‘gle’则结束并返回字符串,反之则追加'O'

image

/**
 * @method go
 * @param {*} str 传入的形参
 * 
 * @returns {Function|String}
 */
function go (str) {

    // 初始字符串
    let BASE_STRING = 'go';

    // 结束后缀
    let SUFFIX = 'gle';

    // 连接字符‘O’
    let STRING_O = 'o';

    function updateString (str) {
        let isEnd = str === SUFFIX;
        BASE_STRING += (isEnd ? SUFFIX : STRING_O);

        return isEnd ? BASE_STRING : updateString;
    }

    return updateString;
}

console.log(go()('gle'))
console.log(go()()('gle'))
console.log(go()()()('gle'))
console.log(go()()()()('gle'))

image