lodash#union TypeScript Examples

The following examples show how to use lodash#union. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: server-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
/**
 * Format the raw data to { [layerId]: availableDates }
 * @param rawLayers Layers data return by the server 'GetCapabilities' request
 * @param layerIdPath path to layer's id
 * @param datesPath path to layer's available dates
 * @returns an object shape like { [layerId]: availableDates }
 */
function formatCapabilitiesInfo(
  rawLayers: any,
  layerIdPath: string,
  datesPath: string,
): AvailableDates {
  return rawLayers.reduce((acc: any, layer: any) => {
    const layerId = get(layer, layerIdPath);
    const rawDates = get(layer, datesPath, []);

    const dates: (string | { _text: string })[] = isString(rawDates)
      ? rawDates.split(',')
      : rawDates;

    const availableDates = dates
      .filter((date) => !isEmpty(date))
      .map((date) =>
        // adding 12 hours to avoid  errors due to daylight saving
        moment.utc(get(date, '_text', date)).set({ hour: 12 }).valueOf(),
      );

    const { [layerId]: oldLayerDates } = acc;
    return {
      ...acc,
      [layerId]: union(availableDates, oldLayerDates),
    };
  }, {});
}
Example #2
Source File: server-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
/**
 * Format the raw data to { [layerId]: availableDates }
 * @param rawLayers Layers data return by the server 'GetCapabilities' request
 * @param layerIdPath path to layer's id
 * @param datesPath path to layer's available dates
 * @returns an object shape like { [layerId]: availableDates }
 */
function formatCapabilitiesInfo(
  rawLayers: any,
  layerIdPath: string,
  datesPath: string,
): AvailableDates {
  return rawLayers.reduce((acc: any, layer: any) => {
    const layerId = get(layer, layerIdPath);
    const rawDates = get(layer, datesPath, []);

    const dates: (string | { _text: string })[] = isString(rawDates)
      ? rawDates.split(',')
      : rawDates;

    const availableDates = dates
      .filter(date => !isEmpty(date))
      .map(date =>
        // adding 12 hours to avoid  errors due to daylight saving
        moment
          .utc(get(date, '_text', date).split('T')[0])
          .set({ hour: 12 })
          .valueOf(),
      );

    const { [layerId]: oldLayerDates } = acc;
    return {
      ...acc,
      [layerId]: union(availableDates, oldLayerDates),
    };
  }, {});
}
Example #3
Source File: helpers.ts    From aqualink-app with MIT License 6 votes vote down vote up
attachTimeSeries = (
  direction: "left" | "right",
  newData: TimeSeriesData,
  previousData?: TimeSeriesData
): TimeSeriesData => {
  const previousMetrics = Object.keys(previousData || {});
  const newMetrics = Object.keys(newData);
  const metrics = union(previousMetrics, newMetrics) as Metrics[];

  return metrics.reduce((ret, currMetric) => {
    const previousMetricData = previousData?.[currMetric] || {};
    const newMetricData = newData?.[currMetric] || {};
    const previousMetricSources = Object.keys(previousMetricData);
    const newMetricSources = Object.keys(newMetricData);
    const sources = union(previousMetricSources, newMetricSources) as Sources[];

    return {
      ...ret,
      [currMetric]: sources.reduce(
        (acc, source) => ({
          ...acc,
          [source]: {
            surveyPoint: (newMetricData || previousMetricData)?.[source]
              ?.surveyPoint,
            data: attachData(
              direction,
              newMetricData?.[source]?.data || [],
              previousMetricData?.[source]?.data || []
            ),
          },
        }),
        {}
      ),
    };
  }, {});
}
Example #4
Source File: assetsDbService.ts    From nautilus-wallet with MIT License 6 votes vote down vote up
public async sync(assets: IDbAsset[], walletId: number): Promise<void> {
    const groups = groupBy(assets, (a) => a.address);
    const dbGroups = groupBy(await this.getByWalletId(walletId), (a) => a.address);
    const groupKeys = union(keys(dbGroups), keys(groups));

    for (const key of groupKeys) {
      const group = groups[key];
      const dbGroup = dbGroups[key];

      if (isEmpty(dbGroup) && isEmpty(groups)) {
        continue;
      } else if (isEmpty(group) && !isEmpty(dbGroup)) {
        await dbContext.assets.bulkDelete(this.primaryKeysFrom(dbGroup));
        continue;
      } else if (isEmpty(dbGroup)) {
        await dbContext.assets.bulkPut(group);
        continue;
      }

      const remove = this.primaryKeysFrom(differenceBy(dbGroup, group, (a) => a.tokenId));
      const put = this.newOrChanged(dbGroup, group);
      if (remove.length > 0) {
        await dbContext.assets.bulkDelete(remove);
      }
      if (put.length > 0) {
        await dbContext.assets.bulkPut(put);
      }
    }
  }
