List.ts 72.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

S
sushuang 已提交
20 21
/* global Float64Array, Int32Array, Uint32Array, Uint16Array */

L
lang 已提交
22 23 24
/**
 * List for data storage
 */
L
lang 已提交
25

S
sushuang 已提交
26
import {__DEV__} from '../config';
S
sushuang 已提交
27
import * as zrUtil from 'zrender/src/core/util';
S
sushuang 已提交
28 29
import Model from '../model/Model';
import DataDiffer from './DataDiffer';
30 31
import Source, { SourceConstructor } from './Source';
import {DefaultDataProvider, DataProvider} from './helper/dataProvider';
32
import {summarizeDimensions, DimensionSummary} from './helper/dimensionHelper';
S
fix:  
SHUANG SU 已提交
33
import DataDimensionInfo from './DataDimensionInfo';
34 35 36 37
import {ArrayLike, Dictionary, FunctionPropertyNames} from 'zrender/src/core/types';
import Element from 'zrender/src/Element';
import {
    DimensionIndex, DimensionName, ECElement, DimensionLoose, OptionDataItem,
38
    ParsedValue, ParsedValueNumeric, OrdinalNumber, DimensionUserOuput, ModelOption
39 40 41 42
} from '../util/types';
import {parseDate} from '../util/number';
import {isDataItemOption} from '../util/model';

S
sushuang 已提交
43 44 45

var isObject = zrUtil.isObject;

S
sushuang 已提交
46
var UNDEFINED = 'undefined';
47
var INDEX_NOT_FOUND = -1;
S
sushuang 已提交
48

49 50 51 52
// Use prefix to avoid index to be the same as otherIdList[idx],
// which will cause weird udpate animation.
var ID_PREFIX = 'e\0\0';

S
sushuang 已提交
53
var dataCtors = {
S
sushuang 已提交
54 55 56 57
    'float': typeof Float64Array === UNDEFINED
        ? Array : Float64Array,
    'int': typeof Int32Array === UNDEFINED
        ? Array : Int32Array,
S
sushuang 已提交
58 59 60 61 62 63
    // Ordinal data type can be string or int
    'ordinal': Array,
    'number': Array,
    'time': Array
};

64 65
export type ListDimensionType = keyof typeof dataCtors;

S
sushuang 已提交
66 67 68
// Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
// different from the Ctor of typed array.
var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
69
var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
S
sushuang 已提交
70
var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
P
pissang 已提交
71

72 73 74 75 76 77 78 79 80 81 82 83
type DataTypedArray = Uint32Array | Int32Array | Uint16Array | Float64Array;
type DataTypedArrayConstructor = typeof Uint32Array | typeof Int32Array | typeof Uint16Array | typeof Float64Array;
type DataArrayLikeConstructor = typeof Array | DataTypedArrayConstructor;



type DimValueGetter = (
    this: List,
    dataItem: any,
    dimName: DimensionName,
    dataIndex: number,
    dimIndex: DimensionIndex
84
) => ParsedValue;
85

86
type DataValueChunk = ArrayLike<ParsedValue>;
87 88 89 90 91 92 93 94
type DataStorage = {[dimName: string]: DataValueChunk[]};
type NameRepeatCount = {[name: string]: number};


type ItrParamDims = DimensionLoose | Array<DimensionLoose>;
// If Ctx not specified, use List as Ctx
type CtxOrList<Ctx> = unknown extends Ctx ? List : Ctx;
type EachCb0<Ctx> = (this: CtxOrList<Ctx>, idx: number) => void;
95 96
type EachCb1<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, idx: number) => void;
type EachCb2<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, y: ParsedValue, idx: number) => void;
97 98
type EachCb<Ctx> = (this: CtxOrList<Ctx>, ...args: any) => void;
type FilterCb0<Ctx> = (this: CtxOrList<Ctx>, idx: number) => boolean;
99 100
type FilterCb1<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, idx: number) => boolean;
type FilterCb2<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, y: ParsedValue, idx: number) => boolean;
101 102
type FilterCb<Ctx> = (this: CtxOrList<Ctx>, ...args: any) => boolean;
type MapArrayCb0<Ctx> = (this: CtxOrList<Ctx>, idx: number) => any;
103 104
type MapArrayCb1<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, idx: number) => any;
type MapArrayCb2<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, y: ParsedValue, idx: number) => any;
105
type MapArrayCb<Ctx> = (this: CtxOrList<Ctx>, ...args: any) => any;
106 107 108 109
type MapCb1<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, idx: number) => ParsedValue | ParsedValue[];
type MapCb2<Ctx> = (this: CtxOrList<Ctx>, x: ParsedValue, y: ParsedValue, idx: number) =>
    ParsedValue | ParsedValue[];
type MapCb<Ctx> = (this: CtxOrList<Ctx>, ...args: any) => ParsedValue | ParsedValue[];
110

S
sushuang 已提交
111

S
sushuang 已提交
112

S
sushuang 已提交
113
var TRANSFERABLE_PROPERTIES = [
114 115 116 117 118 119
    'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
    '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
    '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
];
var CLONE_PROPERTIES = [
    '_extent', '_approximateExtent', '_rawExtent'
S
sushuang 已提交
120 121
];

L
lang 已提交
122

123

P
pissang 已提交
124
class List <HostModel extends Model = Model> {
L
lang 已提交
125

126
    readonly type = 'list';
L
lang 已提交
127

128
    readonly dimensions: string[];
129

130 131
    // Infomation of each data dimension, like data type.
    private _dimensionInfos: {[dimName: string]: DataDimensionInfo};
132

P
pissang 已提交
133
    readonly hostModel: HostModel;
134

135
    readonly dataType: string;
136

137 138 139
    // Indices stores the indices of data subset after filtered.
    // This data subset will be used in chart.
    private _indices: ArrayLike<any>;
S
sushuang 已提交
140

141 142 143 144 145
    private _count: number = 0;
    private _rawCount: number = 0;
    private _storage: DataStorage = {};
    private _nameList: string[] = [];
    private _idList: string[] = [];
S
sushuang 已提交
146

147 148 149
    // Models of data option is stored sparse for optimizing memory cost
    // Never used yet (not used yet).
    // private _optionModels: Model[] = [];
S
sushuang 已提交
150

151 152
    // Global visual properties after visual coding
    private _visual: Dictionary<any> = {};
S
sushuang 已提交
153

154 155
    // Globel layout properties.
    private _layout: Dictionary<any> = {};
S
sushuang 已提交
156

157 158
    // Item visual properties after visual coding
    private _itemVisuals: Dictionary<any>[] = [];
S
sushuang 已提交
159

160 161 162
    // Key: visual type, Value: boolean
    // @readonly
    hasItemVisual: Dictionary<boolean> = {};
163

164 165
    // Item layout properties after layout
    private _itemLayouts: any[] = [];
S
sushuang 已提交
166

167 168
    // Graphic elemnents
    private _graphicEls: Element[] = [];
O
Ovilia 已提交
169

170 171
    // Max size of each chunk.
    private _chunkSize: number = 1e5;
O
Ovilia 已提交
172

173
    private _chunkCount: number = 0;
L
lang 已提交
174

175
    private _rawData: DataProvider;
P
pah100 已提交
176

177 178 179
    // Raw extent will not be cloned, but only transfered.
    // It will not be calculated util needed.
    private _rawExtent: {[dimName: string]: [number, number]} = {};
L
lang 已提交
180

181
    private _extent: {[dimName: string]: [number, number]} = {};
L
lang 已提交
182

183 184
    // key: dim, value: extent
    private _approximateExtent: {[dimName: string]: [number, number]} = {};
S
sushuang 已提交
185

186
    private _dimensionsSummary: DimensionSummary;
P
pah100 已提交
187

188
    private _invertedIndicesMap: {[dimName: string]: ArrayLike<number>};
L
lang 已提交
189

190
    private _calculationInfo: {[key: string]: any} = {};
P
pah100 已提交
191

192 193 194 195 196 197 198 199
    // User output info of this data.
    // DO NOT use it in other places!
    // When preparing user params for user callbacks, we have
    // to clone these inner data structures to prevent users
    // from modifying them to effect built-in logic. And for
    // performance consideration we make this `userOutput` to
    // avoid clone them too many times.
    readonly userOutput: DimensionUserOuput;
O
Ovilia 已提交
200

201 202
    // If each data item has it's own option
    hasItemOption: boolean = true;
S
sushuang 已提交
203

204 205 206 207
    // @readonly
    defaultDimValueGetter: DimValueGetter;
    private _dimValueGetter: DimValueGetter;
    private _dimValueGetterArrayRows: DimValueGetter;
L
lang 已提交
208

209 210 211
    private _nameRepeatCount: NameRepeatCount;
    private _nameDimIdx: number;
    private _idDimIdx: number;
S
sushuang 已提交
212

213
    private __wrappedMethods: string[];
S
sushuang 已提交
214

215 216 217 218 219
    // Methods that create a new list based on this list should be listed here.
    // Notice that those method should `RETURN` the new list.
    TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
    // Methods that change indices of this list should be listed here.
    CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
S
sushuang 已提交
220

221 222

