Skip to content

TransitArrayMap behind-the-scenes conversion can disrupt forEach loops #50

@nasonfish

Description

@nasonfish

Hi folks,

I'm running into a problem with a loop where the amount of accesses on an ArrayMap exceeds the threshold specified in the types file, and thus a loop terminates prematurely.

Consider the following example:

const transit = require("transit-js");

const my_map = transit.map();
// initialize a map with 10 key-value pairs
my_map.set(1,2);
my_map.set(3,4);
my_map.set(5,6);
my_map.set(7,8);
my_map.set(9,10);
my_map.set(11,12);
my_map.set(13,14);
my_map.set(15,16);
my_map.set(17,18);
my_map.set(19,20);

function loop(v,k){
    for(let i = 0; i < 100; i++){
        my_map.get(1);
    }
    console.log("k, v", k, v);
}
my_map.forEach(loop);
// prints: k, v 1 2

Without the extraneous accesses of the map, this loop should print out all 10 of the key-value pairs which exist in the map. However, it is my understanding that some under-the-hood conversion is going on, which interrupts the forEach loop prematurely before it is able to complete, and thus this code only completes one forEach iteration before completing and terminating.

I see that transit/types.js, line 635, defines a conversion that my map matches the criteria for-- the _entries list is converted to a backingMap (since I have defined a small map with many accesses), and the _entries field is cleared in the process. I am assuming this is the condition which is causing a problem for my usage of the map.

I was wondering if you all had any recommendation on how to handle this-- if I should not be using a forEach that also uses the outer map, or if I should be making a copy of the map if I plan to use it in a forEach loop, or if this is a bug which needs to be handled on Transit's end.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions