1

I need help in understanding this piece of code. What is it doing and what is the type its returning. Possibly break it in smaller chunks to understand.

Why would it join array elements on '.' and then split them using the same dilimentor'.' What type of array is being passed back from search results?

    function getRandomInt(max, min = 0) {
      return Math.floor(Math.random() * (max - min + 1)) + min; // eslint-disable-line no-mixed-operators
    }

const searchResult = query =>
  new Array(getRandomInt(5))
    .join('.')
    .split('.')
    .map((item, idx) => {
      const category = `${query}${idx}`;
      return {
        value: category,
        label: (
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <span>
              Found {query} on{' '}
              <a
                href={`https://s.taobao.com/search?q=${query}`}
                target="_blank"
                rel="noopener noreferrer"
              >
                {category}
              </a>
            </span>
            <span>{getRandomInt(200, 100)} results</span>
          </div>
        ),
      };
    });

its been called like this

const [options, setOptions] = useState<SelectProps<unknown>["options"]>([]);

  const handleSearch = (value: string) => {
    setOptions(value ? searchResult(value) : []);
  };

I want to be able to put console.log to see what value is setOptions getting. Thanks

----------------- Update 2-----------------
const searchResult = (query: string) => {
  const myArray = new Array(getRandomInt(5)).fill(0).map((item, idx) => {
    const category = `${query}${idx}`;
    return {
      value: category,
      label: labelElement(query, category),
    };
  });
  console.log(myArray);
  return myArray;
};


const labelElement = (query: string, category: string) => {
  return (
    <div
      style={{
        display: "flex",
        justifyContent: "space-between",
      }}
    >
      <span>
        Found {query} on <a>{category}</a>
      </span>
      <span>{getRandomInt(200, 100)} results</span>
    </div>
  );
};

const [options, setOptions] = useState<SelectProps<unknown>["options"]>([]);

  const handleSearch = (value: string) => {
    setOptions(value ? searchResult(value) : []);
  };
2
  • 1
    It depends on whether or not the array contains strings with periods. Commented Jul 31, 2020 at 20:07
  • As you can see it is building an array actually and I think join is adding periods..But I am not sure. Commented Jul 31, 2020 at 20:10

1 Answer 1

1

If we translate what searchResult does in plain English, I think it will be something like this:

Generate & return an array of objects which length should be between 0 and 5 (including both values).

Objects in array should have this shape:

{
    value: string,
    label: JSX.Element
}

The trick with .join('.').split('.') seems to be needed to make array iterable with .map. If you try to call new Array(5).map(() => 'I am ignored 😐') you will see that you'll get an empty array, and .map(...) part will be simply ignored.

That happens because new Array(5) returns an array of empty cells which are ignored by .map(...). A more usual way to deal with it would be something like this:

new Array(5).fill().map(() => 'Now it works!');
Sign up to request clarification or add additional context in comments.

17 Comments

Thanks, I am checking this, get back with you as soon as I try your map example. Really need to get this figured out.
Also, why does map function have two parameters (item, idx), specially when we are not even using Item param?
@Sarah yes, exactly, it just returns an array with several objects. Regarding the error, it indicates you that you provided duplicated keys to React, which is no good. I don't know how exactly you tried to take the first param out, but if you just left (idx) =>, it's not correct because idx is now always 0. Arguments can be named whatever, but their values depend on their position. So, if we rename arguments in (pears, bananas) =>, it will not matter. pears will always be 0 & bananas will be in 0-4 range
@Sarah regarding the key-value topic, I don't completely get the idea. It might be related topics but I don't see the connection. In general, it rather has a lot to do with how map function works
@Sarah you refactored it very well 👍 regarding the piece of code: the last part ([]) is just initial vale for options. The rest is to explain to Typescript what option type actually is. Somewhere in your application there should be declared SelectProps generic type.
|

Your Answer

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.