    /**
223 224 225
     * @param dimensions
     *        For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
     *        Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
226
     */
P
pissang 已提交
227
    constructor(dimensions: Array<string | object | DataDimensionInfo>, hostModel: HostModel) {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        dimensions = dimensions || ['x', 'y'];

        var dimensionInfos: Dictionary<DataDimensionInfo> = {};
        var dimensionNames = [];
        var invertedIndicesMap: Dictionary<number[]> = {};

        for (var i = 0; i < dimensions.length; i++) {
            // Use the original dimensions[i], where other flag props may exists.
            var dimInfoInput = dimensions[i];

            var dimensionInfo: DataDimensionInfo =
                zrUtil.isString(dimInfoInput)
                ? new DataDimensionInfo({name: dimInfoInput})
                : !(dimInfoInput instanceof DataDimensionInfo)
                ? new DataDimensionInfo(dimInfoInput)
                : dimInfoInput;

            var dimensionName = dimensionInfo.name;
            dimensionInfo.type = dimensionInfo.type || 'float';
            if (!dimensionInfo.coordDim) {
                dimensionInfo.coordDim = dimensionName;
                dimensionInfo.coordDimIndex = 0;
            }
251

252 253 254
            dimensionInfo.otherDims = dimensionInfo.otherDims || {};
            dimensionNames.push(dimensionName);
            dimensionInfos[dimensionName] = dimensionInfo;
L
lang 已提交
255

256
            dimensionInfo.index = i;
S
sushuang 已提交
257

258 259 260 261
            if (dimensionInfo.createInvertedIndices) {
                invertedIndicesMap[dimensionName] = [];
            }
        }
S
sushuang 已提交
262

263 264 265 266 267 268 269 270 271 272 273
        this.dimensions = dimensionNames;
        this._dimensionInfos = dimensionInfos;
        this.hostModel = hostModel;

        // Cache summary info for fast visit. See "dimensionHelper".
        this._dimensionsSummary = summarizeDimensions(this);

        this._invertedIndicesMap = invertedIndicesMap;

        this.userOutput = this._dimensionsSummary.userOutput;
    }
274 275

    /**
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
     * The meanings of the input parameter `dim`:
     *
     * + If dim is a number (e.g., `1`), it means the index of the dimension.
     *   For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
     * + If dim is a number-like string (e.g., `"1"`):
     *     + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
     *     + If not, it will be converted to a number, which means the index of the dimension.
     *        (why? because of the backward compatbility. We have been tolerating number-like string in
     *        dimension setting, although now it seems that it is not a good idea.)
     *     For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
     *     if no dimension name is defined as `"1"`.
     * + If dim is a not-number-like string, it means the concrete dim name.
     *   For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
     *   or customized in `dimensions` property of option like `"age"`.
     *
     * Get dimension name
     * @param dim See above.
     * @return Concrete dim name.
294
     */
295 296 297 298 299 300 301 302 303
    getDimension(dim: DimensionLoose): DimensionName {
        if (typeof dim === 'number'
            // If being a number-like string but not being defined a dimension name.
            || (!isNaN(dim as any) && !this._dimensionInfos.hasOwnProperty(dim))
        ) {
            dim = this.dimensions[dim as DimensionIndex];
        }
        return dim as DimensionName;
    }
S
sushuang 已提交
304 305

    /**
306 307 308 309
     * Get type and calculation info of particular dimension
     * @param dim
     *        Dimension can be concrete names like x, y, z, lng, lat, angle, radius
     *        Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
S
sushuang 已提交
310
     */
311 312 313 314
    getDimensionInfo(dim: DimensionLoose): DataDimensionInfo {
        // Do not clone, because there may be categories in dimInfo.
        return this._dimensionInfos[this.getDimension(dim)];
    }
S
sushuang 已提交
315 316

    /**
317
     * concrete dimension name list on coord.
S
sushuang 已提交
318
     */
319 320 321
    getDimensionsOnCoord(): DimensionName[] {
        return this._dimensionsSummary.dataDimsOnCoord.slice();
    }
322 323

    /**
324 325 326 327 328 329 330
     * @param coordDim
     * @param idx A coordDim may map to more than one data dim.
     *        If idx is `true`, return a array of all mapped dims.
     *        If idx is not specified, return the first dim not extra.
     * @return concrete data dim.
     *        If idx is number, and not found, return null/undefined.
     *        If idx is `true`, and not found, return empty array (always return array).
331
     */
332 333 334 335
    mapDimension(coordDim: DimensionName): DimensionName;
    mapDimension(coordDim: DimensionName, idx: true): DimensionName[];
    mapDimension(coordDim: DimensionName, idx: number): DimensionName;
    mapDimension(coordDim: DimensionName, idx?: true | number): DimensionName | DimensionName[] {
336 337 338 339 340
        var dimensionsSummary = this._dimensionsSummary;

        if (idx == null) {
            return dimensionsSummary.encodeFirstDimNotExtra[coordDim] as any;
        }
L
lang 已提交
341

342 343 344 345 346
        var dims = dimensionsSummary.encode[coordDim];
        return idx === true
            // always return array if idx is `true`
            ? (dims || []).slice()
            : (dims ? dims[idx as number] as any : null);
S
sushuang 已提交
347
    }
L
lang 已提交
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
    /**
     * Initialize from data
     * @param data source or data or data provider.
     * @param nameLIst The name of a datum is used on data diff and
     *        defualt label/tooltip.
     *        A name can be specified in encode.itemName,
     *        or dataItem.name (only for series option data),
     *        or provided in nameList from outside.
     */
    initData(
        data: any,
        nameList?: string[],
        dimValueGetter?: DimValueGetter
    ): void {

        var notProvider = (Source as SourceConstructor).isInstance(data)
            || zrUtil.isArrayLike(data);
        if (notProvider) {
            data = new DefaultDataProvider(data, this.dimensions.length);
        }
L
lang 已提交
369

370 371 372 373 374 375 376
        if (__DEV__) {
            if (!notProvider
                && (typeof data.getItem !== 'function' || typeof data.count !== 'function')
            ) {
                throw new Error('Inavlid data provider.');
            }
        }
S
sushuang 已提交
377

378
        this._rawData = data;
S
sushuang 已提交
379

380 381 382
        // Clear
        this._storage = {};
        this._indices = null;
S
sushuang 已提交
383

384
        this._nameList = nameList || [];
385

386
        this._idList = [];
387

388
        this._nameRepeatCount = {};
389

390 391
        if (!dimValueGetter) {
            this.hasItemOption = false;
L
lang 已提交
392
        }
393

394 395 396 397 398 399 400
        this.defaultDimValueGetter = defaultDimValueGetters[
            this._rawData.getSource().sourceFormat
        ];
        // Default dim value getter
        this._dimValueGetter = dimValueGetter = dimValueGetter
            || this.defaultDimValueGetter;
        this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
L
lang 已提交
401

402 403
        // Reset raw extent.
        this._rawExtent = {};
L
lang 已提交
404

405
        this._initDataFromProvider(0, data.count());
L
lang 已提交
406

407 408 409 410 411
        // If data has no item option.
        if (data.pure) {
            this.hasItemOption = false;
        }
    }
L
lang 已提交
412

413 414
    getProvider(): DataProvider {
        return this._rawData;
S
sushuang 已提交
415
    }
416 417

