Given an array that gets populated with strings. I need following behavior:
foo = []
foo = add_search_string(foo, 'a')
foo should equal [‘a’]
foo = add_search_string(foo, 'a')
foo should equal [‘a’] because ‘a’ was already a search string
foo = add_search_string(foo, 'ab')
foo should equal [‘ab’] because ‘a’ is a substring of ‘ab’ and therefore can be removed
foo = add_search_string(foo, 'a')
foo should equal [‘ab’] because of the same reason as above
foo = add_search_string(foo, 'c')
foo should equal [‘ab’, ‘c’]
My function looks like this:
function add_search_string(search_strings, new_search_string) {
var keep = true;
var new_search_strings = []
$.each(search_strings, function(i, search_string) {
if (new_search_string == search_string) {
keep = false;
} else if (search_string.indexOf(new_search_string) >= 0) {
keep = false;
}
});
if (keep) {
$.each(search_strings, function(i, search_string) {
if (new_search_string.indexOf(search_string) == -1) {
new_search_strings.push(search_string);
}
});
new_search_strings.push(new_search_string);
search_strings = new_search_strings;
}
return search_strings;
}
Is there a ‘better’ way to do this?
If the intention is to keep updating the same array I’d probably do something like this:
Although this function returns the array, it also updates the array you pass in so you don’t have to assign it back when you call the function, you can just say: