immutable#List TypeScript Examples

The following examples show how to use immutable#List. 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: tokens-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Converts {@link BackendToken} to {@link Token} List.
   * @param tokens Tokens from backend response.
   * @return List<Token> Useful tokens list.
   */
  public static prepareTokens(tokens: BackendToken[]): List<Token> {
    return List(
      tokens
        .map((token: BackendToken) => ({
          ...token,
          blockchain: FROM_BACKEND_BLOCKCHAINS[token.blockchainNetwork],
          price: token.usdPrice,
          usedInIframe: token.usedInIframe,
          hasDirectPair: token.hasDirectPair
        }))
        .filter(token => token.address && token.blockchain)
    );
  }
Example #2
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
shouldComponentUpdate({ notifications: newSnacks = List() }) {
    const { closeSnackbar, notifications: currentSnacks, removeSnackbar } = this.props

    if (!newSnacks.size) {
      this.displayed = []
      return false
    }
    let notExists = false
    for (let i = 0; i < newSnacks.size; i += 1) {
      const newSnack = newSnacks.get(i)

      if (newSnack.dismissed) {
        closeSnackbar(newSnack.key)
        removeSnackbar(newSnack.key)
      }

      if (notExists) {
        continue
      }
      notExists = notExists || !currentSnacks.filter(({ key }) => newSnack.key === key).size
    }
    return notExists
  }
Example #3
Source File: material-ui-custom.tsx    From ui-schema with MIT License 6 votes vote down vote up
CountrySelect: React.ComponentType<WidgetProps<MuiWidgetBinding> & WithScalarValue> = ({schema, ...props}) => {
    const [countries, setCountries] = React.useState<List<string>>(List())
    const [loading, setLoading] = useProgress()

    React.useEffect(() => {
        setLoading(PROGRESS_START)
        fetch('https://restcountries.com/v3.1/subregion/europe', {method: 'GET'})
            .then(r => r.json())
            .then(data => {
                setCountries(List(data.map((d: { name: { common: string } }) => d.name.common)))
                setLoading(PROGRESS_DONE)
            })
            .catch(() => {
                setLoading(PROGRESS_ERROR)
            })
    }, [setCountries, setLoading])

    if (loading === PROGRESS_START) {
        return <LinearProgress/>
    }

    return <Select
        {...props}
        schema={schema.set('enum', countries)}
    />
}
Example #4
Source File: tokens-api.service.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Fetches basic tokens from backend.
   */
  private fetchBasicTokens(
    tokensNetworkState$: BehaviorSubject<TokensNetworkState>
  ): Observable<List<Token>> {
    const options = { page: 1, pageSize: DEFAULT_PAGE_SIZE };
    const blockchainsToFetch = [
      BLOCKCHAIN_NAME.ETHEREUM,
      BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN,
      BLOCKCHAIN_NAME.POLYGON,
      BLOCKCHAIN_NAME.HARMONY,
      BLOCKCHAIN_NAME.AVALANCHE,
      BLOCKCHAIN_NAME.MOONRIVER,
      BLOCKCHAIN_NAME.FANTOM,
      BLOCKCHAIN_NAME.ARBITRUM,
      BLOCKCHAIN_NAME.AURORA,
      BLOCKCHAIN_NAME.SOLANA,
      BLOCKCHAIN_NAME.NEAR,
      BLOCKCHAIN_NAME.TELOS
    ].map(blockchain => TO_BACKEND_BLOCKCHAINS[blockchain]);

    const requests$ = blockchainsToFetch.map((network: FromBackendBlockchain) =>
      this.httpService.get<TokensBackendResponse>(ENDPOINTS.TOKENS, { ...options, network }).pipe(
        tap(networkTokens => {
          const blockchain = FROM_BACKEND_BLOCKCHAINS[network];
          if (networkTokens?.results) {
            tokensNetworkState$.next({
              ...tokensNetworkState$.value,
              [blockchain]: {
                ...tokensNetworkState$.value[blockchain],
                page: options.page,
                maxPage: Math.ceil(networkTokens.count / options.pageSize)
              }
            });
          }
        })
      )
    );
    return forkJoin(requests$).pipe(
      map(results => {
        const backendTokens = results.flatMap(el => el.results || []);
        return TokensApiService.prepareTokens(backendTokens);
      })
    );
  }
