All files / datamodel/src helper.js

83.62% Statements 148/177
69.86% Branches 51/73
78.57% Functions 33/42
85.19% Lines 138/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356                                        129x 129x 535x   129x       144x 584x 144x     1x 273x 273x 1037x 273x     1x   87x 77x         77x     10x 10x 10x       1x 33x 33x 33x   111x 33x 18x   33x 129x 81x 26x 26x   55x   81x     33x     1x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 4x 4x     2x 16x 20x     20x 20x       20x     20x 20x   16x           2x 2x 16x                     2x     1x 33x 33x           33x 33x   33x 25x     33x     1x 30x 30x 30x 8x       30x 30x   30x 26x               30x     1x 114x 114x   114x       114x 114x     114x 114x   114x 449x 114x     1x 24x   24x 41x 24x                 1x   8x 6x     8x                 8x 2x 2x     2x       2x       8x 2x 2x     2x       2x         8x 2x       2x   2x     2x     2x       8x                             1x 1x     1x     1x 1x     1x     1x     1x 1x 1x   1x     1x     1x     1x 1x 1x           1x 1x     1x     1x     1x     1x                                      
import { FieldType, FilteringMode } from './enums';
import Field from './fields/field';
import fieldStore from './field-store';
import Value from './value';
import {
    rowDiffsetIterator,
    groupByIterator,
    projectIterator,
    selectIterator,
    calculatedVariableIterator
} from './operator';
import { DM_DERIVATIVES, LOGICAL_OPERATORS } from './constants';
import createFields from './field-creator';
import defaultConfig from './default-config';
import * as converter from './converter';
 
/**
 * Prepares the selection data.
 */
function prepareSelectionData (fields, i) {
    const resp = {};
    for (let field of fields) {
        resp[field.name] = new Value(field.data[i], field);
    }
    return resp;
}
 
export function prepareJoinData (fields) {
    const resp = {};
    Object.keys(fields).forEach((key) => { resp[key] = new Value(fields[key], key); });
    return resp;
}
 
export const updateFields = ([rowDiffset, colIdentifier], partialFieldspace, fieldStoreName) => {
    let collID = colIdentifier.length ? colIdentifier.split(',') : [];
    let partialFieldMap = partialFieldspace.fieldsObj();
    let newFields = collID.map(coll => new Field(partialFieldMap[coll], rowDiffset));
    return fieldStore.createNamespace(newFields, fieldStoreName);
};
 
export const persistDerivation = (model, operation, config = {}, criteriaFn) => {
    let derivative;
    if (operation !== DM_DERIVATIVES.COMPOSE) {
        derivative = {
            op: operation,
            meta: config,
            criteria: criteriaFn
        };
        model._derivation.push(derivative);
    }
    else {
        derivative = [...criteriaFn];
        model._derivation.length = 0;
        model._derivation.push(...derivative);
    }
};
 
export const selectHelper = (rowDiffset, fields, selectFn, config) => {
    const newRowDiffSet = [];
    let lastInsertedValue = -1;
    let { mode } = config;
    let li;
    let checker = index => selectFn(prepareSelectionData(fields, index), index);
    if (mode === FilteringMode.INVERSE) {
        checker = index => !selectFn(prepareSelectionData(fields, index));
    }
    rowDiffsetIterator(rowDiffset, (i) => {
        if (checker(i)) {
            if (lastInsertedValue !== -1 && i === (lastInsertedValue + 1)) {
                li = newRowDiffSet.length - 1;
                newRowDiffSet[li] = `${newRowDiffSet[li].split('-')[0]}-${i}`;
            } else {
                newRowDiffSet.push(`${i}`);
            }
            lastInsertedValue = i;
        }
    });
    return newRowDiffSet.join(',');
};
 
export const filterPropagationModel = (model, propModels, config = {}) => {
    const operation = config.operation || LOGICAL_OPERATORS.AND;
    const filterByMeasure = config.filterByMeasure || false;
    let fns = [];
    Iif (propModels === null) {
        fns = [() => false];
    } else {
        fns = propModels.map(propModel => ((dataModel) => {
            const dataObj = dataModel.getData();
            const schema = dataObj.schema;
            const fieldsConfig = dataModel.getFieldsConfig();
            const fieldsSpace = dataModel.getFieldspace().fieldsObj();
            const data = dataObj.data;
            const domain = Object.values(fieldsConfig).reduce((acc, v) => {
                acc[v.def.name] = fieldsSpace[v.def.name].domain();
                return acc;
            }, {});
 
            return (fields) => {
                const include = !data.length ? false : data.some(row => schema.every((propField) => {
                    Iif (!(propField.name in fields)) {
                        return true;
                    }
                    const value = fields[propField.name].valueOf();
                    Iif (filterByMeasure && propField.type === FieldType.MEASURE) {
                        return value >= domain[propField.name][0] && value <= domain[propField.name][1];
                    }
 
                    Iif (propField.type !== FieldType.DIMENSION) {
                        return true;
                    }
                    const idx = fieldsConfig[propField.name].index;
                    return row[idx] === fields[propField.name].valueOf();
                }));
                return include;
            };
        })(propModel));
    }
 
    let filteredModel;
    Eif (operation === LOGICAL_OPERATORS.AND) {
        const clonedModel = model.clone(false, false);
        filteredModel = clonedModel.select(fields => fns.every(fn => fn(fields)), {
            saveChild: false,
            mode: FilteringMode.ALL
        });
    } else {
        filteredModel = model.clone(false, false).select(fields => fns.some(fn => fn(fields)), {
            mode: FilteringMode.ALL,
            saveChild: false
        });
    }
 
    return filteredModel;
};
 
export const cloneWithSelect = (sourceDm, selectFn, selectConfig, cloneConfig) => {
    const cloned = sourceDm.clone(cloneConfig.saveChild);
    const rowDiffset = selectHelper(
        cloned._rowDiffset,
        cloned.getPartialFieldspace().fields,
        selectFn,
        selectConfig
    );
    cloned._rowDiffset = rowDiffset;
    cloned.__calculateFieldspace().calculateFieldsConfig();
    // Store reference to child model and selector function
    if (cloneConfig.saveChild) {
        persistDerivation(cloned, DM_DERIVATIVES.SELECT, { config: selectConfig }, selectFn);
    }
 
    return cloned;
};
 
export const cloneWithProject = (sourceDm, projField, config, allFields) => {
    const cloned = sourceDm.clone(config.saveChild);
    let projectionSet = projField;
    if (config.mode === FilteringMode.INVERSE) {
        projectionSet = allFields.filter(fieldName => projField.indexOf(fieldName) === -1);
    }
    // cloned._colIdentifier = sourceDm._colIdentifier.split(',')
    //                         .filter(coll => projectionSet.indexOf(coll) !== -1).join();
    cloned._colIdentifier = projectionSet.join(',');
    cloned.__calculateFieldspace().calculateFieldsConfig();
    // Store reference to child model and projection fields
    if (config.saveChild) {
        persistDerivation(
            cloned,
            DM_DERIVATIVES.PROJECT,
            { projField, config, actualProjField: projectionSet },
            null
        );
    }
 
    return cloned;
};
 
export const updateData = (relation, data, schema, options) => {
    options = Object.assign(Object.assign({}, defaultConfig), options);
    const converterFn = converter[options.dataFormat];
 
    Iif (!(converterFn && typeof converterFn === 'function')) {
        throw new Error(`No converter function found for ${options.dataFormat} format`);
    }
 
    const [header, formattedData] = converterFn(data, options);
    const fieldArr = createFields(formattedData, schema, header);
 
    // This will create a new fieldStore with the fields
    const nameSpace = fieldStore.createNamespace(fieldArr, options.name);
    relation._partialFieldspace = nameSpace;
    // If data is provided create the default colIdentifier and rowDiffset
    relation._rowDiffset = formattedData.length && formattedData[0].length ? `0-${formattedData[0].length - 1}` : '';
    relation._colIdentifier = (schema.map(_ => _.name)).join();
    return relation;
};
 
export const fieldInSchema = (schema, field) => {
    let i = 0;
 
    for (; i < schema.length; ++i) {
        if (field === schema[i].name) {
            return {
                type: schema[i].subtype || schema[i].type,
                index: i
            };
        }
    }
    return null;
};
 
export const propagateIdentifiers = (dataModel, propModel, config = {}, nonTraversingModel, grouped) => {
    // function to propagate to target the DataModel instance.
    const forwardPropagation = (targetDM, propagationData, hasGrouped) => {
        propagateIdentifiers(targetDM, propagationData, config, nonTraversingModel, hasGrouped);
    };
 
    dataModel !== nonTraversingModel && dataModel.handlePropagation({
        payload: config.payload,
        data: propModel,
        sourceIdentifiers: config.sourceIdentifiers,
        sourceId: config.propagationSourceId,
        groupedPropModel: !!grouped
    });
 
    // propagate to children created by SELECT operation
    selectIterator(dataModel, (targetDM, criteria) => {
        Eif (targetDM !== nonTraversingModel) {
            const selectionModel = propModel[0].select(criteria, {
                saveChild: false
            });
            const rejectionModel = propModel[1].select(criteria, {
                saveChild: false
            });
 
            forwardPropagation(targetDM, [selectionModel, rejectionModel], grouped);
        }
    });
    // propagate to children created by PROJECT operation
    projectIterator(dataModel, (targetDM, projField) => {
        Eif (targetDM !== nonTraversingModel) {
            const projModel = propModel[0].project(projField, {
                saveChild: false
            });
            const rejectionProjModel = propModel[1].project(projField, {
                saveChild: false
            });
 
            forwardPropagation(targetDM, [projModel, rejectionProjModel], grouped);
        }
    });
 
    // propagate to children created by groupBy operation
    groupByIterator(dataModel, (targetDM, conf) => {
        Eif (targetDM !== nonTraversingModel) {
            const {
                    reducer,
                    groupByString
                } = conf;
                // group the filtered model based on groupBy string of target
            const selectionGroupedModel = propModel[0].groupBy(groupByString.split(','), reducer, {
                saveChild: false
            });
            const rejectionGroupedModel = propModel[1].groupBy(groupByString.split(','), reducer, {
                saveChild: false
            });
            forwardPropagation(targetDM, [selectionGroupedModel, rejectionGroupedModel], true);
        }
    });
 
    calculatedVariableIterator(dataModel, (targetDM, ...params) => {
        if (targetDM !== nonTraversingModel) {
            const entryModel = propModel[0].clone(false, false).calculateVariable(...params, {
                saveChild: false,
                replaceVar: true
            });
            const exitModel = propModel[1].clone(false, false).calculateVariable(...params, {
                saveChild: false,
                replaceVar: true
            });
            forwardPropagation(targetDM, [entryModel, exitModel], grouped);
        }
    });
};
 
export const getRootGroupByModel = (model) => {
    Iif (model._parent && model._derivation.find(d => d.op !== 'group')) {
        return getRootGroupByModel(model._parent);
    }
    return model;
};
 
export const getRootDataModel = (model) => {
    Iif (model._parent) {
        return getRootDataModel(model._parent);
    }
    return model;
};
 
export const propagateToAllDataModels = (identifiers, rootModels, config) => {
    let criteria;
    let propModel;
    const propagationNameSpace = config.propagationNameSpace;
    const payload = config.payload;
    const propagationSourceId = config.propagationSourceId;
 
    Iif (identifiers === null) {
        criteria = null;
    } else {
        const filteredCriteria = Object.entries(propagationNameSpace.mutableActions)
            .filter(d => d[0] !== propagationSourceId)
            .map(d => Object.values(d[1]).map(action => action.criteria));
        criteria = [].concat(...[...filteredCriteria, identifiers]);
    }
 
    const rootGroupByModel = rootModels.groupByModel;
    const rootModel = rootModels.model;
    const propConfig = {
        payload,
        propagationSourceId,
        sourceIdentifiers: identifiers
    };
 
    Eif (rootGroupByModel) {
        propModel = filterPropagationModel(rootGroupByModel, criteria, {
            filterByMeasure: true
        });
        propagateIdentifiers(rootGroupByModel, propModel, propConfig);
    }
 
    propModel = filterPropagationModel(rootModel, criteria, {
        filterByMeasure: !rootGroupByModel
    });
    propagateIdentifiers(rootModel, propModel, propConfig, rootGroupByModel);
};
 
export const propagateImmutableActions = (propagationNameSpace, rootModels, propagationSourceId) => {
    const rootGroupByModel = rootModels.groupByModel;
    const rootModel = rootModels.model;
    const immutableActions = propagationNameSpace.immutableActions;
    for (const sourceId in immutableActions) {
        const actions = immutableActions[sourceId];
        for (const action in actions) {
            const criteriaModel = actions[action].criteria;
            propagateToAllDataModels(criteriaModel, {
                groupByModel: rootGroupByModel,
                model: rootModel
            }, {
                propagationNameSpace,
                payload: actions[action].payload,
                propagationSourceId
            });
        }
    }
};