    /**
418
     * Caution: Can be only called on raw data (before `this._indices` created).
419
     */
420 421 422 423
    appendData(data: ArrayLike<any>): void {
        if (__DEV__) {
            zrUtil.assert(!this._indices, 'appendData can only be called on raw data.');
        }
S
sushuang 已提交
424

425 426 427 428 429 430 431 432
        var rawData = this._rawData;
        var start = this.count();
        rawData.appendData(data);
        var end = rawData.count();
        if (!rawData.persistent) {
            end += start;
        }
        this._initDataFromProvider(start, end);
433
    }
434

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    /**
     * Caution: Can be only called on raw data (before `this._indices` created).
     * This method does not modify `rawData` (`dataProvider`), but only
     * add values to storage.
     *
     * The final count will be increased by `Math.max(values.length, names.length)`.
     *
     * @param values That is the SourceType: 'arrayRows', like
     *        [
     *            [12, 33, 44],
     *            [NaN, 43, 1],
     *            ['-', 'asdf', 0]
     *        ]
     *        Each item is exaclty cooresponding to a dimension.
     */
    appendValues(values: any[][], names?: string[]): void {
        var chunkSize = this._chunkSize;
        var storage = this._storage;
        var dimensions = this.dimensions;
        var dimLen = dimensions.length;
        var rawExtent = this._rawExtent;

        var start = this.count();
        var end = start + Math.max(values.length, names ? names.length : 0);
        var originalChunkCount = this._chunkCount;

        for (var i = 0; i < dimLen; i++) {
            var dim = dimensions[i];
            if (!rawExtent[dim]) {
                rawExtent[dim] = getInitialExtent();
            }
            if (!storage[dim]) {
                storage[dim] = [];
            }
            prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
            this._chunkCount = storage[dim].length;
S
sushuang 已提交
471
        }
472

473 474 475 476 477 478 479 480 481 482 483
        var emptyDataItem = new Array(dimLen);
        for (var idx = start; idx < end; idx++) {
            var sourceIdx = idx - start;
            var chunkIndex = Math.floor(idx / chunkSize);
            var chunkOffset = idx % chunkSize;

            // Store the data by dimensions
            for (var k = 0; k < dimLen; k++) {
                var dim = dimensions[k];
                var val = this._dimValueGetterArrayRows(
                    values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
484
                ) as ParsedValueNumeric;
485 486 487 488 489 490
                storage[dim][chunkIndex][chunkOffset] = val;

                var dimRawExtent = rawExtent[dim];
                val < dimRawExtent[0] && (dimRawExtent[0] = val);
                val > dimRawExtent[1] && (dimRawExtent[1] = val);
            }
491

492 493 494
            if (names) {
                this._nameList[idx] = names[sourceIdx];
            }
495 496
        }

497
        this._rawCount = this._count = end;
498

499 500
        // Reset data extent
        this._extent = {};
501

502 503
        prepareInvertedIndex(this);
    }
504

505 506 507 508
    private _initDataFromProvider(start: number, end: number): void {
        if (start >= end) {
            return;
        }
509

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
        var chunkSize = this._chunkSize;
        var rawData = this._rawData;
        var storage = this._storage;
        var dimensions = this.dimensions;
        var dimLen = dimensions.length;
        var dimensionInfoMap = this._dimensionInfos;
        var nameList = this._nameList;
        var idList = this._idList;
        var rawExtent = this._rawExtent;
        var nameRepeatCount: NameRepeatCount = this._nameRepeatCount = {};
        var nameDimIdx;

        var originalChunkCount = this._chunkCount;
        for (var i = 0; i < dimLen; i++) {
            var dim = dimensions[i];
            if (!rawExtent[dim]) {
                rawExtent[dim] = getInitialExtent();
            }
S
sushuang 已提交
528

529 530 531 532 533 534 535
            var dimInfo = dimensionInfoMap[dim];
            if (dimInfo.otherDims.itemName === 0) {
                nameDimIdx = this._nameDimIdx = i;
            }
            if (dimInfo.otherDims.itemId === 0) {
                this._idDimIdx = i;
            }
S
sushuang 已提交
536

537 538 539
            if (!storage[dim]) {
                storage[dim] = [];
            }
S
tweak  
sushuang 已提交
540

541
            prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
542

543
            this._chunkCount = storage[dim].length;
S
sushuang 已提交
544
        }
545

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        var dataItem = new Array(dimLen) as OptionDataItem;
        for (var idx = start; idx < end; idx++) {
            // NOTICE: Try not to write things into dataItem
            dataItem = rawData.getItem(idx, dataItem);
            // Each data item is value
            // [1, 2]
            // 2
            // Bar chart, line chart which uses category axis
            // only gives the 'y' value. 'x' value is the indices of category
            // Use a tempValue to normalize the value to be a (x, y) value
            var chunkIndex = Math.floor(idx / chunkSize);
            var chunkOffset = idx % chunkSize;

            // Store the data by dimensions
            for (var k = 0; k < dimLen; k++) {
                var dim = dimensions[k];
                var dimStorage = storage[dim][chunkIndex];
                // PENDING NULL is empty or zero
564
                var val = this._dimValueGetter(dataItem, dim, idx, k) as ParsedValueNumeric;
565 566 567 568 569 570
                dimStorage[chunkOffset] = val;

                var dimRawExtent = rawExtent[dim];
                val < dimRawExtent[0] && (dimRawExtent[0] = val);
                val > dimRawExtent[1] && (dimRawExtent[1] = val);
            }
S
sushuang 已提交
571

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
            // ??? FIXME not check by pure but sourceFormat?
            // TODO refactor these logic.
            if (!rawData.pure) {
                var name: any = nameList[idx];

                if (dataItem && name == null) {
                    // If dataItem is {name: ...}, it has highest priority.
                    // That is appropriate for many common cases.
                    if ((dataItem as any).name != null) {
                        // There is no other place to persistent dataItem.name,
                        // so save it to nameList.
                        nameList[idx] = name = (dataItem as any).name;
                    }
                    else if (nameDimIdx != null) {
                        var nameDim = dimensions[nameDimIdx];
                        var nameDimChunk = storage[nameDim][chunkIndex];
                        if (nameDimChunk) {
                            name = nameDimChunk[chunkOffset];
                            var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
                            if (ordinalMeta && ordinalMeta.categories.length) {
                                name = ordinalMeta.categories[name];
                            }
594 595 596
                        }
                    }
                }
S
sushuang 已提交
597

598 599 600
                // Try using the id in option
                // id or name is used on dynamical data, mapping old and new items.
                var id = dataItem == null ? null : (dataItem as any).id;
S
sushuang 已提交
601

602 603 604 605 606 607 608 609
                if (id == null && name != null) {
                    // Use name as id and add counter to avoid same name
                    nameRepeatCount[name] = nameRepeatCount[name] || 0;
                    id = name;
                    if (nameRepeatCount[name] > 0) {
                        id += '__ec__' + nameRepeatCount[name];
                    }
                    nameRepeatCount[name]++;
S
sushuang 已提交
610
                }
611
                id != null && (idList[idx] = id);
S
sushuang 已提交
612 613
            }
        }
S
sushuang 已提交
614

615 616 617 618
        if (!rawData.persistent && rawData.clean) {
            // Clean unused data if data source is typed array.
            rawData.clean();
        }
P
pissang 已提交
619

620
        this._rawCount = this._count = end;
S
sushuang 已提交
621

622 623
        // Reset data extent
        this._extent = {};
S
tweak  
sushuang 已提交
624

625
        prepareInvertedIndex(this);
626 627
    }

628 629
    count(): number {
        return this._count;
630 631
    }

632 633
    getIndices(): ArrayLike<number> {
        var newIndices;
S
sushuang 已提交
634

635 636 637 638 639 640 641 642 643 644
        var indices = this._indices;
        if (indices) {
            var Ctor = indices.constructor as DataArrayLikeConstructor;
            var thisCount = this._count;
            // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
            if (Ctor === Array) {
                newIndices = new Ctor(thisCount);
                for (var i = 0; i < thisCount; i++) {
                    newIndices[i] = indices[i];
                }
S
sushuang 已提交
645
            }
646 647 648 649
            else {
                newIndices = new (Ctor as DataTypedArrayConstructor)(
                    (indices as DataTypedArray).buffer, 0, thisCount
                );
S
sushuang 已提交
650 651
            }
        }
652 653 654 655 656
        else {
            var Ctor = getIndicesCtor(this);
            newIndices = new Ctor(this.count());
            for (var i = 0; i < newIndices.length; i++) {
                newIndices[i] = i;
657
            }
658 659
        }

660 661
        return newIndices;
    }
662

663 664 665 666
    /**
     * Get value. Return NaN if idx is out of range.
     * @param dim Dim must be concrete name.
     */
667
    get(dim: DimensionName, idx: number): ParsedValue {
668 669
        if (!(idx >= 0 && idx < this._count)) {
            return NaN;
S
sushuang 已提交
670
        }
671 672 673 674
        var storage = this._storage;
        if (!storage[dim]) {
            // TODO Warn ?
            return NaN;
S
sushuang 已提交
675
        }
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

        idx = this.getRawIndex(idx);

        var chunkIndex = Math.floor(idx / this._chunkSize);
        var chunkOffset = idx % this._chunkSize;

        var chunkStore = storage[dim][chunkIndex];
        var value = chunkStore[chunkOffset];
        // FIXME ordinal data type is not stackable
        // if (stack) {
        //     var dimensionInfo = this._dimensionInfos[dim];
        //     if (dimensionInfo && dimensionInfo.stackable) {
        //         var stackedOn = this.stackedOn;
        //         while (stackedOn) {
        //             // Get no stacked data of stacked on
        //             var stackedValue = stackedOn.get(dim, idx);
        //             // Considering positive stack, negative stack and empty data
        //             if ((value >= 0 && stackedValue > 0)  // Positive stack
        //                 || (value <= 0 && stackedValue < 0) // Negative stack
        //             ) {
        //                 value += stackedValue;
        //             }
        //             stackedOn = stackedOn.stackedOn;
        //         }
        //     }
        // }

        return value;
704
    }
S
sushuang 已提交
705

706 707 708
    /**
     * @param dim concrete dim
     */
709
    getByRawIndex(dim: DimensionName, rawIdx: number): ParsedValue {
710 711 712 713 714 715 716 717
        if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
            return NaN;
        }
        var dimStore = this._storage[dim];
        if (!dimStore) {
            // TODO Warn ?
            return NaN;
        }
S
sushuang 已提交
718

719 720 721 722
        var chunkIndex = Math.floor(rawIdx / this._chunkSize);
        var chunkOffset = rawIdx % this._chunkSize;
        var chunkStore = dimStore[chunkIndex];
        return chunkStore[chunkOffset];
P
pissang 已提交
723
    }
724 725 726 727 728

    /**
     * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
     * Hack a much simpler _getFast
     */
729
    private _getFast(dim: DimensionName, rawIdx: number): ParsedValue {
730 731 732 733
        var chunkIndex = Math.floor(rawIdx / this._chunkSize);
        var chunkOffset = rawIdx % this._chunkSize;
        var chunkStore = this._storage[dim][chunkIndex];
        return chunkStore[chunkOffset];
734
    }
P
pissang 已提交
735

736 737 738 739
    /**
     * Get value for multi dimensions.
     * @param dimensions If ignored, using all dimensions.
     */
