Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename toArray to arrayFromSet and simplify export syntax #550

Merged
merged 2 commits into from
May 17, 2023

Conversation

benjamn
Copy link
Owner

@benjamn benjamn commented May 17, 2023

As @alessbell has reported in codesandbox/sandpack#940, it appears Sandpack may have a transpiler bug when compiling the following code:

export const {
  from: toArray = (collection: Set<any>) => {
    const array: any[] = [];
    collection.forEach(item => array.push(item));
    return array;
  },
} = Array;

It's understandable the combination of export, destructuring, renaming from: toArray, and a default expression would be unusual enough to have escaped testing, but this works with other transpilers, and is valid TypeScript (and should compile to equivalent valid JS).

What happens, specifically, is that exports.toArray never gets assigned like exports.hasOwnProperty and exports.maybeUnsubscribe, presumably because toArray is not detected as an exported identifier.

Fortunately, there's another way of writing this code that should be less challenging to transpile:

export const arrayFromSet: <T>(set: Set<T>) => T[] =
  Array.from ||
  function (set) {
    const array: any[] = [];
    set.forEach(item => array.push(item));
    return array;
  };

I took this opportunity to rename the helper function from toArray to arrayFromSet, reflecting the fact that we use this function only for converting sets to arrays, which allows us to keep the fallback function simple (for use when Array.from is not available).

@benjamn benjamn self-assigned this May 17, 2023
Copy link
Contributor

@alessbell alessbell left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants