JSFiddle - React, Tailwind, and code Playground
by ronilan
HTML
<pre>
// How do you detect for the first repeated character in a string?
</pre>
JavaScript
// How do you detect for the first repeated character in a string?
function firstRepeatedChar (str) {
var result = null;
var found = false;
var max = str.length;
var i,
j;
for (i = 0; i < max; i++) {
for (j = 0; j < i; j++) {
if (str.substr(i, 1) === str.substr(j, 1)) {
found = true;
result = str.substr(i, 1);
break;
}
}
if (found) {
break;
}
}
return result;
}
/** Tests
* A set of test cases for sumTwoLargest.
* Note, you may use factory functions to generate test cases.
**/
var tests = [{
case: 'abc',
expected: null
}, {
case: 'abcdec',
expected: 'c'
}, {
case: 'aAbBcCdDeeFf',
expected: 'e'
}, {
case: (function () {
'use strict';
return [1, 1, 5].join();
}()),
expected: '1'
}];
/**
* Test Runner
* Runs the above tests and prints true/false to console.
**/
(function () {
'use strict';
/**
* assertEqual will return true if both inputs are equal and false if not;
*
* @param {string} a - first
* @param {string} b - second
* @return {boolean} - are eqaul?
**/
function assertEqual (a, b) {
return a === b;
}
var i = tests.length;
while (i) {
i--;
window.console.log(assertEqual(firstRepeatedChar(tests[i].case), tests[i].expected));
}
}());