Camel Case 4

  • + 0 comments

    Typescript solution: Please do start from main() and move your way into the inner helper functions to see how the problem was broken down

    Hope this helps!

    function readLine(): string {
        return inputLines[currentLine++];
    }
    
    function prepareTokens(input: string): string[] {
        return input
        .trim()
        .replace(/[{()}]/g, '')
        .split(/(?=[A-Z])|\s+/)
    }
    
    function prepareClassTokens(input: string[]): string[] {
        return input.map(str => str.charAt(0).toUpperCase() + str.slice(1))
    }
    
    function prepareCamelCaseTokens(input: string[]): string[] {
        return input.map((str, n) => {
            if(n === 0) {
                return str.toLowerCase()
            }
            return str.charAt(0).toUpperCase() + str.slice(1)
        })
    }
    
    function processSplit(input: string[]) {
        const toPrint = input.map(token => token.toLowerCase())
        console.log(toPrint.join(' '))
    }
    
    function processCombine(input: string[], type: string) {
            let toPrint: string[]
            if(type === 'C') {
                toPrint = prepareClassTokens(input)
            }
            
            if(type === 'M' || type === 'V') {
                toPrint = prepareCamelCaseTokens(input)   
            }
            
            if(type !== 'M') {
                console.log(toPrint.join(''))
            }
            
            if(type === 'M') {
                console.log(`${toPrint.join('')}()`)
            }
    }
    
    function main() {
        while(currentLine <= inputLines.length-1) {
            const currentString = readLine()
            const [ operation, type, input ] = currentString.split(';')
            
            // Prepare tokens by: 
            // 1) sanitizing the input and
            // 2) normalizing them all into lowercase 
            let tokens: string[]
            tokens = prepareTokens(input)
            
            // Handle split
            if(operation === 'S') {
                processSplit(tokens)
            }
            
            // Handle combine: methods, classes, and variables combine differently
            if(operation === 'C') {
                processCombine(tokens, type)
            }
        }
    }