740 741 742
    getValues(idx: number): ParsedValue[];
    getValues(dimensions: DimensionName[], idx: number): ParsedValue[];
    getValues(dimensions: DimensionName[] | number, idx?: number): ParsedValue[] {
743 744 745 746 747 748 749
        var values = [];

        if (!zrUtil.isArray(dimensions)) {
            // stack = idx;
            idx = dimensions;
            dimensions = this.dimensions;
        }
P
pissang 已提交
750

751 752 753
        for (var i = 0, len = dimensions.length; i < len; i++) {
            values.push(this.get(dimensions[i], idx /*, stack */));
        }
S
sushuang 已提交
754

755
        return values;
S
sushuang 已提交
756
    }
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772

    /**
     * If value is NaN. Inlcuding '-'
     * Only check the coord dimensions.
     */
    hasValue(idx: number): boolean {
        var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
        for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
            // Ordinal type originally can be string or number.
            // But when an ordinal type is used on coord, it can
            // not be string but only number. So we can also use isNaN.
            if (isNaN(this.get(dataDimsOnCoord[i], idx) as any)) {
                return false;
            }
        }
        return true;
S
sushuang 已提交
773 774
    }

775 776 777 778 779 780 781 782
    /**
     * Get extent of data in one dimension
     */
    getDataExtent(dim: DimensionLoose): [number, number] {
        // Make sure use concrete dim as cache name.
        dim = this.getDimension(dim);
        var dimData = this._storage[dim];
        var initialExtent = getInitialExtent();
S
sushuang 已提交
783

784
        // stack = !!((stack || false) && this.getCalculationInfo(dim));
P
pissang 已提交
785

786 787 788
        if (!dimData) {
            return initialExtent;
        }
S
sushuang 已提交
789

790 791 792 793
        // Make more strict checkings to ensure hitting cache.
        var currEnd = this.count();
        // var cacheName = [dim, !!stack].join('_');
        // var cacheName = dim;
S
sushuang 已提交
794

795 796 797 798 799
        // Consider the most cases when using data zoom, `getDataExtent`
        // happened before filtering. We cache raw extent, which is not
        // necessary to be cleared and recalculated when restore data.
        var useRaw = !this._indices; // && !stack;
        var dimExtent: [number, number];
S
sushuang 已提交
800

801 802 803 804 805 806 807 808
        if (useRaw) {
            return this._rawExtent[dim].slice() as [number, number];
        }
        dimExtent = this._extent[dim];
        if (dimExtent) {
            return dimExtent.slice() as [number, number];
        }
        dimExtent = initialExtent;
S
sushuang 已提交
809

810 811 812 813 814
        var min = dimExtent[0];
        var max = dimExtent[1];

        for (var i = 0; i < currEnd; i++) {
            // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
815
            var value = this._getFast(dim, this.getRawIndex(i)) as ParsedValueNumeric;
816 817
            value < min && (min = value);
            value > max && (max = value);
L
lang 已提交
818
        }
L
lang 已提交
819

820
        dimExtent = [min, max];
S
sushuang 已提交
821

822
        this._extent[dim] = dimExtent;
P
pissang 已提交
823

824
        return dimExtent;
S
sushuang 已提交
825
    }
S
sushuang 已提交
826

827 828 829 830 831 832 833 834 835 836
    /**
     * Optimize for the scenario that data is filtered by a given extent.
     * Consider that if data amount is more than hundreds of thousand,
     * extent calculation will cost more than 10ms and the cache will
     * be erased because of the filtering.
     */
    getApproximateExtent(dim: DimensionLoose): [number, number] {
        dim = this.getDimension(dim);
        return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
    }
S
sushuang 已提交
837

838 839 840
    setApproximateExtent(extent: [number, number], dim: DimensionLoose): void {
        dim = this.getDimension(dim);
        this._approximateExtent[dim] = extent.slice() as [number, number];
S
sushuang 已提交
841
    }
842

843
    getCalculationInfo(key: string): any {
844
        return this._calculationInfo[key];
S
sushuang 已提交
845 846
    }

847 848 849 850 851 852 853 854
    /**
     * @param key or k-v object
     */
    setCalculationInfo(key: string | object, value?: any) {
        isObject(key)
            ? zrUtil.extend(this._calculationInfo, key as object)
            : (this._calculationInfo[key] = value);
    }
S
sushuang 已提交
855

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
    /**
     * Get sum of data in one dimension
     */
    getSum(dim: DimensionName): number {
        var dimData = this._storage[dim];
        var sum = 0;
        if (dimData) {
            for (var i = 0, len = this.count(); i < len; i++) {
                var value = this.get(dim, i) as number;
                if (!isNaN(value)) {
                    sum += value;
                }
            }
        }
        return sum;
S
sushuang 已提交
871
    }
S
sushuang 已提交
872

873 874 875 876
    /**
     * Get median of data in one dimension
     */
    getMedian(dim: DimensionLoose): number {
877
        var dimDataArray: ParsedValue[] = [];
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
        // map all data of one dimension
        this.each(dim, function (val) {
            if (!isNaN(val as number)) {
                dimDataArray.push(val);
            }
        });

        // TODO
        // Use quick select?

        // immutability & sort
        var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
            return a - b;
        });
        var len = this.count();
        // calculate median
        return len === 0
            ? 0
            : len % 2 === 1
            ? sortedDimDataArray[(len - 1) / 2]
            : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
    }

    // /**
    //  * Retreive the index with given value
    //  * @param {string} dim Concrete dimension.
    //  * @param {number} value
    //  * @return {number}
    //  */
    // Currently incorrect: should return dataIndex but not rawIndex.
    // Do not fix it until this method is to be used somewhere.
    // FIXME Precision of float value
    // indexOf(dim, value) {
    //     var storage = this._storage;
    //     var dimData = storage[dim];
    //     var chunkSize = this._chunkSize;
    //     if (dimData) {
    //         for (var i = 0, len = this.count(); i < len; i++) {
    //             var chunkIndex = Math.floor(i / chunkSize);
    //             var chunkOffset = i % chunkSize;
    //             if (dimData[chunkIndex][chunkOffset] === value) {
    //                 return i;
    //             }
    //         }
    //     }
    //     return -1;
    // }
S
sushuang 已提交
925

926 927 928 929 930 931 932
    /**
     * Only support the dimension which inverted index created.
     * Do not support other cases until required.
     * @param dim concrete dim
     * @param value ordinal index
     * @return rawIndex
     */
1
100pah 已提交
933
    rawIndexOf(dim: DimensionName, value: OrdinalNumber): number {
934 935 936 937 938 939 940 941 942 943 944 945
        var invertedIndices = dim && this._invertedIndicesMap[dim];
        if (__DEV__) {
            if (!invertedIndices) {
                throw new Error('Do not supported yet');
            }
        }
        var rawIndex = invertedIndices[value];
        if (rawIndex == null || isNaN(rawIndex)) {
            return INDEX_NOT_FOUND;
        }
        return rawIndex;
    }
S
sushuang 已提交
946

947 948 949 950
    /**
     * Retreive the index with given name
     */
    indexOfName(name: string): number {
S
sushuang 已提交
951
        for (var i = 0, len = this.count(); i < len; i++) {
952 953
            if (this.getName(i) === name) {
                return i;
L
lang 已提交
954 955
            }
        }
H
hustcc 已提交
956

957 958
        return -1;
    }
S
sushuang 已提交
959

960 961 962 963 964 965
    /**
     * Retreive the index with given raw data index
     */
    indexOfRawIndex(rawIndex: number): number {
        if (rawIndex >= this._rawCount || rawIndex < 0) {
            return -1;
L
lang 已提交
966 967
        }

968 969
        if (!this._indices) {
            return rawIndex;
970 971
        }

972 973
        // Indices are ascending
        var indices = this._indices;
L
lang 已提交
974

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
        // If rawIndex === dataIndex
        var rawDataIndex = indices[rawIndex];
        if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
            return rawIndex;
        }

        var left = 0;
        var right = this._count - 1;
        while (left <= right) {
            var mid = (left + right) / 2 | 0;
            if (indices[mid] < rawIndex) {
                left = mid + 1;
            }
            else if (indices[mid] > rawIndex) {
                right = mid - 1;
            }
            else {
                return mid;
            }
        }
995 996 997
        return -1;
    }

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    /**
     * Retreive the index of nearest value
     * @param dim
     * @param value
     * @param [maxDistance=Infinity]
     * @return If and only if multiple indices has
     *         the same value, they are put to the result.
     */
    indicesOfNearest(
        dim: DimensionName, value: number, maxDistance?: number
    ): number[] {
        var storage = this._storage;
        var dimData = storage[dim];
        var nearestIndices: number[] = [];

        if (!dimData) {
            return nearestIndices;
        }
1016

1017 1018 1019
        if (maxDistance == null) {
            maxDistance = Infinity;
        }
S
sushuang 已提交
1020

1021 1022 1023
        var minDist = Infinity;
        var minDiff = -1;
        var nearestIndicesLen = 0;
1024

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
        // Check the test case of `test/ut/spec/data/List.js`.
        for (var i = 0, len = this.count(); i < len; i++) {
            var diff = value - (this.get(dim, i) as number);
            var dist = Math.abs(diff);
            if (dist <= maxDistance) {
                // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
                // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
                // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
                // So we chose the one that `diff >= 0` in this csae.
                // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
                // should be push to `nearestIndices`.
                if (dist < minDist
                    || (dist === minDist && diff >= 0 && minDiff < 0)
                ) {
                    minDist = dist;
                    minDiff = diff;
                    nearestIndicesLen = 0;
                }
                if (diff === minDiff) {
                    nearestIndices[nearestIndicesLen++] = i;
                }
            }
L
lang 已提交
1047
        }
1048
        nearestIndices.length = nearestIndicesLen;
L
lang 已提交
1049

S
sushuang 已提交
1050 1051
        return nearestIndices;
    }
