Array.prototype.find - Proposal for (breaking) change of API

Jordan Harband ljharb at gmail.com
Tue Apr 7 18:47:23 UTC 2015


Then how could you find `undefined` in an array? That's a real use case too.

In your A example, I'd represent that as:
```
var paths = files.map(file => path.resolve(base, file));
var found = paths.find(filePath => fs.existsSync(filePath));
```

… and then `found` would be the resolved path you're looking for.

On Tue, Apr 7, 2015 at 11:41 AM, Martin Heidegger <
martin.heidegger at gmail.com> wrote:

> I am probably very late to the game but I just read about harmonies
> “Array.prototype.find” and found that it might be worth considering a
> change in way it works. Its not a drastic change but it would break the
> compatibility to the current setup. I understand that the chances for this
> going through will be slim but since I would like to give it a shot anyways:
>
> Currently the API uses a callback function that has to return a boolean to
> identify the item that has been found. This is good because find &
> findIndex can use the same methods but it also has a drawback.
>
> Problem: Say you have a list of items that need to be processed before you
> know if you “found” the item. Then you will need to process the last item
> again since there is no way to “keep” the result (A) of the find method or
> you preprocess all items using map (B) that will require to process all the
> items even if the first one already matches.
>
> Example:
>
> (BASE)
> var files = [“main.md”, “backup.md”]
> var base = “/my/root"
>
> (A)
> // Specifies `path.resolve` on two places
> var found = files.find(function (file) {
>    return fs.existsSync(path.resolve(base, file))
> }))
> if (found)
>   found = path.resolve(base, file)
>
> (B)
> // Runs `path.resolve` for all items
> var found = files.map(function (file) {
>   return path.resolve(base, file)
> }).find(fs.existsSync)
>
> Proposal (C): I think it might be interesting to have a change of the
> signature so that the return value is not true/false but the value that
> actually will be returned (not undefined):
>
> (C)
> var found = files.find(function (file) {
>    file = path.resolve(base, file)
>    if(fs.existsSync(file))
>      return file
> });
>
> This way the operations would be minimised, it is still few to write and
> it would make life a bit easier.
>
> yours
> Martin Heidegger
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150407/afedf4b3/attachment.html>


More information about the es-discuss mailing list