baji kommadhi
baji kommadhi

Reputation: 11

How to translate the function

Write a function translate() that will translate a text into "rövarspråket". That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon"

Upvotes: 0

Views: 399

Answers (3)

Aprillion
Aprillion

Reputation: 22324

Simple regex replacement - but you need to decide for yourself whether you want to treat Y as a vowel or as a consonant:

function translate(text, cons, char) {
    // translate text into "rövarspråket"
    // text - string
    // cons (optional) - regex with character list to be replaced, must have 1 group
    // char (optional) - character to insert between duplicated cons
    cons = cons || /([bcdfghjklmnpqrstvwxz])/ig;  // excluding y by default
    char = char || 'o';
    return text.replace(cons, '$1' + char + '$1');
}

console.log(translate("this is fun"));

JSFiddle

Upvotes: 1

ElPedro
ElPedro

Reputation: 586

I'll go for attempting the minimum amount of code while also taking uppercase letters at the beginning of words into account...

function translate(fullString) {    
    cons=new Array("b","B","c","C","d","D","f","F","g","G","h","H","j","J","k","K","l","L","m","M","n","N","p","P","q","Q","r","R","s","S","t","T","v","V","w","W","x","X","y","Y","z","Z");
    for(x in cons) {
        fullString=fullString.replace(new RegExp(cons[x], 'g'), cons[x] + "o" + cons[x].toLowerCase());
    }
    return fullString;
}

I'm sure someone with a better knowledge of regex than me could also reduce the size of the array :-)

Upvotes: 0

Nk SP
Nk SP

Reputation: 862

function checkConsonants(letterToCheck) {
    var consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];
    var isConsonant = false;

    for (i = 0; i < consonants.length; i++) {
        if (letterToCheck == consonants[i]) {
            isConsonant = true;
        }
    }
    return isConsonant;
}

function translate(funString, letterO) {

    console.log('The original string is: "' + funString + '"');
    console.log('The separator is: "' + letterO + '"');

    var newString = '';

    for (var i = 0; i < funString.length; i++) {
        if (checkConsonants(funString[i])) {
            newString += funString[i] + letterO + funString[i];
        } else {
            newString += funString[i];
        }
    }
    console.log('The "rövarspråket" result is: ' + '"' + newString + '"');
}

translate('this is fun', 'o');

Take a look of this.

JS Fiddle Example

Upvotes: 0

Related Questions