Search code examples
javascriptstringimmutable.jsstartswith

StartsWith() not working with takeWhile()


I'm trying to iterate over an Immutable List and have it return a new List with any entries that start with a specific string. For the example here, I am just trying to find all of the states that begin with the letter 'D' I would expect the code below to return a List with a size of 1 and 'Delaware' as an entry, but it comes back with an empty list.

const states = Immutable.fromJS([
    "Alabama",
    "Alaska",
    "Arizona",
    "Arkansas",
    "California",
    "Colorado",
    "Connecticut",
    "Delaware"]);
    
function filter() {
  const testA = 'A';
  const filteredOptions = states.takeWhile((option) =>  option.startsWith(testA));
  console.error(filteredOptions.size); // is 4 as I would expect
  
  const testD = 'D';
  const filteredOptions2 = states.takeWhile((option) =>  option.startsWith(testD));
  console.error(filteredOptions2.size); // is 0 when I expect 1
};

filter();
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


Solution

  • Computer's thinking:

    Does Alamaba start with A? Yes; I'll take it and continue. Does Alaska start with A? Yes; I'll take it and continue. Does Arizona start with A? Yes; I'll take it and continue. Does Arkansas start with A? Yes; I'll take it and continue. Does California start with A? No, so I stop.

    Does Alabama start with D? No, so I stop.

    You want filter, not takeWhile. filter will take all elements that satisfy the proposition; takeWhile only those from the start of the sequence.