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

Update flatten helper without recursion #5454

Merged
merged 4 commits into from
Sep 19, 2023

Conversation

Connormiha
Copy link
Contributor

I've rewritten the flatten algorithm. Instead of a recursive approach, i'm using a stack. This way, we avoid unnecessary function calls and the creation of intermediate arrays. flattened in each call and new array after each concat.
In cases of deep recursion or with a large number of arrays, this algorithm is more efficient and generates less work for the garbage collector.

if '[object Array]' is Object::toString.call element
stack.push(element)
else
flattened.push(element)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Perhaps instead we should use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat? I don’t think we even need to feature-detect it, support goes very far back.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, we can use this if old browser/Node.js support is not required.

exports.flatten = flatten = (array) ->
  array.flat(10)

10 - is max depth

Copy link
Collaborator

Choose a reason for hiding this comment

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

Yes, we can use this if old browser/Node.js support is not required.

You can look in our GitHub Actions to see our support matrix, but basically everywhere we support can run .flat. You can use .flat(Infinity) to go as far down as necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I changed it and built.

npx cake build
npx cake build:browser

Copy link
Collaborator

Choose a reason for hiding this comment

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

CI is failing. Try cake release?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

@GeoffreyBooth GeoffreyBooth merged commit 817c39a into jashkenas:main Sep 19, 2023
15 checks passed
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