L
lang 已提交
1052

1053 1054 1055 1056 1057 1058
    /**
     * Get raw data index.
     * Do not initialize.
     * Default `getRawIndex`. And it can be changed.
     */
    getRawIndex: (idx: number) => number = getRawIndexWithoutIndices;
L
lang 已提交
1059

1060 1061 1062 1063 1064 1065 1066 1067 1068
    /**
     * Get raw data item
     */
    getRawDataItem(idx: number): OptionDataItem {
        if (!this._rawData.persistent) {
            var val = [];
            for (var i = 0; i < this.dimensions.length; i++) {
                var dim = this.dimensions[i];
                val.push(this.get(dim, idx));
S
sushuang 已提交
1069
            }
1070 1071 1072 1073
            return val;
        }
        else {
            return this._rawData.getItem(this.getRawIndex(idx));
L
lang 已提交
1074 1075
        }
    }
P
pissang 已提交
1076

1077 1078 1079 1080 1081 1082
    getName(idx: number): string {
        var rawIndex = this.getRawIndex(idx);
        return this._nameList[rawIndex]
            || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
            || '';
    }
P
pissang 已提交
1083

1084 1085
    getId(idx: number): string {
        return getId(this, this.getRawIndex(idx));
1086
    }
L
lang 已提交
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    /**
     * Data iteration
     * @param ctx default this
     * @example
     *  list.each('x', function (x, idx) {});
     *  list.each(['x', 'y'], function (x, y, idx) {});
     *  list.each(function (idx) {})
     */
    each<Ctx>(cb: EachCb0<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): void;
    each<Ctx>(dims: DimensionLoose, cb: EachCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): void;
    each<Ctx>(dims: [DimensionLoose], cb: EachCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): void;
    each<Ctx>(dims: [DimensionLoose, DimensionLoose], cb: EachCb2<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): void;
    each<Ctx>(dims: ItrParamDims, cb: EachCb<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): void;
    each<Ctx>(
        dims: ItrParamDims | EachCb<Ctx>,
        cb: EachCb<Ctx> | Ctx,
        ctx?: Ctx,
        ctxCompat?: Ctx
    ): void {
        'use strict';

        if (!this._count) {
            return;
1111
        }
L
lang 已提交
1112

1113 1114 1115 1116 1117 1118
        if (typeof dims === 'function') {
            ctxCompat = ctx;
            ctx = cb as Ctx;
            cb = dims;
            dims = [];
        }
L
lang 已提交
1119

1120 1121
        // ctxCompat just for compat echarts3
        var fCtx = (ctx || ctxCompat || this) as CtxOrList<Ctx>;
L
lang 已提交
1122

1123
        var dimNames = zrUtil.map(normalizeDimensions(dims), this.getDimension, this);
L
lang 已提交
1124

1125 1126 1127
        if (__DEV__) {
            validateDimensions(this, dimNames);
        }
L
lang 已提交
1128

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        var dimSize = dimNames.length;

        for (var i = 0; i < this.count(); i++) {
            // Simple optimization
            switch (dimSize) {
                case 0:
                    (cb as EachCb0<Ctx>).call(fCtx, i);
                    break;
                case 1:
                    (cb as EachCb1<Ctx>).call(fCtx, this.get(dimNames[0], i), i);
                    break;
                case 2:
                    (cb as EachCb2<Ctx>).call(fCtx, this.get(dimNames[0], i), this.get(dimNames[1], i), i);
                    break;
                default:
                    var k = 0;
                    var value = [];
                    for (; k < dimSize; k++) {
                        value[k] = this.get(dimNames[k], i);
                    }
                    // Index
                    value[k] = i;
                    (cb as EachCb<Ctx>).apply(fCtx, value);
            }
1153 1154 1155
        }
    }

1156 1157 1158
    /**
     * Data filter
     */
P
pissang 已提交
1159 1160 1161 1162 1163
    filterSelf<Ctx>(cb: FilterCb0<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): this;
    filterSelf<Ctx>(dims: DimensionLoose, cb: FilterCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): this;
    filterSelf<Ctx>(dims: [DimensionLoose], cb: FilterCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): this;
    filterSelf<Ctx>(dims: [DimensionLoose, DimensionLoose], cb: FilterCb2<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): this;
    filterSelf<Ctx>(dims: ItrParamDims, cb: FilterCb<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): this;
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    filterSelf<Ctx>(
        dims: ItrParamDims | FilterCb<Ctx>,
        cb: FilterCb<Ctx> | Ctx,
        ctx?: Ctx,
        ctxCompat?: Ctx
    ): List {
        'use strict';

        if (!this._count) {
            return;
        }
1175

1176 1177 1178 1179 1180 1181
        if (typeof dims === 'function') {
            ctxCompat = ctx;
            ctx = cb as Ctx;
            cb = dims;
            dims = [];
        }
P
pissang 已提交
1182

1183 1184
        // ctxCompat just for compat echarts3
        var fCtx = (ctx || ctxCompat || this) as CtxOrList<Ctx>;
S
sushuang 已提交
1185

1186 1187 1188
        var dimNames = zrUtil.map(
            normalizeDimensions(dims), this.getDimension, this
        );
S
sushuang 已提交
1189

1190 1191 1192
        if (__DEV__) {
            validateDimensions(this, dimNames);
        }
S
sushuang 已提交
1193

1194

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
        var count = this.count();
        var Ctor = getIndicesCtor(this);
        var newIndices = new Ctor(count);
        var value = [];
        var dimSize = dimNames.length;

        var offset = 0;
        var dim0 = dimNames[0];

        for (var i = 0; i < count; i++) {
            var keep;
            var rawIdx = this.getRawIndex(i);
            // Simple optimization
            if (dimSize === 0) {
                keep = (cb as FilterCb0<Ctx>).call(fCtx, i);
            }
            else if (dimSize === 1) {
                var val = this._getFast(dim0, rawIdx);
                keep = (cb as FilterCb1<Ctx>).call(fCtx, val, i);
            }
            else {
                for (var k = 0; k < dimSize; k++) {
                    value[k] = this._getFast(dim0, rawIdx);
L
lang 已提交
1218 1219
                }
                value[k] = i;
1220 1221 1222 1223 1224
                keep = (cb as FilterCb<Ctx>).apply(fCtx, value);
            }
            if (keep) {
                newIndices[offset++] = rawIdx;
            }
L
lang 已提交
1225
        }
P
pissang 已提交
1226

1227 1228 1229 1230 1231 1232 1233
        // Set indices after filtered.
        if (offset < count) {
            this._indices = newIndices;
        }
        this._count = offset;
        // Reset data extent
        this._extent = {};
P
pissang 已提交
1234

1235
        this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
S
tweak.  
sushuang 已提交
1236

1237
        return this;
1238 1239
    }

1240 1241 1242 1243
    /**
     * Select data in range. (For optimization of filter)
     * (Manually inline code, support 5 million data filtering in data zoom.)
     */
