-
Notifications
You must be signed in to change notification settings - Fork 2k
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
Update flatten helper without recursion #5454
Conversation
3d7349d
to
45c9449
Compare
45c9449
to
fbb3518
Compare
src/helpers.coffee
Outdated
if '[object Array]' is Object::toString.call element | ||
stack.push(element) | ||
else | ||
flattened.push(element) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done
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 eachconcat
.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.