lodash#sortBy JavaScript Examples

The following examples show how to use lodash#sortBy. 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: helpers.js    From sampo-ui with MIT License 6 votes vote down vote up
createPerspectiveConfigOnlyInfoPages = async ({ portalID, onlyInstancePagePerspectives }) => {
  const perspectiveConfigOnlyInfoPages = []
  for (const perspectiveID of onlyInstancePagePerspectives) {
    const { default: perspective } = await import(`../../configs/${portalID}/only_instance_pages/${perspectiveID}.json`)
    perspectiveConfigOnlyInfoPages.push(perspective)
  }
  for (const perspective of perspectiveConfigOnlyInfoPages) {
    const instancePageTabs = []
    const defaultResultClassConfig = perspective.resultClasses[perspective.id]
    if (has(defaultResultClassConfig.instanceConfig, 'instancePageResultClasses')) {
      for (const instancePageResultClassID in defaultResultClassConfig.instanceConfig.instancePageResultClasses) {
        const instancePageResultClassConfig = defaultResultClassConfig.instanceConfig.instancePageResultClasses[instancePageResultClassID]
        if (!instancePageResultClassConfig.hideTab && has(instancePageResultClassConfig, 'tabID') && has(instancePageResultClassConfig, 'tabPath')) {
          const { tabID, tabPath, tabIcon } = instancePageResultClassConfig
          instancePageTabs.push({
            id: tabPath,
            value: tabID,
            icon: <MuiIcon iconName={tabIcon} />
          })
        }
      }
    }
    perspective.instancePageTabs = sortBy(instancePageTabs, 'value')
  }
  return perspectiveConfigOnlyInfoPages
}
Example #2
Source File: capital.js    From climatescape.org with MIT License 6 votes vote down vote up
export function summarizeCapitalStages(stages) {
  if (!stages) return null
  if (stages.length === 1) return stages[0]

  const ordered = sortBy(stages, stage => capitalStages.indexOf(stage))
  const start = ordered[0]
  const end = ordered[stages.length - 1]

  return `${start}${end}`
}
Example #3
Source File: index.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
async componentDidMount() {
    const { secGrpId } = this.props;
    const dimensionTypes = await querySecGrpDimension(secGrpId);
    if (!isEmpty(dimensionTypes)) {
      const sortedDimensionTypes = sortBy(dimensionTypes, 'orderSeq');
      const defaultList = [
        'PURORG',
        'LOV',
        'DATASOURCE',
        'LOV_VIEW',
        'PURAGENT',
        'COMPANY',
        'DATA_GROUP',
      ];
      const arr = sortedDimensionTypes
        .filter(
          (item) => defaultList.includes(item.dimensionCode) && item.valueSourceType === 'LOCAL'
        )
        .map((item) => item.dimensionCode);
      this.setState({ defaultList: arr, allDimensions: dimensionTypes });
      this.loadDimensions(dimensionTypes);
    }
    // this.setState({
    //   authorityTypeCode: dimensionTypes.length ? dimensionTypes[0] : '',
    // });
  }
Example #4
Source File: capital.js    From climatescape.org with MIT License 6 votes vote down vote up
export function summarizeCapitalCheckSizes(checkSizes) {
  if (!checkSizes) return null
  if (checkSizes.length === 1) return checkSizes[0]

  const ordered = sortBy(checkSizes, size => extractNumeric(size))
  const start = ordered[0].split("-").shift()
  const end = ordered[ordered.length - 1].split("-").pop()

  return `${start}${end}`
}
Example #5
Source File: node-details-controls.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
export default function NodeDetailsControls({
  controls, error, nodeId, pending
}) {
  let spinnerClassName = 'fa fa-circle-notch fa-spin';
  if (pending) {
    spinnerClassName += ' node-details-controls-spinner';
  } else {
    spinnerClassName += ' node-details-controls-spinner hide';
  }

  return (
    <div className="node-details-controls">
      {error
        && (
        <div className="node-details-controls-error" title={error}>
          <i className="node-details-controls-error-icon fa fa-exclamation-triangle" />
          <span className="node-details-controls-error-messages">{error}</span>
        </div>
        )
      }
      <span className="node-details-controls-buttons">
        {sortBy(controls, 'rank').map(control => (
          <NodeDetailsControlButton
            nodeId={nodeId}
            control={control}
            pending={pending}
            key={control.id}
          />
        ))}
      </span>
      {controls && <span title="Applying..." className={spinnerClassName} />}
    </div>
  );
}
Example #6
Source File: configuration.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * @param {object} configuration the configuration from `getConfiguration`
 * @returns {array} array of  {index , title, thumbnail}
 */
export function getBaseMapsFromConfig({ pdfbasemaptitles: titles, pdfbasemapthumbnails: previews} = {}) {

    return sortBy((titles || []).map(({value, key}) => ({
        title: value,
        index: key.split(".").reverse()[1], // need to take "0" from "pdf.baseMap.0.title" --> split --> reverse --> [title, 0, ...]. So I get the element at index 1 to get the number.
        thumbnail: head((previews || []).filter(({key: kk}) => kk.indexOf(key) === 0).map(({value: vv}) => vv))
    })), "index");
}
Example #7
Source File: node-details-table.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
function sortNodes(nodes, getValue, sortedDesc) {
  const sortedNodes = sortBy(
    nodes,
    getValue,
    getMetaDataSorters(nodes)
  );
  if (sortedDesc) {
    sortedNodes.reverse();
  }
  return sortedNodes;
}
Example #8
Source File: data.js    From covid19-dashboard with MIT License 6 votes vote down vote up
export async function getReport(date, code) {
  const records = await getData(getFileName(date, code))
  const filteredReports = records.filter(item => item.code.includes(code))
  const sortedFilteredReports = sortBy(filteredReports, 'date')
  return {
    ...sortedFilteredReports.find(r => r.date === date),
    history: sortedFilteredReports
  }
}
Example #9
Source File: node-details-table.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
function sortNodes(nodes, getValue, sortedDesc) {
  const sortedNodes = sortBy(
    nodes,
    getValue,
    getMetaDataSorters(nodes)
  );
  if (sortedDesc) {
    sortedNodes.reverse();
  }
  return sortedNodes;
}
Example #10
Source File: PlotsSelectionTable.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
function PlotsSelectionTable({
    onRowDoubleClick = () => {},
    onRowsSelected = () => { },
    onRowsDeselected = () => { },
    data,
    selectedKeys
}) {
    const [sorting, setSorting] = useState();
    if (!data) {
        return null;
    }
    // create mixed column for address
    const processedRows = data.map(v => ({ ...v, cadastralAddr: v.dnvoiri + " " + v.cconvo + " " + v.dvoilib }));
    const rows = (({sortColumn, sortDirection} = {}) => {
        if (sortDirection === "ASC") {
            return sortBy(processedRows, sortColumn);
        } else if (sortDirection === "DESC") {
            return sortBy(processedRows, sortColumn).reverse();
        }
        return processedRows;
    })(sorting);
    return (<ReactDataGrid
        sortable
        onRowDoubleClick={onRowDoubleClick}
        rowGetter={i => rows[i]}
        rowsCount={rows.length}
        minHeight={230}
        columns={columns}
        onGridSort={(sortColumn, sortDirection) => {
            // sortDirection: "ASC", "DESC", "NONE"
            if (sortDirection === "NONE") {
                setSorting(undefined);
            } else {
                setSorting({sortColumn, sortDirection});
            }
        }}
        rowSelection={{
            showCheckbox: true,
            enableShiftSelect: true,
            onRowsSelected: (rr = []) => onRowsSelected(rr.map(({ row }) => row)),
            onRowsDeselected: (rr = []) => onRowsDeselected(rr.map(({ row }) => row)),
            selectBy: {
                keys: {
                    rowKey: 'parcelle',
                    values: selectedKeys
                }
            }
        }}
    />);
}
Example #11
Source File: index.js    From flatris-LAB_V1 with MIT License 5 votes vote down vote up
renderGameGrid(games: Array<Game>, showTrailingShell = false) {
    const { curUser } = this.props;
    const { added } = this.state;

    // Sort games consistently between renders
    // TODO: Add timestamps to games to be able to sort them by age
    const sortedGames = sortBy(games, game => game.id);
    return (
      <div className="game-grid">
        {sortedGames.map(game => {
          const { id } = game;
          const classes = classNames('game-preview', {
            'game-added': added.indexOf(id) !== -1,
            'game-removed': !this.props.games[id]
          });

          return (
            <Link key={id} href={`/join?g=${id}`} as={`/join/${id}`}>
              <div className={classes}>
                <GamePreview curUser={curUser} game={game} />
              </div>
            </Link>
          );
        })}
        {showTrailingShell && (
          <Link key="new-game" href="/new">
            <div className="game-preview">
              <GamePreviewShell />
            </div>
          </Link>
        )}
        <style jsx>{`
          .game-grid {
            overflow: hidden; /* clear the floats old school style */
          }
          .game-preview {
            float: left;
            position: relative;
            width: 320px;
            height: 400px;
            margin: 0 0 20px 20px;
            font-size: 12px;
            cursor: pointer;
          }
          .game-added {
            animation: 0.5s added forwards;
          }
          .game-removed {
            animation: 0.5s removed forwards;
          }

          @keyframes added {
            0% {
              opacity: 0;
              transform: scale(0.9);
            }
            100% {
              opacity: 1;
              transform: scale(1);
            }
          }
          @keyframes removed {
            0% {
              opacity: 1;
              transform: scale(1);
            }
            100% {
              opacity: 0;
              transform: scale(0.9);
            }
          }
        `}</style>
      </div>
    );
  }
Example #12
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useGambitVolumeData({ from, to }) {
  const [graphData, loading, error] = useGraph(`{
    volumeStats(
      first: 1000,
      where: { id_gte: ${from}, id_lte: ${to}, period: daily }
      orderBy: id
      orderDirection: desc
    ) {
      id
      margin
      swap
      liquidation
      mint
      burn
    }
  }`, {
    subgraph: 'gmx-io/gmx-bsc-stats'
  })

  let data
  if (graphData) {
    data = sortBy(graphData.volumeStats, item => item.id).map(({ id, margin, swap, liquidation, mint, burn }) => {
      margin = margin / 1e30
      swap = swap / 1e30
      liquidation = liquidation / 1e30
      mint = mint / 1e30
      burn = burn / 1e30
      const all = margin + swap + liquidation + mint + burn
      return {
        timestamp: id,
        all,
        margin,
        swap,
        liquidation,
        mint,
        burn
      }
    })
  }

  return [data, loading]
}
Example #13
Source File: workarounds.js    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
workaroundDuplicatedParcelle = parcelleProperty => (v, index, array) => {
    const sameParcelleElements = array.filter((vv) => vv?.properties?.[parcelleProperty] === v?.properties?.[parcelleProperty]);
    const correctValue = head(sortBy(sameParcelleElements, 'lot').reverse());
    return v?.properties?.lot === correctValue?.properties?.lot;
}
Example #14
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
// 编辑
  @Bind()
  async handleEdit(record) {
    const id = record.get('id');
    let frontLabels = (await queryApiLabel(id)) || [];
    frontLabels = isEmpty(frontLabels) ? [] : frontLabels;
    const labelList = this.drawerDS.toData() || [];
    record.set('apiTags', {
      PAGE: isEmpty(frontLabels) ? [] : frontLabels.map((item) => item.label.name).sort(),
    });
    const drawerProps = {
      labelList: sortBy(
        labelList.map((item) => {
          return {
            type: (frontLabels.find((temp) => temp.label.name === item.name) || {}).assignType,
            ...item,
          };
        }),
        (item) => item.name
      ),
      id,
      record,
    };
    // const originalData = this.tableDS.toData();
    this.tableDS.frontLabels = frontLabels
      .filter((item) => {
        return item.assignType === 'A';
      })
      .map((tmp) => {
        return tmp.label.name;
      });
    Modal.open({
      closable: true,
      key: 'knowledge-category',
      title: intl.get('hiam.apiManagement.view.message.edit').d('编辑API'),
      drawer: true,
      style: {
        width: 500,
      },
      children: <EditDrawer {...drawerProps} />,
      onOk: this.handleSave,
      onCancel: () => {
        // this.tableDS.loadData(originalData);
        record.reset();
      },
    });
  }
Example #15
Source File: FieldProp.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
renderFieldTypeLinkButtonProps() {
    const { field } = this.props;
    return (
      <React.Fragment>
        <Form.Item
          colon={false}
          label={
            <React.Fragment>
              {intl.get('hpfm.ui.field.linkButton').d('LinkButton')}
              :&nbsp;
              <a style={addButtonStyle} onClick={this.handleLinkButtonAddBtn}>
                {intl.get('hzero.common.button.create').d('新建')}
              </a>
            </React.Fragment>
          }
        />
        {map(sortBy(field.btns, 'orderSeq'), (btnConfig, index) => {
          const btnProps = {};
          forEach(btnConfig, attr => {
            btnProps[attr[attributeNameProp]] = attr[attributeValueProp];
          });
          const { btnKey } = btnProps;
          return (
            <Form.Item key={btnKey} className="ant-form-item-without-help">
              <Button
                style={linkButtonStyle}
                onClick={() => {
                  this.openPropEditModal(btnKey, btnProps, btnConfig, index);
                }}
              >
                {btnProps.title}
              </Button>
              <Icon
                type="edit"
                style={buttonStyle}
                onClick={() => {
                  this.openBtnTitleEditModal(btnKey, btnProps, btnConfig, index);
                }}
              />
              <Popconfirm
                title={intl.get('hzero.common.message.confirm.remove').d('确定删除选中数据?')}
                onConfirm={() => this.handleLinkButtonRemoveBtn(index)}
              >
                <Icon type="close" style={removeIconStyle} />
              </Popconfirm>
            </Form.Item>
          );
        })}
      </React.Fragment>
    );
  }
Example #16
Source File: bootstrap.js    From atomize with MIT License 5 votes vote down vote up
getSortedBreakpoints = memoize(breakpoints =>
  sortBy(
    Object.entries(breakpoints),
    ([, [item]]) => (item.type === 'max-width' ? -1 : 1),
    ([, [item]]) => item.value * (item.type === 'max-width' ? -1 : 1),
  ),
)
Example #17
Source File: bootstrap.js    From atomize with MIT License 5 votes vote down vote up
sortByBreakpointsOrder = (chunks, props) => {
  const sortedBreakpoints = getSortedBreakpoints(themeGet(props, 'breakpoints'));
  return sortBy(chunks, ({ chains }) =>
    sortedBreakpoints.findIndex(([key]) => key === chains.breackpointChain),
  );
}
Example #18
Source File: helpers.js    From sampo-ui with MIT License 5 votes vote down vote up
createPerspectiveConfig = async ({ portalID, searchPerspectives }) => {
  const perspectiveConfig = []
  for (const perspectiveID of searchPerspectives) {
    const { default: perspective } = await import(`../../configs/${portalID}/search_perspectives/${perspectiveID}.json`)
    perspectiveConfig.push(perspective)
  }
  for (const perspective of perspectiveConfig) {
    if (has(perspective, 'frontPageImage') && perspective.frontPageImage !== null) {
      const { default: image } = await import(/* webpackMode: "eager" */ `../img/${perspective.frontPageImage}`)
      perspective.frontPageImage = image
    }
    if (has(perspective, 'resultClasses')) {
      const tabs = []
      const instancePageTabs = []
      Object.keys(perspective.resultClasses).forEach(resultClass => {
        let resultClassConfig = perspective.resultClasses[resultClass]
        // handle the default resultClass of this perspective
        if (resultClass === perspective.id) {
          // default resultClass, instance pages
          if (has(resultClassConfig.instanceConfig, 'instancePageResultClasses')) {
            for (const instancePageResultClassID in resultClassConfig.instanceConfig.instancePageResultClasses) {
              const instancePageResultClassConfig = resultClassConfig.instanceConfig.instancePageResultClasses[instancePageResultClassID]
              if (!instancePageResultClassConfig.hideTab && has(instancePageResultClassConfig, 'tabID') && has(instancePageResultClassConfig, 'tabPath')) {
                const { tabID, tabPath, tabIcon } = instancePageResultClassConfig
                instancePageTabs.push({
                  id: tabPath,
                  value: tabID,
                  icon: <MuiIcon iconName={tabIcon} />
                })
              }
            }
          }
          // default resultClass, paginated results tab is added next
          resultClassConfig = resultClassConfig.paginatedResultsConfig
        }
        if (resultClassConfig && has(resultClassConfig, 'tabID') && !resultClassConfig.hideTab && has(resultClassConfig, 'tabPath')) {
          const { tabID, tabPath, tabIcon } = resultClassConfig
          tabs.push({
            id: tabPath,
            value: tabID,
            icon: <MuiIcon iconName={tabIcon} />
          })
        }
      })
      perspective.tabs = sortBy(tabs, 'value')
      perspective.instancePageTabs = sortBy(instancePageTabs, 'value')
    }
    if (has(perspective, 'defaultActiveFacets')) {
      perspective.defaultActiveFacets = new Set(perspective.defaultActiveFacets)
    }
  }
  return perspectiveConfig
}
Example #19
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useVolumesData({ from = FIRST_DATE_TS, to = NOW_TS, chainName = "arbitrum" } = {}) {
  const PROPS = 'margin liquidation swap mint burn'.split(' ')
  const feesQuery = `{
    volumeStats(
      first: 1000
      orderBy: id
      orderDirection: desc
      where: { period: daily, id_gte: ${from}, id_lte: ${to} }
    ) {
      id
      margin
      liquidation
      swap
      mint
      burn
      ${chainName === "avalanche" ? "timestamp" : ""}
    }
  }`
  let [feesData, loading, error] = useGraph(feesQuery, {
    chainName
  })

  const feesChartData = useMemo(() => {
    if (!feesData) {
      return null
    }

    let chartData = sortBy(feesData.feeStats, 'id').map(item => {
      const ret = { timestamp: item.timestamp || item.id };

      PROPS.forEach(prop => {
        if (item[prop]) {
          ret[prop] = item[prop] / 1e30
        }
      })

      ret.liquidation = item.liquidation / 1e30 - item.margin / 1e30
      ret.all = PROPS.reduce((memo, prop) => memo + ret[prop], 0)
      return ret
    })

    let cumulative = 0
    const cumulativeByTs = {}
    return chain(chartData)
      .groupBy(item => item.timestamp)
      .map((values, timestamp) => {
        const all = sumBy(values, 'all')
        cumulative += all

        let movingAverageAll
        const movingAverageTs = timestamp - MOVING_AVERAGE_PERIOD
        if (movingAverageTs in cumulativeByTs) {
          movingAverageAll = (cumulative - cumulativeByTs[movingAverageTs]) / MOVING_AVERAGE_DAYS
        }

        const ret = {
          timestamp: Number(timestamp),
          all,
          cumulative,
          movingAverageAll
        }
        PROPS.forEach(prop => {
           ret[prop] = sumBy(values, prop)
        })
        cumulativeByTs[timestamp] = cumulative
        return ret
      })
      .value()
      .filter(item => item.timestamp >= from)
  }, [feesData])
  return [feesChartData, loading, error]
}
Example #20
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useFeesData({ from = FIRST_DATE_TS, to = NOW_TS, chainName = "arbitrum" } = {}) {
  const PROPS = 'margin liquidation swap mint burn'.split(' ')
  const feesQuery = `{
    feeStats(
      first: 1000
      orderBy: id
      orderDirection: desc
      where: { period: daily, id_gte: ${from}, id_lte: ${to} }
    ) {
      id
      margin
      marginAndLiquidation
      swap
      mint
      burn
      ${chainName === "avalanche" ? "timestamp" : ""}
    }
  }`
  let [feesData, loading, error] = useGraph(feesQuery, {
    chainName
  })

  const feesChartData = useMemo(() => {
    if (!feesData) {
      return null
    }

    let chartData = sortBy(feesData.feeStats, 'id').map(item => {
      const ret = { timestamp: item.timestamp || item.id };

      PROPS.forEach(prop => {
        if (item[prop]) {
          ret[prop] = item[prop] / 1e30
        }
      })

      ret.liquidation = item.marginAndLiquidation / 1e30 - item.margin / 1e30
      ret.all = PROPS.reduce((memo, prop) => memo + ret[prop], 0)
      return ret
    })

    let cumulative = 0
    const cumulativeByTs = {}
    return chain(chartData)
      .groupBy(item => item.timestamp)
      .map((values, timestamp) => {
        const all = sumBy(values, 'all')
        cumulative += all

        let movingAverageAll
        const movingAverageTs = timestamp - MOVING_AVERAGE_PERIOD
        if (movingAverageTs in cumulativeByTs) {
          movingAverageAll = (cumulative - cumulativeByTs[movingAverageTs]) / MOVING_AVERAGE_DAYS
        }

        const ret = {
          timestamp: Number(timestamp),
          all,
          cumulative,
          movingAverageAll
        }
        PROPS.forEach(prop => {
           ret[prop] = sumBy(values, prop)
        })
        cumulativeByTs[timestamp] = cumulative
        return ret
      })
      .value()
      .filter(item => item.timestamp >= from)
  }, [feesData])
  return [feesChartData, loading, error]
}
Example #21
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useVolumeData({ from = FIRST_DATE_TS, to = NOW_TS, chainName = "arbitrum" } = {}) {
	const PROPS = 'margin liquidation swap mint burn'.split(' ')
  const timestampProp = chainName === "arbitrum" ? "id" : "timestamp"
  const query = `{
    volumeStats(
      first: 1000,
      orderBy: ${timestampProp},
      orderDirection: desc
      where: { period: daily, ${timestampProp}_gte: ${from}, ${timestampProp}_lte: ${to} }
    ) {
      ${timestampProp}
      ${PROPS.join('\n')}
    }
  }`
  const [graphData, loading, error] = useGraph(query, { chainName })

  const data = useMemo(() => {
    if (!graphData) {
      return null
    }

    let ret =  sortBy(graphData.volumeStats, timestampProp).map(item => {
      const ret = { timestamp: item[timestampProp] };
      let all = 0;
      PROPS.forEach(prop => {
        ret[prop] = item[prop] / 1e30
        all += ret[prop]
      })
      ret.all = all
      return ret
    })

    let cumulative = 0
    const cumulativeByTs = {}
    return ret.map(item => {
      cumulative += item.all

      let movingAverageAll
      const movingAverageTs = item.timestamp - MOVING_AVERAGE_PERIOD
      if (movingAverageTs in cumulativeByTs) {
        movingAverageAll = (cumulative - cumulativeByTs[movingAverageTs]) / MOVING_AVERAGE_DAYS
      }

      return {
        movingAverageAll,
        cumulative,
        ...item
      }
    })
  }, [graphData])
  return [data, loading, error]
}
Example #22
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useBorrowRateData({ from = FIRST_DATE_TS, to = NOW_TS, chainName = "arbitrum" } = {}) {
  const query = `{
    borrowRates(
      first: 1000,
      orderBy: timestamp,
      orderDirection: desc,
      where: { period: "daily", id_gte: ${from}, id_lte: ${to} }
    ) {
      id,
      token,
      timestamp,
      startBorrowRate,
      startTimestamp,
      endBorrowRate,
      endTimestamp
    }
  }`
  const [graphData, loading, error] = useGraph(query, { chainName })


  const data = useMemo(() => {
    if (!graphData) {
      return null
    }

    const groups = graphData.borrowRates.reduce((memo, item) => {
      const symbol = tokenSymbols[item.token];
      memo[item.timestamp] = memo[item.timestamp] || {
        timestamp: item.timestamp
      }
      const group = memo[item.timestamp]
      const timeDelta = parseInt((item.endTimestamp - item.startTimestamp) / 3600) * 3600

      let borrowRate = 0
      if (item.endBorrowRate && item.startBorrowRate) {
        const fundingDelta = item.endBorrowRate - item.startBorrowRate
        const divisor = timeDelta / 86400
        borrowRate = fundingDelta / divisor / 10000 * 365
      }
      group[symbol] = borrowRate
      return memo
    }, {})
    return fillNa(sortBy(Object.values(groups), 'timestamp'), ['ETH', 'USDC', 'USDT', 'BTC', 'MATIC'])
  }, [graphData])

  return [data, loading, error]
}
Example #23
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useUsersData({ from = FIRST_DATE_TS, to = NOW_TS, chainName = "arbitrum" } = {}) {
  const query = `{
    userStats(
      first: 1000
      orderBy: timestamp
      orderDirection: desc
      where: { period: "daily", timestamp_gte: ${from}, timestamp_lte: ${to} }
    ) {
      uniqueCount
      uniqueSwapCount
      uniqueMarginCount
      uniqueMintBurnCount
      uniqueCountCumulative
      uniqueSwapCountCumulative
      uniqueMarginCountCumulative
      uniqueMintBurnCountCumulative
      actionCount
      actionSwapCount
      actionMarginCount
      actionMintBurnCount
      timestamp
    }
  }`
  const [graphData, loading, error] = useGraph(query, { chainName })

  const prevUniqueCountCumulative = {}
  const data = graphData ? sortBy(graphData.userStats, 'timestamp').map(item => {
    const newCountData = ['', 'Swap', 'Margin', 'MintBurn'].reduce((memo, type) => {
      memo[`new${type}Count`] = prevUniqueCountCumulative[type]
        ? item[`unique${type}CountCumulative`] - prevUniqueCountCumulative[type]
        : item[`unique${type}Count`]
      prevUniqueCountCumulative[type] = item[`unique${type}CountCumulative`]
      return memo
    }, {})
    const oldCount = item.uniqueCount - newCountData.newCount
    const oldPercent = (oldCount / item.uniqueCount * 100).toFixed(1)
    return {
      all: item.uniqueCount,
      uniqueSum: item.uniqueSwapCount + item.uniqueMarginCount + item.uniqueMintBurnCount,
      oldCount,
      oldPercent,
      ...newCountData,
      ...item
    }
  }) : null

  return [data, loading, error]
}
Example #24
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useSwapSources({ from = FIRST_DATE_TS, to = NOW_TS, chainName = "arbitrum" } = {}) {
  const query = `{
    a: ${getSwapSourcesFragment(0, from, to)}
    b: ${getSwapSourcesFragment(1000, from, to)}
    c: ${getSwapSourcesFragment(2000, from, to)}
    d: ${getSwapSourcesFragment(3000, from, to)}
    e: ${getSwapSourcesFragment(4000, from, to)}
  }`
  const [graphData, loading, error] = useGraph(query, { chainName })

  let total = 0
  let data = useMemo(() => {
    if (!graphData) {
      return null
    }

    const {a, b, c, d, e} = graphData
    let ret = chain([...a, ...b, ...c, ...d, ...e])
      .groupBy(item => parseInt(item.timestamp / 86400) * 86400)
      .map((values, timestamp) => {
        let all = 0
        const retItem = {
          timestamp: Number(timestamp),
          ...values.reduce((memo, item) => {
            const source = knownSwapSources[chainName][item.source] || item.source
            if (item.swap != 0) {
              const volume = item.swap / 1e30
              memo[source] = memo[source] || 0
              memo[source] += volume
              all += volume
            }
            return memo
          }, {})
        } 

        retItem.all = all

        return retItem
      })
      .sortBy(item => item.timestamp)
      .value()

    return ret
  }, [graphData])

  return [data, loading, error]
}
Example #25
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useGambitPoolStats({ from, to, groupPeriod }) {
  const [data, loading, error] = useGraph(`{
    poolStats (
      first: 1000,
      where: { id_gte: ${from}, id_lte: ${to} }
      orderBy: id
      orderDirection: desc
    ) {
      id,
      usdgSupply,
      BTC_usd,
      ETH_usd,
      BNB_usd,
      USDC_usd,
      USDT_usd,
      BUSD_usd
    }
  }`, { subgraph: 'gkrasulya/gambit' })

  const ret = useMemo(() => {
    if (!data) {
       return null
    } 
    let ret = data.poolStats.map(item => {
      return Object.entries(item).reduce((memo, [key, value]) => {
        if (key === 'id') memo.timestamp = value
        else if (key === 'usdgSupply') memo.usdgSupply = value / 1e18
        else memo[key.substr(0, key.length - 4)] = value / 1e30
        return memo
      }, {})
    })

    ret = chain(ret)
      .sortBy('timestamp')
      .groupBy(item => Math.floor(item.timestamp / groupPeriod) * groupPeriod)
      .map((values, timestamp) => {
        return {
          ...values[values.length - 1],
          timestamp
        }
      })
      .value()

     return fillPeriods(ret, { period: groupPeriod, from, to, interpolate: false, extrapolate: true })
  }, [data])

  return [ret, loading, error]
}
Example #26
Source File: dataProvider.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useGambitFeesData({ from, to }) {
  const [graphData, loading, error] = useGraph(`{
    feeStats(
      first: 1000,
      where: { id_gte: ${from}, id_lte: ${to}, period: daily }
      orderBy: id
      orderDirection: desc
    ) {
      id
      margin
      swap
      mint
      burn
      marginCumulative
      swapCumulative
      liquidationCumulative
      mintCumulative
      burnCumulative
    }
  }`, {
    subgraph: 'gmx-io/gmx-bsc-stats'
  })

  let data
  if (graphData) {
    data = sortBy(graphData.feeStats, item => item.id).map(({ id, margin, swap, mint, burn }) => {
      margin = margin / 1e30
      swap = swap / 1e30
      const liquidation = 0
      mint = mint / 1e30
      burn = burn / 1e30
      const all = margin + swap + mint + burn
      return {
        timestamp: id,
        all,
        margin,
        swap,
        liquidation,
        mint,
        burn
      }
    })
  }

  return [data, loading]
}
Example #27
Source File: ChartData.js    From powir with GNU General Public License v3.0 4 votes vote down vote up
function createBatteryLifeHistoryData(info) {
    function getDaysInMonth(date) {
        return new Date(date.getFullYear(), date.getMonth()+1, 0).getDate()
    }

    function chooseDate(date) {
        let [start_date, end_date] = date.split(" - ")
        if (getDaysInMonth(new Date(start_date)) - new Date(start_date).getDate() > new Date(end_date).getDate()) {
            return start_date.split("-").slice(0, 2).join("")
        }
        return end_date.split("-").slice(0, 2).join("")
    }

    function filterOutliers(array) {
        /*
        * Reference: https://www.mathworks.com/matlabcentral/cody/problems/42485-eliminate-outliers-using-interquartile-range
        * Following this approach except we aren't repeating the IQR and elimination process after every step.
        * */
        // Then sort
        // noinspection JSValidateTypes
        if (array.length < 4) {
            return {
                data: array,
                indexes: []
            }
        }
        // noinspection JSValidateTypes
        let values = sortBy(array)

        /* Then find a generous IQR. This is generous because if (values.length / 4)
         * is not an int, then really you should average the two elements on either
         * side to find q1.
         */
        let q1 = values[Math.floor((values.length / 4))]
        // Likewise for q3.
        let q3 = values[Math.ceil((values.length * (3 / 4)))]
        let iqr = q3 - q1;

        // Then find min and max values
        let maxValue = q3 + iqr*1.5;

        // Then reduce anything beyond or beneath these values.
        return array.reduce((data, item, index) => {
            if (item <= maxValue) {
                data.indexes.push(index)
                data.data.push(item)
                return data
            }
            return data
        }, {
            data: [],
            indexes: []
        })
    }

    function averageDatasetByMonth(value, index) {
        return value.reduce((data, element) => {
            data += element[index]
            return data
        }, 0) / value.length
    }

    let formattedInfo = groupBy(info.data.reduce((data, item) => {
        if (item[1] === "0:00:00" || item[3] === "0:00:00") {
            return data
        }
        data.push([
            chooseDate(item[0]),
            Number(item[1].split(":")[0])*60 + Number(item[1].split(":")[1]),
            Number(item[3].split(":")[0])*60 + Number(item[3].split(":")[1]),
        ])
        return data
    }, []), 0)

    let activeDataset = []
    let designDataset = []

    for (let [, value] of Object.entries(formattedInfo)) {
        activeDataset.push(averageDatasetByMonth(value, 1))
        designDataset.push(averageDatasetByMonth(value, 2))
    }
    let filteredDataset = filterOutliers(activeDataset)
    let filteredActiveDataset = filterOutliers(activeDataset).data
    let filteredDesignDataset = designDataset.filter((item, index) => filteredDataset.indexes.includes(index))
    let labelsDataset = Object.keys(formattedInfo).reduce((data, item, index) => {
        if (filteredDataset.indexes.includes(index)) {
            data.push(item.slice(0, 4) + "/" + item.slice(4, 6))
            return data
        }
        return data
    }, [])

    return {
        labels: labelsDataset,
        datasets: [{
            label: info.keys[1],
            backgroundColor: 'red',
            borderColor: 'red',
            data: filteredActiveDataset,
            fill: false,
        }, {
            label: info.keys[3],
            backgroundColor: 'blue',
            borderColor: 'blue',
            data: filteredDesignDataset,
            fill: false,
        }]
    }
}
Example #28
Source File: index.js    From strapi-molecules with MIT License 4 votes vote down vote up
EditView = ({
  components,
  currentEnvironment,
  deleteLayout,
  layouts,
  plugins,
  slug,
}) => {
  const formatLayoutRef = useRef();
  formatLayoutRef.current = createAttributesLayout;
  const { goBack } = useHistory();
  // Retrieve the search and the pathname
  const { pathname } = useLocation();
  const {
    params: { contentType },
  } = useRouteMatch("/plugins/content-manager/:contentType");
  const viewPermissions = useMemo(() => generatePermissionsObject(slug), [
    slug,
  ]);
  const { allowedActions } = useUserPermissions(viewPermissions);

  const entityId = pathname.split("/").pop();
  const [versions, setVersions] = useState([{ date: "current" }]);
  const [selectedVersion, setSelectedVersion] = useState("current");

  const changeLatestDateToCurrent = (versions) => {
    if (versions.length) {
      const sortedVersions = [...versions].sort(
        (previous, next) =>
          new Date(previous.date).getTime() - new Date(next.date).getTime(),
      );

      return sortedVersions.map((sortedVersion, i, arr) => {
        if (i === arr.length - 1) {
          sortedVersion = {
            ...sortedVersion,
            date: "current",
          };
        }
        return sortedVersion;
      });
    }
    return [{ date: "current" }];
  };

  useEffect(() => {
    const getVersions = async () => {
      try {
        const versions = await request(
          getRequestUrl(`explorer/versions/${slug}/${entityId}`),
          {
            method: "GET",
          },
        );
        setVersions(changeLatestDateToCurrent(versions));
      } catch (err) {
        strapi.notification.error("content-manager.error.relation.fetch");
      }
    };
    if (entityId != "create") {
      getVersions();
    }
  }, [slug, entityId]);

  const generateDataForSelectedOption = () =>
    versions.length <= 1
      ? {}
      : versions.find((version) => version.date === selectedVersion).content;

  const isSingleType = useMemo(() => contentType === "singleType", [
    contentType,
  ]);
  const [
    { formattedContentTypeLayout, isDraggingComponent },
    dispatch,
  ] = useReducer(reducer, initialState, () => init(initialState));
  const allLayoutData = useMemo(() => get(layouts, [slug], {}), [
    layouts,
    slug,
  ]);
  const currentContentTypeLayoutData = useMemo(
    () => get(allLayoutData, ["contentType"], {}),
    [allLayoutData],
  );
  const currentContentTypeLayout = useMemo(
    () => get(currentContentTypeLayoutData, ["layouts", "edit"], []),
    [currentContentTypeLayoutData],
  );
  const currentContentTypeLayoutRelations = useMemo(
    () => get(currentContentTypeLayoutData, ["layouts", "editRelations"], []),
    [currentContentTypeLayoutData],
  );
  const currentContentTypeSchema = useMemo(
    () => get(currentContentTypeLayoutData, ["schema"], {}),
    [currentContentTypeLayoutData],
  );

  const getFieldMetas = useCallback(
    (fieldName) => {
      return get(
        currentContentTypeLayoutData,
        ["metadatas", fieldName, "edit"],
        {},
      );
    },
    [currentContentTypeLayoutData],
  );
  const getField = useCallback(
    (fieldName) => {
      return get(currentContentTypeSchema, ["attributes", fieldName], {});
    },
    [currentContentTypeSchema],
  );
  const getFieldType = useCallback(
    (fieldName) => {
      return get(getField(fieldName), ["type"], "");
    },
    [getField],
  );
  const getFieldComponentUid = useCallback(
    (fieldName) => {
      return get(getField(fieldName), ["component"], "");
    },
    [getField],
  );

  // Check if a block is a dynamic zone
  const isDynamicZone = useCallback(
    (block) => {
      return block.every((subBlock) => {
        return subBlock.every(
          (obj) => getFieldType(obj.name) === "dynamiczone",
        );
      });
    },
    [getFieldType],
  );

  useEffect(() => {
    // Force state to be cleared when navigation from one entry to another
    dispatch({ type: "RESET_PROPS" });
    dispatch({
      type: "SET_LAYOUT_DATA",
      formattedContentTypeLayout: formatLayoutRef.current(
        currentContentTypeLayout,
        currentContentTypeSchema.attributes,
      ),
    });

    return () => deleteLayout(slug);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentContentTypeLayout, currentContentTypeSchema.attributes]);

  const isVersionCurrent = () => selectedVersion === "current";
  const currentFieldNames = Object.keys(currentContentTypeSchema.attributes);

  const currentVersionFieldNames = () => {
    if (selectedVersion === "current") {
      return [];
    }

    return Object.keys(generateDataForSelectedOption());
  };

  const isSelectVersionContainsAllCurrentRelations = () => {
    if (generateDataForSelectedOption()) {
      const selectedVersionAttributeNames = Object.keys(
        generateDataForSelectedOption(),
      );

      return currentContentTypeLayoutRelations.every((el) =>
        selectedVersionAttributeNames.includes(el),
      );
    }
    return true;
  };

  const removeUnnecessaryAttributes = (
    originalArray,
    unnecessaryAttributes,
  ) => {
    return originalArray.filter(
      (value) => !unnecessaryAttributes.includes(value),
    );
  };

  const isRevertButtonDisabled = () => {
    const unnecessaryAttributes = [
      "created_at",
      "created_by",
      "updated_at",
      "updated_by",
    ];
    const sortedCurrentFieldNames = sortBy(
      removeUnnecessaryAttributes(currentFieldNames, unnecessaryAttributes),
    );
    const sortedVersionsFieldNames = sortBy(
      removeUnnecessaryAttributes(
        currentVersionFieldNames(),
        unnecessaryAttributes,
      ),
    );
    const areFieldsTheSame = isEqual(
      sortedCurrentFieldNames,
      sortedVersionsFieldNames,
    );

    return (
      isVersionCurrent() ||
      !areFieldsTheSame ||
      !isSelectVersionContainsAllCurrentRelations()
    );
  };

  const findSelectedVersionRelationValue = (name) => {
    const dataForSelectedOption = generateDataForSelectedOption();
    return dataForSelectedOption[name];
  };

  return (
    <EditViewProvider
      allowedActions={allowedActions}
      allLayoutData={allLayoutData}
      components={components}
      layout={currentContentTypeLayoutData}
      isDraggingComponent={isDraggingComponent}
      isSingleType={isSingleType}
      setIsDraggingComponent={() => {
        dispatch({
          type: "SET_IS_DRAGGING_COMPONENT",
        });
      }}
      unsetIsDraggingComponent={() => {
        dispatch({
          type: "UNSET_IS_DRAGGING_COMPONENT",
        });
      }}
    >
      <EditViewDataManagerProvider
        allLayoutData={allLayoutData}
        redirectToPreviousPage={goBack}
        isSingleType={isSingleType}
        slug={slug}
      >
        <BackHeader onClick={goBack} />
        <Container className="container-fluid">
          <Header />
          <div className="row" style={{ paddingTop: 3 }}>
            <div className="col-md-12 col-lg-9" style={{ marginBottom: 13 }}>
              {formattedContentTypeLayout.map((block, blockIndex) => {
                if (isDynamicZone(block)) {
                  const {
                    0: {
                      0: { name },
                    },
                  } = block;
                  const { max, min } = getField(name);

                  return (
                    <DynamicZone
                      key={blockIndex}
                      name={name}
                      max={max}
                      min={min}
                      dataForCurrentVersion={generateDataForSelectedOption()}
                      isVersionCurrent={isVersionCurrent()}
                    />
                  );
                }

                return (
                  <FormWrapper key={blockIndex}>
                    {block.map((fieldsBlock, fieldsBlockIndex) => {
                      return (
                        <div className="row" key={fieldsBlockIndex}>
                          {fieldsBlock.map(({ name, size }, fieldIndex) => {
                            const isComponent =
                              getFieldType(name) === "component";

                            if (isComponent) {
                              const componentUid = getFieldComponentUid(name);
                              const isRepeatable = get(
                                getField(name),
                                "repeatable",
                                false,
                              );
                              const { max, min } = getField(name);

                              const label = get(
                                getFieldMetas(name),
                                "label",
                                componentUid,
                              );

                              return (
                                <FieldComponent
                                  key={componentUid}
                                  componentUid={componentUid}
                                  isRepeatable={isRepeatable}
                                  label={label}
                                  max={max}
                                  min={min}
                                  name={name}
                                  dataForCurrentVersion={generateDataForSelectedOption()}
                                  isVersionCurrent={isVersionCurrent()}
                                />
                              );
                            }

                            return (
                              <div className={`col-${size}`} key={name}>
                                <Inputs
                                  autoFocus={
                                    blockIndex === 0 &&
                                    fieldsBlockIndex === 0 &&
                                    fieldIndex === 0
                                  }
                                  keys={name}
                                  layout={currentContentTypeLayoutData}
                                  name={name}
                                  dataForCurrentVersion={generateDataForSelectedOption()}
                                  isVersionCurrent={isVersionCurrent()}
                                />
                              </div>
                            );
                          })}
                        </div>
                      );
                    })}
                  </FormWrapper>
                );
              })}
            </div>

            <div className="col-md-12 col-lg-3">
              {currentContentTypeLayoutRelations.length > 0 && (
                <SubWrapper
                  style={{ padding: "0 20px 1px", marginBottom: "25px" }}
                >
                  <div style={{ paddingTop: "22px" }}>
                    {currentContentTypeLayoutRelations.map((relationName) => {
                      const relation = get(
                        currentContentTypeLayoutData,
                        ["schema", "attributes", relationName],
                        {},
                      );
                      const relationMetas = get(
                        currentContentTypeLayoutData,
                        ["metadatas", relationName, "edit"],
                        {},
                      );

                      return (
                        <SelectWrapper
                          {...relation}
                          {...relationMetas}
                          key={relationName}
                          name={relationName}
                          relationsType={relation.relationType}
                          valueToSet={
                            isVersionCurrent()
                              ? "current"
                              : findSelectedVersionRelationValue(relationName)
                          }
                        />
                      );
                    })}
                  </div>
                </SubWrapper>
              )}
              <LinkWrapper>
                <ul>
                  <CheckPermissions
                    permissions={
                      isSingleType
                        ? pluginPermissions.singleTypesConfigurations
                        : pluginPermissions.collectionTypesConfigurations
                    }
                  >
                    <LiLink
                      message={{
                        id: "app.links.configure-view",
                      }}
                      icon="layout"
                      key={`${pluginId}.link`}
                      url={`${
                        isSingleType ? `${pathname}/` : ""
                      }ctm-configurations/edit-settings/content-types`}
                      onClick={() => {
                        // emitEvent('willEditContentTypeLayoutFromEditView');
                      }}
                    />
                  </CheckPermissions>
                  {getInjectedComponents(
                    "editView",
                    "right.links",
                    plugins,
                    currentEnvironment,
                    slug,
                  )}
                </ul>
              </LinkWrapper>
              {entityId != "create" && (
                <div className="form-inline well">
                  <div className="form-group pr-2">
                    <label className="control-label">
                      <FormattedMessage
                        id={`${pluginId}.containers.EditView.versions`}
                      />
                    </label>
                  </div>
                  <div>
                    <Select
                      name="versionSelect"
                      onChange={({ target: { value } }) => {
                        setSelectedVersion(value);
                      }}
                      options={versions.map((el) => el.date).reverse()}
                      value={selectedVersion}
                    />
                    <Button
                      color="success"
                      type="submit"
                      disabled={isRevertButtonDisabled()}
                    >
                      <FormattedMessage
                        id={`${pluginId}.containers.EditView.revert`}
                      />
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </Container>
      </EditViewDataManagerProvider>
    </EditViewProvider>
  );
}
Example #29
Source File: helpers.js    From sampo-ui with MIT License 4 votes vote down vote up
stateToUrl = ({
  perspectiveID = null,
  facets,
  facetClass = null,
  page = null,
  pagesize = null,
  sortBy = null,
  sortDirection = null,
  resultFormat = null,
  constrainSelf = null,
  groupBy = null,
  uri = null,
  limit = null,
  optimize = null,
  fromID = null,
  toID = null,
  period = null,
  province = null
}) => {
  const params = {}
  if (perspectiveID !== null) { params.perspectiveID = perspectiveID }
  if (facetClass !== null) { params.facetClass = facetClass }
  if (page !== null) { params.page = page }
  if (pagesize !== null) { params.pagesize = parseInt(pagesize) }
  if (sortBy !== null) { params.sortBy = sortBy }
  if (sortDirection !== null) { params.sortDirection = sortDirection }
  if (resultFormat !== null) { params.resultFormat = resultFormat }
  if (constrainSelf !== null) { params.constrainSelf = constrainSelf }
  if (groupBy !== null) { params.groupBy = groupBy }
  if (uri !== null) { params.uri = uri }
  if (limit !== null) { params.limit = limit }
  if (optimize !== null) { params.optimize = optimize }
  if (fromID !== null) { params.fromID = fromID }
  if (toID !== null) { params.toID = toID }
  if (period !== null) { params.period = period }
  if (province !== null) { params.province = province }
  if (facets !== null) {
    const constraints = []
    for (const [key, value] of Object.entries(facets)) {
      if (has(value, 'uriFilter') && value.uriFilter !== null) {
        constraints.push({
          facetID: key,
          filterType: value.filterType,
          priority: value.priority,
          values: Object.keys(value.uriFilter),
          ...(Object.prototype.hasOwnProperty.call(value, 'selectAlsoSubconcepts') &&
            { selectAlsoSubconcepts: value.selectAlsoSubconcepts }),
          useConjuction: Object.prototype.hasOwnProperty.call(value, 'useConjuction')
            ? value.useConjuction
            : false
        })
      } else if (has(value, 'spatialFilter') && value.spatialFilter !== null) {
        constraints.push({
          facetID: key,
          filterType: value.filterType,
          priority: value.priority,
          values: boundsToValues(value.spatialFilter._bounds)
        })
      } else if (has(value, 'textFilter') && value.textFilter !== null) {
        constraints.push({
          facetID: key,
          filterType: value.filterType,
          priority: value.priority,
          values: value.textFilter
        })
      } else if (has(value, 'timespanFilter') && value.timespanFilter !== null) {
        constraints.push({
          facetID: key,
          filterType: value.filterType,
          priority: value.priority,
          values: value.timespanFilter
        })
      } else if (has(value, 'dateNoTimespanFilter') && value.dateNoTimespanFilter !== null) {
        constraints.push({
          facetID: key,
          filterType: value.filterType,
          priority: value.priority,
          values: value.dateNoTimespanFilter
        })
      } else if (has(value, 'integerFilter') && value.integerFilter !== null) {
        constraints.push({
          facetID: key,
          filterType: value.filterType,
          priority: value.priority,
          values: value.integerFilter
        })
      }
    }
    if (constraints.length > 0) {
      params.constraints = constraints
    }
  }
  return params
}