P
pissang 已提交
1244
    selectRange(range: {[dimName: string]: [number, number]}): List {
1245
        'use strict';
1246

1247 1248
        if (!this._count) {
            return;
S
tweak.  
sushuang 已提交
1249
        }
1250 1251 1252 1253 1254

        var dimensions = [];
        for (var dim in range) {
            if (range.hasOwnProperty(dim)) {
                dimensions.push(dim);
S
tweak.  
sushuang 已提交
1255 1256
            }
        }
P
pissang 已提交
1257

1258 1259
        if (__DEV__) {
            validateDimensions(this, dimensions);
S
sushuang 已提交
1260
        }
1261

1262 1263 1264 1265
        var dimSize = dimensions.length;
        if (!dimSize) {
            return;
        }
P
pissang 已提交
1266

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
        var originalCount = this.count();
        var Ctor = getIndicesCtor(this);
        var newIndices = new Ctor(originalCount);

        var offset = 0;
        var dim0 = dimensions[0];

        var min = range[dim0][0];
        var max = range[dim0][1];

        var quickFinished = false;
        if (!this._indices) {
            // Extreme optimization for common case. About 2x faster in chrome.
            var idx = 0;
            if (dimSize === 1) {
                var dimStorage = this._storage[dimensions[0]];
                for (var k = 0; k < this._chunkCount; k++) {
                    var chunkStorage = dimStorage[k];
                    var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
                    for (var i = 0; i < len; i++) {
                        var val = chunkStorage[i];
                        // NaN will not be filtered. Consider the case, in line chart, empty
                        // value indicates the line should be broken. But for the case like
                        // scatter plot, a data item with empty value will not be rendered,
                        // but the axis extent may be effected if some other dim of the data
                        // item has value. Fortunately it is not a significant negative effect.
                        if (
                            (val >= min && val <= max) || isNaN(val as any)
                        ) {
                            newIndices[offset++] = idx;
                        }
                        idx++;
1299 1300
                    }
                }
1301
                quickFinished = true;
P
pissang 已提交
1302
            }
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
            else if (dimSize === 2) {
                var dimStorage = this._storage[dim0];
                var dimStorage2 = this._storage[dimensions[1]];
                var min2 = range[dimensions[1]][0];
                var max2 = range[dimensions[1]][1];
                for (var k = 0; k < this._chunkCount; k++) {
                    var chunkStorage = dimStorage[k];
                    var chunkStorage2 = dimStorage2[k];
                    var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
                    for (var i = 0; i < len; i++) {
                        var val = chunkStorage[i];
                        var val2 = chunkStorage2[i];
                        // Do not filter NaN, see comment above.
                        if ((
                                (val >= min && val <= max) || isNaN(val as any)
                            )
                            && (
                                (val2 >= min2 && val2 <= max2) || isNaN(val2 as any)
                            )
                        ) {
                            newIndices[offset++] = idx;
                        }
                        idx++;
P
pissang 已提交
1326
                    }
P
pissang 已提交
1327
                }
1328
                quickFinished = true;
P
pissang 已提交
1329 1330
            }
        }
1331 1332 1333 1334 1335
        if (!quickFinished) {
            if (dimSize === 1) {
                for (var i = 0; i < originalCount; i++) {
                    var rawIndex = this.getRawIndex(i);
                    var val = this._getFast(dim0, rawIndex);
1336
                    // Do not filter NaN, see comment above.
1337 1338 1339 1340
                    if (
                        (val >= min && val <= max) || isNaN(val as any)
                    ) {
                        newIndices[offset++] = rawIndex;
P
pissang 已提交
1341 1342
                    }
                }
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
            }
            else {
                for (var i = 0; i < originalCount; i++) {
                    var keep = true;
                    var rawIndex = this.getRawIndex(i);
                    for (var k = 0; k < dimSize; k++) {
                        var dimk = dimensions[k];
                        var val = this._getFast(dim, rawIndex);
                        // Do not filter NaN, see comment above.
                        if (val < range[dimk][0] || val > range[dimk][1]) {
                            keep = false;
                        }
                    }
                    if (keep) {
                        newIndices[offset++] = this.getRawIndex(i);
                    }
P
pissang 已提交
1359 1360 1361 1362
                }
            }
        }

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
        // Set indices after filtered.
        if (offset < originalCount) {
            this._indices = newIndices;
        }
        this._count = offset;
        // Reset data extent
        this._extent = {};

        this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;

        return this;
P
pissang 已提交
1374 1375
    }

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    /**
     * Data mapping to a plain array
     */
    mapArray<Ctx>(cb: MapArrayCb0<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): any[];
    mapArray<Ctx>(dims: DimensionLoose, cb: MapArrayCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): any[];
    mapArray<Ctx>(dims: [DimensionLoose], cb: MapArrayCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): any[];
    mapArray<Ctx>(dims: [DimensionLoose, DimensionLoose], cb: MapArrayCb2<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): any[];
    mapArray<Ctx>(dims: ItrParamDims, cb: MapArrayCb<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): any[];
    mapArray<Ctx>(
        dims: ItrParamDims | MapArrayCb<Ctx>,
        cb: MapArrayCb<Ctx> | Ctx,
        ctx?: Ctx,
        ctxCompat?: Ctx
    ): any[] {
        'use strict';

        if (typeof dims === 'function') {
            ctxCompat = ctx;
            ctx = cb as Ctx;
            cb = dims;
            dims = [];
        }
P
pissang 已提交
1398

1399 1400
        // ctxCompat just for compat echarts3
        ctx = (ctx || ctxCompat || this) as Ctx;
P
pissang 已提交
1401

1402 1403 1404 1405 1406
        var result: any[] = [];
        this.each(dims, function () {
            result.push(cb && (cb as MapArrayCb<Ctx>).apply(this, arguments));
        }, ctx);
        return result;
S
sushuang 已提交
1407 1408
    }

1409 1410 1411
    /**
     * Data mapping to a new List with given dimensions
     */
P
pissang 已提交
1412 1413 1414
    map<Ctx>(dims: DimensionLoose, cb: MapCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): List<HostModel>;
    map<Ctx>(dims: [DimensionLoose], cb: MapCb1<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): List<HostModel>;
    map<Ctx>(dims: [DimensionLoose, DimensionLoose], cb: MapCb2<Ctx>, ctx?: Ctx, ctxCompat?: Ctx): List<HostModel>;
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    map<Ctx>(
        dims: ItrParamDims,
        cb: MapCb<Ctx>,
        ctx?: Ctx,
        ctxCompat?: Ctx
    ): List {
        'use strict';

        // ctxCompat just for compat echarts3
        var fCtx = (ctx || ctxCompat || this) as CtxOrList<Ctx>;

        var dimNames = zrUtil.map(
            normalizeDimensions(dims), this.getDimension, this
        );

        if (__DEV__) {
            validateDimensions(this, dimNames);
        }

        var list = cloneListForMapAndSample(this, dimNames);
S
sushuang 已提交
1435

1436 1437 1438 1439 1440 1441
        // Following properties are all immutable.
        // So we can reference to the same value
        list._indices = this._indices;
        list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;

        var storage = list._storage;
S
sushuang 已提交
1442

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
        var tmpRetValue = [];
        var chunkSize = this._chunkSize;
        var dimSize = dimNames.length;
        var dataCount = this.count();
        var values = [];
        var rawExtent = list._rawExtent;

        for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
            for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
                values[dimIndex] = this.get(dimNames[dimIndex], dataIndex);
S
sushuang 已提交
1453
            }
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
            values[dimSize] = dataIndex;

            var retValue = cb && cb.apply(fCtx, values);
            if (retValue != null) {
                // a number or string (in oridinal dimension)?
                if (typeof retValue !== 'object') {
                    tmpRetValue[0] = retValue;
                    retValue = tmpRetValue;
                }

                var rawIndex = this.getRawIndex(dataIndex);
                var chunkIndex = Math.floor(rawIndex / chunkSize);
                var chunkOffset = rawIndex % chunkSize;

                for (var i = 0; i < retValue.length; i++) {
                    var dim = dimNames[i];
                    var val = retValue[i];
                    var rawExtentOnDim = rawExtent[dim];

                    var dimStore = storage[dim];
                    if (dimStore) {
                        dimStore[chunkIndex][chunkOffset] = val;
                    }

                    if (val < rawExtentOnDim[0]) {
                        rawExtentOnDim[0] = val as number;
                    }
                    if (val > rawExtentOnDim[1]) {
                        rawExtentOnDim[1] = val as number;
                    }
                }
S
sushuang 已提交
1485
            }
S
sushuang 已提交
1486
        }
S
sushuang 已提交
1487

1488
        return list;
S
sushuang 已提交
1489 1490
    }

1491 1492 1493 1494 1495 1496 1497
    /**
     * Large data down sampling on given dimension
     * @param sampleIndex Sample index for name and id
     */
    downSample(
        dimension: DimensionName,
        rate: number,
1498 1499
        sampleValue: (frameValues: ParsedValue[]) => ParsedValueNumeric,
        sampleIndex: (frameValues: ParsedValue[], value: ParsedValueNumeric) => number
P
pissang 已提交
1500
    ): List<HostModel> {
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
        var list = cloneListForMapAndSample(this, [dimension]);
        var targetStorage = list._storage;

        var frameValues = [];
        var frameSize = Math.floor(1 / rate);

        var dimStore = targetStorage[dimension];
        var len = this.count();
        var chunkSize = this._chunkSize;
        var rawExtentOnDim = list._rawExtent[dimension];

        var newIndices = new (getIndicesCtor(this))(len);

        var offset = 0;
        for (var i = 0; i < len; i += frameSize) {
            // Last frame
            if (frameSize > len - i) {
                frameSize = len - i;
                frameValues.length = frameSize;
            }
            for (var k = 0; k < frameSize; k++) {
                var dataIdx = this.getRawIndex(i + k);
                var originalChunkIndex = Math.floor(dataIdx / chunkSize);
                var originalChunkOffset = dataIdx % chunkSize;
                frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
            }
            var value = sampleValue(frameValues);
            var sampleFrameIdx = this.getRawIndex(
                Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
            );
            var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
            var sampleChunkOffset = sampleFrameIdx % chunkSize;
            // Only write value on the filtered data
            dimStore[sampleChunkIndex][sampleChunkOffset] = value;
S
sushuang 已提交
1535

1536 1537 1538 1539 1540 1541 1542 1543 1544
            if (value < rawExtentOnDim[0]) {
                rawExtentOnDim[0] = value;
            }
            if (value > rawExtentOnDim[1]) {
                rawExtentOnDim[1] = value;
            }

            newIndices[offset++] = sampleFrameIdx;
        }
1545

1546 1547
        list._count = offset;
        list._indices = newIndices;
S
sushuang 已提交
1548

1549
        list.getRawIndex = getRawIndexWithIndices;
S
sushuang 已提交
1550

P
pissang 已提交
1551
        return list as List<HostModel>;
1552 1553
    }

1554 1555 1556
    /**
     * Get model of one data item.
     */
P
pissang 已提交
1557
    // TODO: Type of data item
1558 1559
    getItemModel(idx: number): Model {
        var hostModel = this.hostModel;
1560 1561
        var dataItem = this.getRawDataItem(idx) as ModelOption;
        return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
1562
    }
S
sushuang 已提交
1563

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
    /**
     * Create a data differ
     */
    diff(otherList: List): DataDiffer {
        var thisList = this;

        return new DataDiffer(
            otherList ? otherList.getIndices() : [],
            this.getIndices(),
            function (idx) {
                return getId(otherList, idx);
            },
            function (idx) {
                return getId(thisList, idx);
            }
        );
    }
