ballerina-platform / ballerina-spec

Ballerina Language and Platform Specifications
Other
168 stars 53 forks source link

Add array method `includes` #1315

Open Shadow-Devil opened 1 month ago

Shadow-Devil commented 1 month ago

Description

I'm quite surprised that there currently is no array.contains(item) method. Of course, I could use a query expression or array.indexOf(item) !is () or array.some(a => a == item) but I think it would be convenient to have this simple method. Another idea is to use a similar syntax to Python (e.g. item in array) since in is already a keyword.

Describe your problem(s)

No response

Describe your solution(s)

No response

Related area

-> Standard Library

Related issue(s) (optional)

No response

Suggested label(s) (optional)

No response

Suggested assignee(s) (optional)

No response

MaryamZi commented 1 month ago

Moving this to the spec repo since this is a suggestion for the array langlib.

jclark commented 4 days ago

If we add it, it should be called includes for consistency with lang.string.

jclark commented 4 days ago

ECMAScript has this too: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

jclark commented 4 days ago

I think probably we should add for consistency with lang.string and ECMAScript/JavaScript. It should have an additional argument, defaulting to zero, saying where to start looking from.

jclark commented 4 days ago
# Tests whether an array has a member equal to a value.
#
# + arr - the array in which to search
# + val - member to search for
# + startIndex - index to start the search from
# + return - `true` if there is a member of `arr` equal to `val` at an index >= `startIndex`,
#    or `false` otherwise
public isolated function indexOf(AnydataType[] arr, AnydataType val, int startIndex = 0) returns int? = external;