I am working on a code project that checks if all the characters in str1
can be arranged to form another string (str2
). If all the characters in str2
are present in str1
(including any repeated characters in str2
, i.e. if str2
has two 'a' characters, str1
must correspondingly have two as well), then the function returns true
.
I have a working code solution, but I'd like to refactor for optimal performance as there are a quite a number of random tests (of unknown length) that the code must test against and my code isn't completing the tests in the recommended timeframe.
function stringscrambling(str1, str2) {
var arr1 = str1.split('');
var arr2 = str2.split('');
var index;
var l = arr2.length;
while (l--) {
index = arr1.indexOf(arr2[l]);
if (index > -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
I originally used a basic for loop (with the array length cached as a variable and not in the for
statement) as follows:
for (var i = 0, l = arr2.length; i < l ; i++) {
index = arr1.indexOf(arr2[i]);
if (index > -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
but tried the while
-loop in reverse as I read that specific looping would offer a bit better in terms of benchmarked performance. The change in loop offered a negligible performance upgrade.
Are there any other specific tricks I can implement on my code that can speed it up and still retain the original functionality?