S
sushuang 已提交
1581

1582 1583 1584 1585 1586 1587 1588
    /**
     * Get visual property.
     */
    getVisual(key: string): any {
        var visual = this._visual;
        return visual && visual[key];
    }
S
sushuang 已提交
1589

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
    /**
     * Set visual property
     *
     * @example
     *  setVisual('color', color);
     *  setVisual({
     *      'color': color
     *  });
     */
    setVisual(key: string, val: any): void;
    setVisual(kvObj: Dictionary<any>): void;
    setVisual(key: string | Dictionary<any>, val?: any): void {
1602
        if (isObject(key)) {
1603 1604 1605 1606 1607 1608
            for (var name in key) {
                if (key.hasOwnProperty(name)) {
                    this.setVisual(name, key[name]);
                }
            }
            return;
S
sushuang 已提交
1609
        }
1610 1611 1612
        this._visual = this._visual || {};
        this._visual[key] = val;
    }
S
sushuang 已提交
1613

1614 1615 1616 1617 1618 1619
    /**
     * Set layout property.
     */
    setLayout(key: string, val: any): void;
    setLayout(kvObj: Dictionary<any>): void;
    setLayout(key: string | Dictionary<any>, val?: any): void {
1620
        if (isObject(key)) {
1621 1622 1623 1624
            for (var name in key) {
                if (key.hasOwnProperty(name)) {
                    this.setLayout(name, key[name]);
                }
L
lang 已提交
1625
            }
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
            return;
        }
        this._layout[key] = val;
    }

    /**
     * Get layout property.
     */
    getLayout(key: string): any {
        return this._layout[key];
    }
S
sushuang 已提交
1637

1638 1639 1640 1641 1642 1643
    /**
     * Get layout of single data item
     */
    getItemLayout(idx: number): Dictionary<any> {
        return this._itemLayouts[idx];
    }
S
sushuang 已提交
1644

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
    /**
     * Set layout of single data item
     */
    setItemLayout<M = false>(
        idx: number,
        layout: (M extends true ? Dictionary<any> : any),
        merge?: M
    ): void {
        this._itemLayouts[idx] = merge
            ? zrUtil.extend(this._itemLayouts[idx] || {}, layout)
            : layout;
    }
S
sushuang 已提交
1657

1658 1659 1660 1661 1662 1663
    /**
     * Clear all layout of single data item
     */
    clearItemLayouts(): void {
        this._itemLayouts.length = 0;
    }
S
sushuang 已提交
1664

1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
    /**
     * Get visual property of single data item
     */
    getItemVisual(idx: number, key: string, ignoreParent?: boolean): any {
        var itemVisual = this._itemVisuals[idx];
        var val = itemVisual && itemVisual[key];
        if (val == null && !ignoreParent) {
            // Use global visual property
            return this.getVisual(key);
        }
        return val;
    }

    /**
     * Set visual property of single data item
     *
     * @param {number} idx
     * @param {string|Object} key
     * @param {*} [value]
     *
     * @example
     *  setItemVisual(0, 'color', color);
     *  setItemVisual(0, {
     *      'color': color
     *  });
     */
    setItemVisual(idx: number, key: string, value: any): void;
    setItemVisual(idx: number, kvObject: Dictionary<any>): void;
    setItemVisual(idx: number, key: string | Dictionary<any>, value?: any): void {
        var itemVisual = this._itemVisuals[idx] || {};
        var hasItemVisual = this.hasItemVisual;
        this._itemVisuals[idx] = itemVisual;

1698
        if (isObject(key)) {
1699 1700 1701 1702
            for (var name in key) {
                if (key.hasOwnProperty(name)) {
                    itemVisual[name] = key[name];
                    hasItemVisual[name] = true;
S
sushuang 已提交
1703
                }
L
lang 已提交
1704
            }
1705
            return;
L
lang 已提交
1706
        }
1707 1708
        itemVisual[key] = value;
        hasItemVisual[key] = true;
S
sushuang 已提交
1709
    }
1710

1711 1712 1713 1714 1715 1716 1717 1718
    /**
     * Clear itemVisuals and list visual.
     */
    clearAllVisual(): void {
        this._visual = {};
        this._itemVisuals = [];
        this.hasItemVisual = {};
    }
L
lang 已提交
1719

1720 1721 1722 1723 1724
    /**
     * Set graphic element relative to data. It can be set as null
     */
    setItemGraphicEl(idx: number, el: Element): void {
        var hostModel = this.hostModel;
P
pissang 已提交
1725

1726 1727 1728 1729 1730 1731 1732 1733 1734
        if (el) {
            // Add data index and series index for indexing the data by element
            // Useful in tooltip
            (el as ECElement).dataIndex = idx;
            (el as ECElement).dataType = this.dataType;
            (el as ECElement).seriesIndex = hostModel && (hostModel as any).seriesIndex;
            if (el.type === 'group') {
                el.traverse(setItemDataAndSeriesIndex, el);
            }
S
sushuang 已提交
1735 1736
        }

1737
        this._graphicEls[idx] = el;
S
sushuang 已提交
1738
    }
L
lang 已提交
1739

1740 1741 1742
    getItemGraphicEl(idx: number): Element {
        return this._graphicEls[idx];
    }
P
pissang 已提交
1743

1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
    eachItemGraphicEl<Ctx = unknown>(
        cb: (this: Ctx, el: Element, idx: number) => void,
        context?: Ctx
    ): void {
        zrUtil.each(this._graphicEls, function (el, idx) {
            if (el) {
                cb && cb.call(context, el, idx);
            }
        });
    }
P
pissang 已提交
1754

1755 1756 1757 1758
    /**
     * Shallow clone a new list except visual and layout properties, and graph elements.
     * New list only change the indices.
     */
P
pissang 已提交
1759
    cloneShallow(list?: List<HostModel>): List<HostModel> {
1760 1761 1762 1763
        if (!list) {
            var dimensionInfoList = zrUtil.map(this.dimensions, this.getDimensionInfo, this);
            list = new List(dimensionInfoList, this.hostModel);
        }
L
lang 已提交
1764

1765 1766
        // FIXME
        list._storage = this._storage;
S
sushuang 已提交
1767

1768
        transferProperties(list, this);
S
sushuang 已提交
1769

1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
        // Clone will not change the data extent and indices
        if (this._indices) {
            var Ctor = this._indices.constructor as DataArrayLikeConstructor;
            if (Ctor === Array) {
                var thisCount = this._indices.length;
                list._indices = new Ctor(thisCount);
                for (var i = 0; i < thisCount; i++) {
                    list._indices[i] = this._indices[i];
                }
            }
            else {
                list._indices = new (Ctor as DataTypedArrayConstructor)(this._indices);
L
lang 已提交
1782
            }
L
lang 已提交
1783
        }
1784 1785 1786 1787 1788 1789
        else {
            list._indices = null;
        }
        list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;

        return list;
S
sushuang 已提交
1790
    }
L
lang 已提交
1791

1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
    /**
     * Wrap some method to add more feature
     */
    wrapMethod(
        methodName: FunctionPropertyNames<List>,
        injectFunction: (...args: any) => any
    ): void {
        var originalMethod = this[methodName];
        if (typeof originalMethod !== 'function') {
            return;
1802
        }
1803 1804 1805 1806 1807 1808
        this.__wrappedMethods = this.__wrappedMethods || [];
        this.__wrappedMethods.push(methodName);
        this[methodName] = function () {
            var res = (originalMethod as any).apply(this, arguments);
            return injectFunction.apply(this, [res].concat(zrUtil.slice(arguments)));
        };
S
sushuang 已提交
1809
    }
D
deqingli 已提交
1810 1811


1812 1813 1814
    // ----------------------------------------------------------
    // A work around for internal method visiting private member.
    // ----------------------------------------------------------