Example #5
Source File: collection.ts    From zebra-editor-core with MIT License 5 votes vote down vote up
children: List<T> = List();
Example #6
Source File: htmlToDraft.ts    From brilliant with MIT License 5 votes vote down vote up
function convertFromHTMLtoContentBlocks(
  html,
  processCustomInlineStyles,
  checkEntityNode,
  checkEntityText,
  checkBlockType,
  createEntity,
  getEntity,
  mergeEntityData,
  replaceEntityData,
  options,
  DOMBuilder,
  generateKey
) {
  const chunk = getChunkForHTML(
    html,
    processCustomInlineStyles,
    checkEntityNode,
    checkEntityText,
    checkBlockType,
    createEntity,
    getEntity,
    mergeEntityData,
    replaceEntityData,
    options,
    DOMBuilder
  );

  if (chunk == null) {
    return [];
  }
  let start = 0;
  return chunk.text.split('\r').map((textBlock, blockIndex) => {
    textBlock = sanitizeDraftText(textBlock);
    const end = start + textBlock.length;
    const inlines = nullthrows(chunk).inlines.slice(start, end);
    const entities = nullthrows(chunk).entities.slice(start, end);
    const characterList = List(
      inlines.map((style, entityIndex) => {
        const data = { style, entity: null };
        if (entities[entityIndex]) {
          data.entity = entities[entityIndex];
        }
        return CharacterMetadata.create(data);
      })
    );
    start = end + 1;

    return new ContentBlock({
      key: generateKey(),
      type: nullthrows(chunk).blocks[blockIndex].type,
      data: nullthrows(chunk).blocks[blockIndex].data,
      depth: nullthrows(chunk).blocks[blockIndex].depth,
      text: textBlock,
      characterList,
    });
  });
}
Example #7
Source File: index.tsx    From ui with MIT License 5 votes vote down vote up
provinces = List(_provinces)
Example #8
Source File: WYSIWYGMode.tsx    From roamjs-com with MIT License 5 votes vote down vote up
parseValue = ({
  initialValue,
  initialStart,
  initialEnd,
}: {
  initialValue: string;
  initialStart: number;
  initialEnd: number;
}) => {
  const textData = Array.from(initialValue).map((c) => ({
    c,
    styles: [] as string[],
    keep: true,
  }));
  const selection = {
    defaultSelectionStart: initialStart,
    defaultSelectionEnd: initialEnd,
  };
  const deleteIndex = (n: number) => {
    textData[n].keep = false;
    if (initialStart > n) {
      selection.defaultSelectionStart--;
    }
    if (initialEnd > n) {
      selection.defaultSelectionEnd--;
    }
  };

  const applyStyle = (matcher: string, style: string) => {
    const regex = new RegExp(matcher, "g");
    let match;
    const indices = [];
    while ((match = regex.exec(initialValue))) {
      indices.push(match.index);
    }

    const groupedIndices = indices.slice(0, Math.floor(indices.length / 2) * 2);
    for (let pointer = 0; pointer < groupedIndices.length; pointer += 2) {
      const start = groupedIndices[pointer];
      const end = groupedIndices[pointer + 1];
      for (let td = start + 2; td < end; td++) {
        textData[td].styles.push(style);
      }
      [start, start + 1, end, end + 1].forEach(deleteIndex);
    }
  };
  applyStyle("\\*\\*", "BOLD");
  applyStyle("__", "ITALIC");

  const filteredTextData = textData.filter((td) => td.keep);
  const text = filteredTextData.map((t) => t.c).join("");
  const characterList = List(
    filteredTextData.map((t) =>
      t.styles.reduce(
        (c, s) => CharacterMetadata.applyStyle(c, s),
        CharacterMetadata.create()
      )
    )
  );
  return {
    ...selection,
    defaultEditorState: EditorState.createWithContent(
      ContentState.createFromBlockArray([
        new ContentBlock({
          characterList,
          type: "paragraph",
          text,
          key: genKey(),
        }),
      ])
    ),
  };
}
Example #9
Source File: validator.ts    From multisig-react with MIT License 5 votes vote down vote up
uniqueAddress = (addresses: string[] | List<string> = []) => (address?: string): string | undefined => {
  const addressExists = addresses.some((addressFromList) => sameAddress(addressFromList, address))
  return addressExists ? ADDRESS_REPEATED_ERROR : undefined
}