JSFiddle - React, Tailwind, and code Playground
by darcyclarke
JavaScript
// -------------------------------------------
// Examples:
// "din" => "((("
// "recede" => "()()()"
// "Success" => ")())())"
// "(( @" => "))((“
// -------------------------------------------
var examples = [ 'din', 'recede', 'Success', '(( @' ];
// toLowerCase, split, map, indexOf, lastIndexOf, join
function convert ( str ) {
str = str.toLowerCase();
return str.split( '' ).map( function( val, i ) {
return str.indexOf( val ) !== i || str.lastIndexOf( val ) !== i ? ')' : '(';
}).join( '' );
};
// toLowerCase, split, map, reduce
function convertTwo ( str ) {
var cache = {};
str = str.toLowerCase();
return str.split( '' ).map( function ( val ) {
cache[ val ] = ( cache[ val ] || 0 ) + 1;
return val;
}).reduce( function ( ret, val ) {
return ret + ( ( cache[ val ] > 1 ) ? ')' : '(' );
}, '');
};
// toLowerCase, split, reduce, some
function convertThree ( str ) {
str = str.toLowerCase().split('');
return str.reduce( function ( ret, a, ai ) {
return ret + str.some( function ( b, bi ) { return a === b && ai !== bi; }) ? ')' : '(';
}, '');
};
// Test all examples
examples.forEach( function ( str ) {
console.log( convertTwo( str ) );
});