P
pissang 已提交
1815
    private static internalField = (function () {
L
lang 已提交
1816

1817
        defaultDimValueGetters = {
1818

1819
            arrayRows: getDimValueSimply,
L
lang 已提交
1820

1821 1822
            objectRows: function (
                this: List, dataItem: Dictionary<any>, dimName: string, dataIndex: number, dimIndex: number
1823
            ): ParsedValue {
1824 1825
                return convertDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
            },
L
lang 已提交
1826

1827 1828 1829 1830
            keyedColumns: getDimValueSimply,

            original: function (
                this: List, dataItem: any, dimName: string, dataIndex: number, dimIndex: number
1831
            ): ParsedValue {
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
                // Performance sensitive, do not use modelUtil.getDataItemValue.
                // If dataItem is an plain object with no value field, the var `value`
                // will be assigned with the object, but it will be tread correctly
                // in the `convertDataValue`.
                var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);

                // If any dataItem is like { value: 10 }
                if (!this._rawData.pure && isDataItemOption(dataItem)) {
                    this.hasItemOption = true;
                }
                return convertDataValue(
                    (value instanceof Array)
                        ? value[dimIndex]
                        // If value is a single number or something else not array.
                        : value,
                    this._dimensionInfos[dimName]
                );
            },

            typedArray: function (
                this: List, dataItem: any, dimName: string, dataIndex: number, dimIndex: number
1853
            ): ParsedValue {
1854
                return dataItem[dimIndex];
L
lang 已提交
1855
            }
P
pah100 已提交
1856

1857
        };
S
sushuang 已提交
1858

1859 1860
        function getDimValueSimply(
            this: List, dataItem: any, dimName: string, dataIndex: number, dimIndex: number
1861
        ): ParsedValue {
1862
            return convertDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
P
pah100 已提交
1863
        }
1864

1865 1866 1867 1868 1869
        /**
         * Convert raw the value in to inner value in List.
         * [Caution]: this is the key logic of user value parser.
         * For backward compatibiliy, do not modify it until have to.
         */
1870
        function convertDataValue(value: any, dimInfo: DataDimensionInfo): ParsedValue {
1871 1872 1873 1874 1875 1876 1877 1878 1879
            // Performance sensitive.
            var dimType = dimInfo && dimInfo.type;
            if (dimType === 'ordinal') {
                // If given value is a category string
                var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
                return ordinalMeta
                    ? ordinalMeta.parseAndCollect(value)
                    : value;
            }
P
pah100 已提交
1880

1881 1882 1883 1884 1885 1886 1887 1888
            if (dimType === 'time'
                // spead up when using timestamp
                && typeof value !== 'number'
                && value != null
                && value !== '-'
            ) {
                value = +parseDate(value);
            }
L
lang 已提交
1889

1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
            // dimType defaults 'number'.
            // If dimType is not ordinal and value is null or undefined or NaN or '-',
            // parse to NaN.
            return (value == null || value === '')
                ? NaN
                // If string (like '-'), using '+' parse to NaN
                // If object, also parse to NaN
                : +value;
        };

        prepareInvertedIndex = function (list: List): void {
            var invertedIndicesMap = list._invertedIndicesMap;
            zrUtil.each(invertedIndicesMap, function (invertedIndices, dim) {
                var dimInfo = list._dimensionInfos[dim];

                // Currently, only dimensions that has ordinalMeta can create inverted indices.
                var ordinalMeta = dimInfo.ordinalMeta;
                if (ordinalMeta) {
                    invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
                        ordinalMeta.categories.length
                    );
                    // The default value of TypedArray is 0. To avoid miss
                    // mapping to 0, we should set it as INDEX_NOT_FOUND.
                    for (var i = 0; i < invertedIndices.length; i++) {
                        invertedIndices[i] = INDEX_NOT_FOUND;
                    }
                    for (var i = 0; i < list._count; i++) {
                        // Only support the case that all values are distinct.
                        invertedIndices[list.get(dim, i) as number] = i;
                    }
                }
            });
        };

        getRawValueFromStore = function (list: List, dimIndex: number, rawIndex: number): any {
            var val;
            if (dimIndex != null) {
                var chunkSize = list._chunkSize;
                var chunkIndex = Math.floor(rawIndex / chunkSize);
                var chunkOffset = rawIndex % chunkSize;
                var dim = list.dimensions[dimIndex];
                var chunk = list._storage[dim][chunkIndex];
                if (chunk) {
                    val = chunk[chunkOffset];
                    var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
                    if (ordinalMeta && ordinalMeta.categories.length) {
1
100pah 已提交
1936
                        val = ordinalMeta.categories[val as OrdinalNumber];
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
                    }
                }
            }
            return val;
        };

        getIndicesCtor = function (list: List): DataArrayLikeConstructor {
            // The possible max value in this._indicies is always this._rawCount despite of filtering.
            return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
        };

        prepareChunks = function (
            storage: DataStorage,
            dimInfo: DataDimensionInfo,
            chunkSize: number,
            chunkCount: number,
            end: number
        ): void {
            var DataCtor = dataCtors[dimInfo.type];
            var lastChunkIndex = chunkCount - 1;
            var dim = dimInfo.name;
            var resizeChunkArray = storage[dim][lastChunkIndex];
            if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
                var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
                // The cost of the copy is probably inconsiderable
                // within the initial chunkSize.
                for (var j = 0; j < resizeChunkArray.length; j++) {
                    newStore[j] = resizeChunkArray[j];
                }
                storage[dim][lastChunkIndex] = newStore;
            }

            // Create new chunks.
            for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
                storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
            }
        };

        getRawIndexWithoutIndices = function (this: List, idx: number): number {
            return idx;
        };

        getRawIndexWithIndices = function (this: List, idx: number): number {
            if (idx < this._count && idx >= 0) {
                return this._indices[idx];
            }
            return -1;
        };

        getId = function (list: List, rawIndex: number): string {
            var id = list._idList[rawIndex];
            if (id == null) {
                id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
            }
            if (id == null) {
                // FIXME Check the usage in graph, should not use prefix.
                id = ID_PREFIX + rawIndex;
            }
            return id;
        };

        normalizeDimensions = function (
            dimensions: ItrParamDims
        ): Array<DimensionLoose> {
            if (!zrUtil.isArray(dimensions)) {
                dimensions = [dimensions];
            }
            return dimensions;
        };

        validateDimensions = function (list: List, dims: DimensionName[]): void {
            for (var i = 0; i < dims.length; i++) {
                // stroage may be empty when no data, so use
                // dimensionInfos to check.
                if (!list._dimensionInfos[dims[i]]) {
                    console.error('Unkown dimension ' + dims[i]);
                }
            }
        };

        // Data in excludeDimensions is copied, otherwise transfered.
        cloneListForMapAndSample = function (
            original: List, excludeDimensions: DimensionName[]
        ): List {
            var allDimensions = original.dimensions;
            var list = new List(
                zrUtil.map(allDimensions, original.getDimensionInfo, original),
                original.hostModel
            );
            // FIXME If needs stackedOn, value may already been stacked
            transferProperties(list, original);

            var storage = list._storage = {} as DataStorage;
            var originalStorage = original._storage;

            // Init storage
            for (var i = 0; i < allDimensions.length; i++) {
                var dim = allDimensions[i];
                if (originalStorage[dim]) {
                    // Notice that we do not reset invertedIndicesMap here, becuase
                    // there is no scenario of mapping or sampling ordinal dimension.
                    if (zrUtil.indexOf(excludeDimensions, dim) >= 0) {
                        storage[dim] = cloneDimStore(originalStorage[dim]);
                        list._rawExtent[dim] = getInitialExtent();
                        list._extent[dim] = null;
                    }
                    else {
                        // Direct reference for other dimensions
                        storage[dim] = originalStorage[dim];
                    }
                }
            }
            return list;
        };

        cloneDimStore = function (originalDimStore: DataValueChunk[]): DataValueChunk[] {
            var newDimStore = new Array(originalDimStore.length);
            for (var j = 0; j < originalDimStore.length; j++) {
                newDimStore[j] = cloneChunk(originalDimStore[j]);
            }
            return newDimStore;
        };

        function cloneChunk(originalChunk: DataValueChunk): DataValueChunk {
            var Ctor = originalChunk.constructor;
            // Only shallow clone is enough when Array.
            return Ctor === Array
2064
                ? (originalChunk as Array<ParsedValue>).slice()
2065
                : new (Ctor as DataTypedArrayConstructor)(originalChunk as DataTypedArray);
S
sushuang 已提交
2066
        }
L
lang 已提交
2067

2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
        getInitialExtent = function (): [number, number] {
            return [Infinity, -Infinity];
        };

        setItemDataAndSeriesIndex = function (this: Element, child: Element): void {
            (child as ECElement).seriesIndex = (this as ECElement).seriesIndex;
            (child as ECElement).dataIndex = (this as ECElement).dataIndex;
            (child as ECElement).dataType = (this as ECElement).dataType;
        };

        transferProperties = function (target: List, source: List): void {
            zrUtil.each(
                TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []),
                function (propName) {
                    if (source.hasOwnProperty(propName)) {
                        (target as any)[propName] = (source as any)[propName];
                    }
                }
            );
L
lang 已提交
2087

2088
            target.__wrappedMethods = source.__wrappedMethods;
L
lang 已提交
2089

2090 2091 2092
            zrUtil.each(CLONE_PROPERTIES, function (propName) {
                (target as any)[propName] = zrUtil.clone((source as any)[propName]);
            });
L
lang 已提交
2093

2094 2095
            target._calculationInfo = zrUtil.extend({}, source._calculationInfo);
        };
P
pah100 已提交
2096

2097
    })();
L
lang 已提交
2098

2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
}

// -----------------------------
// Internal method declarations:
// -----------------------------
var defaultDimValueGetters: {[sourceFormat: string]: DimValueGetter};
var prepareInvertedIndex: (list: List) => void;
var getRawValueFromStore: (list: List, dimIndex: number, rawIndex: number) => any;
var getIndicesCtor: (list: List) => DataArrayLikeConstructor;
var prepareChunks: (
    storage: DataStorage, dimInfo: DataDimensionInfo, chunkSize: number, chunkCount: number, end: number
) => void;
var getRawIndexWithoutIndices: (this: List, idx: number) => number;
var getRawIndexWithIndices: (this: List, idx: number) => number;
var getId: (list: List, rawIndex: number) => string;
var normalizeDimensions: (dimensions: ItrParamDims) => Array<DimensionLoose>;
var validateDimensions: (list: List, dims: DimensionName[]) => void;
var cloneListForMapAndSample: (original: List, excludeDimensions: DimensionName[]) => List;
var cloneDimStore: (originalDimStore: DataValueChunk[]) => DataValueChunk[];
var getInitialExtent: () => [number, number];
var setItemDataAndSeriesIndex: (this: Element, child: Element) => void;
var transferProperties: (target: List, source: List) => void;
2121

2122

S
sushuang 已提交
2123
export default List;