3
\$\begingroup\$

I'm making a Chrome extension that lets you choose a size of an item and check out quickly.

I have a value called "Large" in sizePref array in my chrome.storage. And when it calls that value, it will choose an option in a dropdown based on that. However, possible labels are "Large", "L", "M/L" or "L/XL" ("Large" being the most often) with the value changing each time.

What is the most efficient way for me to ensure that it makes the correct selection (assuming the speed of doing so is the highest priority)?

This is my current code which just chooses "L" if "Large" doesn't exist. This code works without errors, but I want it to be improved.

chrome.storage.sync.get('sizePref', function(items) { // Get size preferences from storage
 var sizePref = items.sizePref.top1; // Set size to a var
 var sizeVal = $("#size option").filter(function() {
 return $(this).html() == sizePref;
 }).val();
 var sizeVal2 = $("#size option").filter(function() {
 return $(this).html() == "L";
 }).val();
 if (sizeVal !== undefined) {
 $("#size").val(sizeVal);
 } else {
 $("#size").val(sizeVal2);
 }
 });

The targeted dropdown code is as follows:

<select id="size" name="size"><option value="25243">Small</option>
<option value="25244">Medium</option>
<option value="25245">Large</option>
<option value="25246">XLarge</option></select>
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 17, 2015 at 7:32
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

If speed is important, then you should avoid unnecessary dom lookups. For example, if sizeVal is not undefined, then you'll never need another dom lookup for sizeVal2. You can rearrange the code accordingly:

 var sizeVal = $("#size option").filter(function() {
 return $(this).html() == sizePref;
 }).val();
 if (sizeVal !== undefined) {
 $("#size").val(sizeVal);
 } else {
 var sizeVal2 = $("#size option").filter(function() {
 return $(this).html() == "L";
 }).val();
 $("#size").val(sizeVal2);
 }

I would go even further an cache the $("#size option"), and also move the repeated logic into a function:

var options = $("#size option");
function findSize(target) {
 options.filter(function() { return $(this).html() == target; });
}
var size = findSize(sizePref).val() || findSize("L").val();
var $("#size").val(size);
answered May 17, 2015 at 9:53
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.