export function buildIndex()

in tools/CCPLogParser/src/utils/findExtras.js [248:303]


export function buildIndex() {
    // this function is quit ugly but I cannot find a prettier way to do it right now.
    // I am assuming that this function will be ran right after
    // the load of the file is complete and the `index` is not empty.
    // index shall have at least 2 items:
    // contacts: holds information about the information for a call;
    // latency: holds information about the latency,
    const outputIndex = new Map();
    // loop through the Index to sort the entries.
    index.latency.forEach((items, key) => {
        // sort the array here.
        // let timestamps = items.sort(); // < magically this actrually works.........
        // yeah according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
        items.sort((a, b) => a._key - b._key); // sort happens in-place.
        items.forEach((item, idx) => {
            switch (item.type) {
            case 'SEND':
                // find it's next reply
                if (items[idx + 1] !== undefined && items[idx + 1].type === 'REPLY') {
                    outputIndex.set(item._key, {
                        type: item.type,
                        apiName: key,
                        relatedWith: items[idx + 1]._key,
                        lastReplyInterval:
                            items[idx - 1] ? items[idx]._ts - items[idx - 1]._ts : null,
                    });
                    // push the next entry as well.
                    outputIndex.set(items[idx + 1]._key, {
                        type: items[idx + 1].type,
                        apiName: key,
                        relatedWith: item._key,
                        latency: items[idx + 1]._ts - items[idx]._ts,
                        status: items[idx + 1].status,
                    });
                } else {
                    // this SEND cannot find it's related REPLY
                    outputIndex.set(item._key, { type: item.type, apiName: key, relateWith: null });
                }
                break;
            case 'REPLY':
                // normally a REPLY should exist already in the index.
                // now picking up orphans
                if (!outputIndex.has(item._key)) {
                    outputIndex.set(items._key, {
                        type: item.type, apiName: key, relateWith: null, status: item.status,
                    });
                }
                break;
            default:
                // we shouldn't reach here.
                break;
            }
        });
    });
    return outputIndex;
}