Example #5
Source File: index.tsx    From web-pdm with Apache License 2.0 6 votes vote down vote up
@modelAction
    setCheckedKeys = (keys: string[]) => {
        if (!this.sys.tabOrTree) {
            this.sys.checkedKeys = keys
        } else {
            const modelKeys = [...this.Models.values()]
                .filter(
                    a =>
                        !this.sys.currentModule ||
                        a.moduleId === this.sys.currentModule
                )
                .map(a => a.id)
            const withoutKeys = without(modelKeys, ...keys)
            this.sys.checkedKeys = union(
                without(this.sys.checkedKeys, ...withoutKeys),
                keys
            )
        }
    }
Example #6
Source File: traceSummary.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
function endpointsForSpan(span: any) {
  return union(
    (span.annotations || []).map((a: any) => a.endpoint),
    (span.binaryAnnotations || []).map((a: any) => a.endpoint),
  ).filter((h) => h != null);
}
Example #7
Source File: index.tsx    From web-pdm with Apache License 2.0 5 votes vote down vote up
@modelAction
    checkAllFun() {
        const currentModule = this.sys.currentModule
        const modelIds = currentModule
            ? this.Modules.get(currentModule)?.models?.map(a => a.id)
            : [...this.Models.values()].map(a => a.id)
        this.sys.checkedKeys = union(this.sys.checkedKeys, modelIds)
    }
