Bloomberg | Phone | Chain JS Function

1294
Jan 17, 2021
Jan 17, 2021

I came across one question in Bloomberg where we are expected to write a JS function 'func' which is suppose to behave as given below

func("world") --> returns --> hiworld
func()("world") --> returns --> hiiworld
func()()("world") --> returns --> hiiiworld
func()()()("world") --> returns --> hiiiiworld
func()()()()("world") --> returns --> hiiiiiworld
func()()()()()("world") --> returns --> hiiiiiiworld

So, it has to be callable and we need to add 'i' between hi and world depending upon the number of times it is called. I was able to write the code as given below:-

function parent () {
    let mid = '' 
    function func(param) {
        if(param) {
            let str = 'hi' + mid + param
            mid = ''
            return str
        }
        
        mid += 'i'
        
        return func
    }
    
    return func
}


let func = parent()

But I was unable to meet the test case:-

func() --> returns func
func()("world") --> returns --> hiiworld

We are not suppose to define func variable again. Basically we need a way to track number of times func is called when invoked in chaining mechanism. New call should count from start. Can anybody pitch in and throw some ideas regarding how can we achieve this behavior?

Comments (9)