Example #8
Source File: time-series.spec.ts    From aqualink-app with MIT License 4 votes vote down vote up
timeSeriesTests = () => {
  const testService = TestService.getInstance();
  let app: INestApplication;
  let surveyPointDataRange: StringDateRange = [
    new Date(0).toISOString(),
    new Date().toISOString(),
  ];
  let siteDataRange: StringDateRange = [
    new Date(0).toISOString(),
    new Date().toISOString(),
  ];

  beforeAll(async () => {
    app = await testService.getApp();
  });

  it('GET /sites/:siteId/site-survey-points/:surveyPointId/range fetch range of poi data', async () => {
    const rsp = await request(app.getHttpServer()).get(
      `/time-series/sites/${athensSite.id}/site-survey-points/${athensSurveyPointPiraeus.id}/range`,
    );

    expect(rsp.status).toBe(200);
    const metrics = union(hoboMetrics, NOAAMetrics);
    metrics.forEach((metric) => {
      expect(rsp.body).toHaveProperty(metric);
    });
    hoboMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.HOBO);
      expect(rsp.body[metric][SourceType.HOBO].data.length).toBe(1);
      const { minDate, maxDate } = rsp.body[metric][SourceType.HOBO].data[0];
      const [startDate, endDate] = surveyPointDataRange;
      surveyPointDataRange = [
        min([minDate, startDate]),
        max([maxDate, endDate]),
      ];
    });
    NOAAMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.NOAA);
      expect(rsp.body[metric][SourceType.NOAA].data.length).toBe(1);
      const { minDate, maxDate } = rsp.body[metric][SourceType.NOAA].data[0];
      const [startDate, endDate] = surveyPointDataRange;
      surveyPointDataRange = [
        min([minDate, startDate]),
        max([maxDate, endDate]),
      ];
    });
  });

  it('GET /sites/:id/range fetch range of site data', async () => {
    const rsp = await request(app.getHttpServer()).get(
      `/time-series/sites/${californiaSite.id}/range`,
    );

    expect(rsp.status).toBe(200);
    const metrics = union(NOAAMetrics, spotterMetrics);
    metrics.forEach((metric) => {
      expect(rsp.body).toHaveProperty(metric);
    });
    NOAAMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.NOAA);
      expect(rsp.body[metric][SourceType.NOAA].data.length).toBe(1);
      const { minDate, maxDate } = rsp.body[metric][SourceType.NOAA].data[0];
      const [startDate, endDate] = siteDataRange;
      siteDataRange = [min([minDate, startDate]), max([maxDate, endDate])];
    });
    spotterMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.SPOTTER);
      expect(rsp.body[metric][SourceType.SPOTTER].data.length).toBe(1);
      const { minDate, maxDate } = rsp.body[metric][SourceType.SPOTTER].data[0];
      const [startDate, endDate] = siteDataRange;
      siteDataRange = [min([minDate, startDate]), max([maxDate, endDate])];
    });
  });

  it('GET /sites/:siteId/site-survey-points/:surveyPointId fetch poi data', async () => {
    const [startDate, endDate] = surveyPointDataRange;
    const rsp = await request(app.getHttpServer())
      .get(
        `/time-series/sites/${athensSite.id}/site-survey-points/${athensSurveyPointPiraeus.id}`,
      )
      .query({
        // Increase the search window to combat precision issues with the dates
        start: moment(startDate).subtract(1, 'minute').toISOString(),
        end: moment(endDate).add(1, 'day').toISOString(),
        metrics: hoboMetrics.concat(NOAAMetrics),
        hourly: false,
      });

    expect(rsp.status).toBe(200);
    const metrics = union(hoboMetrics, NOAAMetrics);
    metrics.forEach((metric) => {
      expect(rsp.body).toHaveProperty(metric);
    });
    hoboMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.HOBO);
      expect(rsp.body[metric][SourceType.HOBO].data.length).toBe(10);
    });
    NOAAMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.NOAA);
      expect(rsp.body[metric][SourceType.NOAA].data.length).toBe(10);
    });
  });

  it('GET /sites/:siteId fetch site data', async () => {
    const [startDate, endDate] = siteDataRange;
    const rsp = await request(app.getHttpServer())
      .get(`/time-series/sites/${californiaSite.id}`)
      .query({
        // Increase the search window to combat precision issues with the dates
        start: moment(startDate).subtract(1, 'minute').toISOString(),
        end: moment(endDate).add(1, 'day').toISOString(),
        metrics: spotterMetrics.concat(NOAAMetrics),
        hourly: false,
      });

    expect(rsp.status).toBe(200);
    const metrics = union(NOAAMetrics, spotterMetrics);
    metrics.forEach((metric) => {
      expect(rsp.body).toHaveProperty(metric);
    });
    NOAAMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.NOAA);
      expect(rsp.body[metric][SourceType.NOAA].data.length).toBe(10);
    });
    spotterMetrics.forEach((metric) => {
      expect(rsp.body[metric]).toHaveProperty(SourceType.SPOTTER);
      expect(rsp.body[metric][SourceType.SPOTTER].data.length).toBe(10);
    });
  });
}
Example #9
Source File: useSelection.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
useSelection = <RecordType,>(
  data: RecordType[],
  rowSelection: RowSelection<RecordType> | undefined,
  config: {
    rowKey?: TableProps<RecordType>['rowKey'];
  }
): [(columns: ColumnsType<RecordType>) => ColumnsType<RecordType>, Key[]] => {
  const { onChange, selectedRowKeys, columnWidth = 52, fixed, getCheckboxProps } = rowSelection || {};
  const { rowKey } = config;

  const [localSelectedRowKeys, setLocalSelectedRowKeys] = useControlledState<Key[]>(selectedRowKeys, []);

  // 获取当前页所有row的key
  const currentPageRowKeys = useMemo(() => flatten(data.map((item) => getRowKey(item, rowKey))), [data]);

  const isAllChecked = useMemo(
    () => intersection(localSelectedRowKeys, currentPageRowKeys).length === currentPageRowKeys.length,
    [currentPageRowKeys, localSelectedRowKeys]
  );
  const atLeastOneChecked = useMemo(
    () => intersection(currentPageRowKeys, localSelectedRowKeys).length > 0,
    [currentPageRowKeys, localSelectedRowKeys]
  );
  const isPartChecked = useMemo(() => !isAllChecked && atLeastOneChecked, [isAllChecked, atLeastOneChecked]);
  const isAllDisabled = useMemo(
    () => data.every((item) => getCheckboxProps?.(item)?.disabled),
    [data, getCheckboxProps]
  );

  const isRowAllSelected = (keys: any) => {
    const childrenKeys = Array.isArray(keys) ? keys.slice(1, keys.length) : [keys];

    return childrenKeys.every((keyItem) => localSelectedRowKeys.includes(keyItem));
  };

  const isRowPartSelected = (keys: any) =>
    Array.isArray(keys) ? keys.slice(1, keys.length).some((keyItem) => localSelectedRowKeys.includes(keyItem)) : false;

  const allDisabledKey: string[] = [];
  // 获取所有的disabled选项的key
  const getAllDisabledKey = (dataTree: any) => {
    dataTree.forEach((item: any) => {
      if (isFunction(getCheckboxProps) && getCheckboxProps(item).disabled) {
        Array.isArray(getRowKey(item, rowKey))
          ? allDisabledKey.push(...(getRowKey(item, rowKey) as any))
          : allDisabledKey.push(getRowKey(item, rowKey) as any);
      } else if (item.children) {
        getAllDisabledKey(item.children);
      }
    });
  };

  // 所有的子元素全部disabled
  const isParentDisabled = (keys: Key | Key[]) =>
    Array.isArray(keys) ? keys.slice(1).every((key) => allDisabledKey.includes(`${key}`)) : false;

  // 父元素disabled
  const isChildDisabled = (keys: Key | Key[]) => (Array.isArray(keys) ? false : allDisabledKey.includes(`${keys}`));

  const getSelectRows = useCallback(
    (_selectedRowKeys) => data.filter((item) => _selectedRowKeys.includes(getRowKey(item, rowKey))),
    [data]
  );

  // 获取父节点的keys
  const getParentKeys = (dataTree: any, keys: Key | Key[]): Key[] => {
    if (!Array.isArray(keys)) {
      if (data.some((item: any) => item.key === keys)) {
        return [];
      }

      // eslint-disable-next-line no-restricted-syntax
      for (let item of dataTree) {
        if (item.children) {
          if (item.children.some((child: any) => child.key === keys)) {
            return getRowKey(item, rowKey) as any;
          }

          return getParentKeys(item.children, keys);
        }
      }
    }

    return [];
  };

  // 更新parent的check状态
  const updateParentCheck = (selectedKeys: Key[], childKey: Key | Key[]): any => {
    const parentKeys = getParentKeys(data, childKey);
    if (parentKeys.length) {
      /** @todo: 无法执行此代码  */
      // if (parentKeys.slice(1).every((key) => selectedKeys.includes(key))) {
      //   // 向上递归更新状态,直至根结点
      //   return updateParentCheck(flattenDeep(union(selectedKeys, flattenDeep(parentKeys))), parentKeys[0]);
      // }
      return selectedKeys.filter((key) => key !== parentKeys[0]);
    }
    return selectedKeys;
  };

  const selectionColumn: ColumnType<RecordType> = {
    title: (
      <Checkbox
        checked={atLeastOneChecked}
        indeterminate={isPartChecked}
        onClick={(e) => e.stopPropagation()}
        onChange={(e) => {
          getAllDisabledKey(data);
          const latestLocalSelectedRowKeys = e.target.checked
            ? flattenDeep(difference(union(localSelectedRowKeys, currentPageRowKeys), allDisabledKey))
            : flattenDeep(difference(localSelectedRowKeys, currentPageRowKeys, allDisabledKey));
          setLocalSelectedRowKeys(latestLocalSelectedRowKeys);
          onChange?.(latestLocalSelectedRowKeys, getSelectRows(latestLocalSelectedRowKeys));
        }}
        disabled={isAllDisabled}
      />
    ),
    fixed,
    key: 'selection',
    align: 'center',
    width: columnWidth,
    render: (...rest) => {
      getAllDisabledKey(data);
      const key = getRowKey(rest[1], rowKey);
      const thisCheckboxProps = getCheckboxProps?.(rest[1]) || {};
      const { tooltipProps, disabled, ...restCheckboxProps } = thisCheckboxProps;
      const contentNode = (
        <div>
          <Checkbox
            {...restCheckboxProps}
            disabled={disabled || isParentDisabled(key) || isChildDisabled(key)}
            indeterminate={!isRowAllSelected(key) && isRowPartSelected(key)}
            checked={
              Array.isArray(key)
                ? key.some((keyItem) => localSelectedRowKeys.includes(keyItem))
                : localSelectedRowKeys.includes(key)
            }
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => {
              getAllDisabledKey(data);
              const latestLocalSelectedRowKeys = e.target.checked
                ? flattenDeep(difference(union(localSelectedRowKeys, flattenDeep([key])), allDisabledKey))
                : flattenDeep(difference(localSelectedRowKeys, flattenDeep([key]), allDisabledKey));
              setLocalSelectedRowKeys(latestLocalSelectedRowKeys);

              const updatedSelectedRowKeys = updateParentCheck(latestLocalSelectedRowKeys, key);
              setLocalSelectedRowKeys(updatedSelectedRowKeys);

              onChange?.(updatedSelectedRowKeys, getSelectRows(updatedSelectedRowKeys));
            }}
          >
            {disabled ? null : undefined}
          </Checkbox>
        </div>
      );
      return disabled ? (
        <Tooltip placement="topLeft" arrowPointAtCenter {...tooltipProps}>
          <span>{contentNode}</span>
        </Tooltip>
      ) : (
        <Tooltip placement="topLeft" arrowPointAtCenter {...tooltipProps}>
          {contentNode}
        </Tooltip>
      );
    },
  };

  const transformSelectionPipeline = useCallback(
    (columns: ColumnsType<RecordType>) => (!isUndefined(rowSelection) ? [selectionColumn, ...columns] : columns),
    [selectionColumn, rowSelection]
  );

  return [transformSelectionPipeline, localSelectedRowKeys];
}