ramda#cond JavaScript Examples

The following examples show how to use ramda#cond. 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: index.js    From web with GNU General Public License v3.0 6 votes vote down vote up
callBridgeDataHandler = cond([
  [equals(DATA_TYPE.NATIVE_SERVICES_STATUS), always(handleServicesStatus)],
  [equals(DATA_TYPE.HISTORICAL_DATA), always(handleUploadHistoricalDataResponse)],
  [equals(DATA_TYPE.EXPOSURE_STATISTICS), always(handleExposureSummary)],
  [equals(DATA_TYPE.NATIVE_STATE), always(handleNativeState)],
  [equals(DATA_TYPE.LANGUAGE), always(handleNativeLanguage)],
  [equals(DATA_TYPE.LAB_TEST_SUBSCRIPTION), always(handleLabTestSubscription)],
  [equals(DATA_TYPE.BACK_PRESSED), always(handleBackPressed)],
  [equals(DATA_TYPE.CHANGE_SCREEN), always(handleChangeScreen)],
  [equals(DATA_TYPE.SUMMARY_STATISTICS), always(handleNewSummaryStatistics)],
  [equals(DATA_TYPE.DETAILS_STATISTICS), always(handleNewDetailsStatistics)]
])
Example #2
Source File: processOrderBookSnapshot.js    From binance-websocket-examples with MIT License 6 votes vote down vote up
processOrderBookSnapshot = (orderBookData, snapshotOrderbook) => {
  const { lastUpdateId, bids, asks } = snapshotOrderbook;

  // clean the order that is out of date
  const cleanOutOfDateOrder = (order) => order[2] > lastUpdateId;
  orderBookData.bid = filter(cleanOutOfDateOrder, orderBookData.bid);
  orderBookData.ask = filter(cleanOutOfDateOrder, orderBookData.ask);

  // append the updateId into snapshotOrderbook
  const snapshotOrders = appendUpdatedId(lastUpdateId, asks, bids);
  const compareValueFn = cond([
    [equals('ask'), () => (a, b) => (new Big(a[0])).minus(b[0])],
    [equals('bid'), () => (a, b) => (new Big(b[0])).minus(a[0])],
  ]);

  const validateValue = (v) => Big(v[0]);
  orderBookData.bid = uniqBy(validateValue, [...snapshotOrders[1], ...orderBookData.bid])
    .sort(compareValueFn('bid'), orderBookData.bid);

  orderBookData.ask = uniqBy(validateValue, [...snapshotOrders[0], ...orderBookData.ask])
    .sort(compareValueFn('ask'), orderBookData.ask);


  return orderBookData;
}
Example #3
Source File: processOrderBookUpdate.js    From binance-websocket-examples with MIT License 6 votes vote down vote up
processOrderBookUpdate = (data, bid, ask) => {
  const validateValue = (v) => Big(v[0]);
  const compareValueFn = cond([
    [equals('ask'), () => (a, b) => (new Big(a[0])).minus(b[0])],
    [equals('bid'), () => (a, b) => (new Big(b[0])).minus(a[0])],
  ]);
  const purgeEmptyVolume = (v) => Big(v[1]).gt(0);

  data.bid = uniqBy(validateValue, [...bid, ...data.bid])
    .sort(compareValueFn('bid'), data.bid)
    .filter(purgeEmptyVolume, data.bid);

  data.ask = uniqBy(validateValue, [...ask, ...data.ask])
    .sort(compareValueFn('ask'), data.ask)
    .filter(purgeEmptyVolume, data.ask);
  return data;
}
Example #4
Source File: Accordion.js    From lundium with MIT License 6 votes vote down vote up
Accordion = forwardRef(({ openItemIndex, className, children }, ref) => {
	const [indexOpen, setIndexOpen] = useState(openItemIndex);

	useEffect(() => {
		if (!isNaN(openItemIndex)) {
			setIndexOpen(openItemIndex);
		}
	}, [openItemIndex]);

	useImperativeHandle(ref, () => ({ setActiveIndex: setIndexOpen }));

	return (
		<Box className={cx('accordion', className)}>
			{Children.map(children, (child, index) =>
				cond([
					[
						o(equals(AccordionItem), prop('type')),
						clone({ index, indexOpen, setIndexOpen }),
					],
					[T, identity],
				])(child),
			)}
		</Box>
	);
})
Example #5
Source File: HistoryActivitiesItem.helpers.js    From web with GNU General Public License v3.0 5 votes vote down vote up
resolveDatas = (content, riskChecks, riskLevel, title, type) => {
  const resoleRiskLevel = cond([
    [
      equals(1),
      always({
        title: <T i18nKey="history_notifications_text_10" />,
        content: <T i18nKey="history_notifications_text_14" />
      })
    ],
    [
      equals(2),
      always({
        title: <T i18nKey="history_notifications_text_9" />,
        content: <T i18nKey="history_notifications_text_13" />
      })
    ],
    [
      equals(3),
      always({
        title: <T i18nKey="history_notifications_text_8" />,
        content: <T i18nKey="history_notifications_text_12" />
      })
    ]
  ]);

  switch (type) {
    case TYPE.NOTIFICATION: {
      return { icon: <Icon3 />, content, title };
    }
    case TYPE.RISK_CHECK: {
      return {
        content: <ContentRiskCheck data={riskChecks} />,
        icon: <Icon2 />,
        title: <T i18nKey="history_notifications_text_11" />
      };
    }
    case TYPE.EXPOSURE: {
      return { icon: <Icon1 />, ...resoleRiskLevel(riskLevel) };
    }
    default: {
      return null;
    }
  }
}
Example #6
Source File: Notification.js    From lundium with MIT License 5 votes vote down vote up
getIcon = cond([
	[equals('danger'), always('status-rejected')],
	[equals('warning'), always('error')],
	[T, identity],
])
Example #7
Source File: classNamesByBreakpoint.js    From lundium with MIT License 5 votes vote down vote up
prepareBreakpointArray = cond([
	[isNilOrEmpty, alwaysEmptyArray],
	[isPlainObject, prepareBreakpointArrayFromObject],
	[isArray, identity],
	[T, of],
])
Example #8
Source File: checkArbitratorAnswers.js    From cross-chain-realitio-proxy with MIT License 4 votes vote down vote up
export default async function checkArbitratorAnswers({ homeChainApi }) {
  const chainId = await homeChainApi.getChainId();

  await checkUntrackedArbitratorAnswers();
  await checkCurrentArbitratorAnswers();

  async function checkUntrackedArbitratorAnswers() {
    const [fromBlock, toBlock] = await P.all([getBlockHeight("RULED_REQUESTS"), homeChainApi.getBlockNumber()]);

    const untrackedNotifiedRequests = filter(
      ({ status }) => [Status.AwaitingRuling, Status.Ruled].includes(status),
      await homeChainApi.getNotifiedRequests({ fromBlock, toBlock })
    );

    await saveRequests(untrackedNotifiedRequests);

    const blockHeight = toBlock + 1;
    await updateBlockHeight({ key: "RULED_REQUESTS", blockHeight });
    console.info({ blockHeight }, "Set RULED_REQUESTS block height");

    const stats = {
      data: map(pick(["questionId", "chainId"]), untrackedNotifiedRequests),
      fromBlock,
      toBlock,
    };

    console.info(stats, "Found new requests with arbitrator answers");

    return stats;
  }

  async function checkCurrentArbitratorAnswers() {
    const requestFinishedOrCanceled = ([_, onChainRequest]) =>
      [Status.None, Status.Finished].includes(onChainRequest.status);
    const removeOffChainRequest = asyncPipe([
      mergeOnChainOntoOffChain,
      removeRequest,
      (request) => ({
        action: "OFF_CHAIN_REQUEST_REMOVED",
        payload: request,
      }),
    ]);

    const requestRuled = ([_, onChainArbitration]) => onChainArbitration.status === Status.Ruled;
    const reportArbitrationAnswer = asyncPipe([
      mergeOnChainOntoOffChain,
      homeChainApi.reportArbitrationAnswer,
      (request) => ({
        action: "ARBITRATION_ANSWER_REPORTED",
        payload: request,
      }),
    ]);

    const noop = asyncPipe([
      mergeOnChainOntoOffChain,
      (arbtration) => ({
        action: "NO_OP",
        payload: arbtration,
      }),
    ]);

    const requestsWithRuling = await fetchRequestsByChainId({ status: Status.Ruled, chainId });

    console.info(
      { data: map(pick(["questionId", "requester"]), requestsWithRuling) },
      "Fetched requests which received the arbitration ruling"
    );

    const pipeline = asyncPipe([
      fetchOnChainCounterpart,
      cond([
        [requestFinishedOrCanceled, removeOffChainRequest],
        [requestRuled, reportArbitrationAnswer],
        [() => true, noop],
      ]),
    ]);

    const results = await P.allSettled(map(pipeline, requestsWithRuling));

    const groupQuestionsOrErrorMessage = (acc, r) => {
      if (r.status === "rejected") {
        return [...acc, r.reason?.message];
      }

      const questionId = r.value?.payload?.questionId ?? "<not set>";
      const requester = r.value?.payload?.requester ?? "<not set>";
      return [...acc, { questionId, requester }];
    };
    const toTag = (r) => (r.status === "rejected" ? "FAILURE" : r.value?.action);
    const stats = reduceBy(groupQuestionsOrErrorMessage, [], toTag, results);

    console.info(stats, "Processed requests with ruling");
  }

  async function fetchOnChainCounterpart(offChainRequest) {
    const { questionId, requester } = offChainRequest;

    const onChainRequest = await homeChainApi.getRequest({ questionId, requester });

    return [offChainRequest, onChainRequest];
  }
}
Example #9
Source File: checkNotifiedRequests.js    From cross-chain-realitio-proxy with MIT License 4 votes vote down vote up
export default async function checkNotifiedRequests({ homeChainApi }) {
  const chainId = await homeChainApi.getChainId();

  await checkUntrackedNotifiedRequests();
  await checkCurrentNotifiedRequests();

  async function checkUntrackedNotifiedRequests() {
    const [fromBlock, toBlock] = await P.all([getBlockHeight("NOTIFIED_REQUESTS"), homeChainApi.getBlockNumber()]);

    const untrackedNotifiedRequests = filter(
      ({ status }) => status !== Status.None,
      await homeChainApi.getNotifiedRequests({ fromBlock, toBlock })
    );

    await saveRequests(untrackedNotifiedRequests);

    const blockHeight = toBlock + 1;
    await updateBlockHeight({ key: "NOTIFIED_REQUESTS", blockHeight });
    console.info({ blockHeight }, "Set NOTIFIED_REQUESTS block height");

    const stats = {
      data: map(pick(["questionId", "chainId", "status"]), untrackedNotifiedRequests),
      fromBlock,
      toBlock,
    };

    console.info(stats, "Found new notified arbitration requests");

    return stats;
  }

  async function checkCurrentNotifiedRequests() {
    const requestNotified = ([_, onChainArbitration]) => onChainArbitration.status === Status.Notified;
    const handleNotifiedRequest = asyncPipe([
      mergeOnChainOntoOffChain,
      homeChainApi.handleNotifiedRequest,
      (request) => ({
        action: "NOTIFIED_REQUEST_HANDLED",
        payload: request,
      }),
    ]);

    const requestStatusChanged = ([offChainRequest, onChainRequest]) => offChainRequest.status != onChainRequest.status;
    const updateOffChainRequest = asyncPipe([
      mergeOnChainOntoOffChain,
      updateRequest,
      (request) => ({
        action: "STATUS_CHANGED",
        payload: request,
      }),
    ]);

    const noop = asyncPipe([
      mergeOnChainOntoOffChain,
      (request) => ({
        action: "NO_OP",
        payload: request,
      }),
    ]);

    const pipeline = asyncPipe([
      fetchOnChainCounterpart,
      cond([
        [requestNotified, handleNotifiedRequest],
        [requestStatusChanged, updateOffChainRequest],
        [() => true, noop],
      ]),
    ]);

    const notifiedRequests = await fetchRequestsByChainIdAndStatus({ status: Status.Notified, chainId });

    console.info({ data: map(pick(["questionId", "requester"]), notifiedRequests) }, "Fetched notified requests");

    const results = await P.allSettled(map(pipeline, notifiedRequests));

    const groupQuestionsOrErrorMessage = (acc, r) => {
      if (r.status === "rejected") {
        return [...acc, r.reason?.message];
      }

      const questionId = r.value?.payload?.questionId ?? "<not set>";
      const requester = r.value?.payload?.requester ?? "<not set>";
      return [...acc, { questionId, requester }];
    };
    const toTag = (r) => (r.status === "rejected" ? "FAILURE" : r.value?.action);
    const stats = reduceBy(groupQuestionsOrErrorMessage, [], toTag, results);

    console.info(stats, "Processed notified requests");

    return stats;
  }

  async function fetchOnChainCounterpart(offChainRequest) {
    const { questionId, requester } = offChainRequest;

    const onChainRequest = await homeChainApi.getRequest({ questionId, requester });

    return [offChainRequest, onChainRequest];
  }
}
Example #10
Source File: checkRejectedRequests.js    From cross-chain-realitio-proxy with MIT License 4 votes vote down vote up
export default async function checkRejectedRequests({ homeChainApi }) {
  const chainId = await homeChainApi.getChainId();

  await checkUntrackedRejectedRequests();
  await checkCurrentRejectedRequests();

  async function checkUntrackedRejectedRequests() {
    const [fromBlock, toBlock] = await Promise.all([
      getBlockHeight("REJECTED_REQUESTS"),
      homeChainApi.getBlockNumber(),
    ]);

    const untrackedRejectedRequests = filter(
      ({ status }) => status === Status.Rejected,
      await homeChainApi.getRejectedRequests({ fromBlock, toBlock })
    );

    await saveRequests(untrackedRejectedRequests);

    const blockHeight = toBlock + 1;
    await updateBlockHeight({ key: "REJECTED_REQUESTS", blockHeight });
    console.info({ blockHeight }, "Set REJECTED_REQUESTS block height");

    const stats = {
      data: map(pick(["questionId", "requester"]), untrackedRejectedRequests),
      fromBlock,
      toBlock,
    };

    console.info(stats, "Found new rejected arbitration requests");

    return stats;
  }

  async function checkCurrentRejectedRequests() {
    const requestRemoved = ([_, onChainArbitration]) => onChainArbitration.status === Status.None;
    const removeOffChainRequest = asyncPipe([
      mergeOnChainOntoOffChain,
      removeRequest,
      (arbitration) => ({
        action: "REQUEST_REMOVED",
        payload: arbitration,
      }),
    ]);

    const requestRejected = ([_, onChainArbitration]) => onChainArbitration.status === Status.Rejected;
    const handleRejectedRequest = asyncPipe([
      mergeOnChainOntoOffChain,
      homeChainApi.handleRejectedRequest,
      (request) => ({
        action: "REJECTED_REQUEST_HANDLED",
        payload: request,
      }),
    ]);

    const noop = asyncPipe([
      mergeOnChainOntoOffChain,
      (request) => ({
        action: "NO_OP",
        payload: request,
      }),
    ]);

    const pipeline = asyncPipe([
      fetchOnChainCounterpart,
      cond([
        [requestRemoved, removeOffChainRequest],
        [requestRejected, handleRejectedRequest],
        [() => true, noop],
      ]),
    ]);

    const rejectedRequests = await fetchRequestsByChainIdAndStatus({ chainId, status: Status.Rejected });

    console.info({ data: map(pick(["questionId", "requester"]), rejectedRequests) }, "Fetched rejected requests");

    const results = await P.allSettled(map(pipeline, rejectedRequests));

    const groupQuestionsOrErrorMessage = (acc, r) => {
      if (r.status === "rejected") {
        return [...acc, r.reason?.message];
      }

      const questionId = r.value?.payload?.questionId ?? "<not set>";
      const requester = r.value?.payload?.requester ?? "<not set>";
      return [...acc, { questionId, requester }];
    };
    const toTag = (r) => (r.status === "rejected" ? "FAILURE" : r.value?.action);
    const stats = reduceBy(groupQuestionsOrErrorMessage, [], toTag, results);

    console.info(stats, "Processed rejected requests");

    return stats;
  }

  async function fetchOnChainCounterpart(offChainRequest) {
    const { questionId, requester } = offChainRequest;

    const onChainRequest = await homeChainApi.getRequest({ questionId, requester });

    return [offChainRequest, onChainRequest];
  }
}
Example #11
Source File: checkRequestedArbitrations.js    From cross-chain-realitio-proxy with MIT License 4 votes vote down vote up
export default async function checkRequestedArbitrations({ foreignChainApi }) {
  const chainId = await foreignChainApi.getChainId();

  await checkUntrackedArbitrationRequests();
  await processArbitrationRequests();

  async function checkUntrackedArbitrationRequests() {
    const [fromBlock, toBlock] = await P.all([
      getBlockHeight("ACCEPTED_ARBITRATION_REQUESTS"),
      foreignChainApi.getBlockNumber(),
    ]);

    const untrackedArbitrationRequests = filter(
      ({ status }) => status !== status.None,
      await foreignChainApi.getRequestedArbitrations({ fromBlock, toBlock })
    );

    await saveRequests(untrackedArbitrationRequests);

    const blockHeight = toBlock + 1;
    await updateBlockHeight({ key: "ACCEPTED_ARBITRATION_REQUESTS", blockHeight });
    console.info({ blockHeight }, "Set ACCEPTED_ARBITRATION_REQUESTS block height");

    const stats = {
      data: map(pick(["questionId", "requester", "chainId", "status"]), untrackedArbitrationRequests),
      fromBlock,
      toBlock,
    };

    console.info(stats, "Found new notified arbitration requests");

    return stats;
  }

  async function processArbitrationRequests() {
    const requestRemovedOrRuled = ([_, onChainArbitration]) =>
      [Status.None, Status.Ruled].includes(onChainArbitration.status);
    const removeOffChainRequest = asyncPipe([
      mergeOnChainOntoOffChain,
      removeRequest,
      (arbitration) => ({
        action: "ARBITRATION_REQUEST_REMOVED",
        payload: arbitration,
      }),
    ]);

    const disputeCreationFailed = ([_, onChainArbitration]) => onChainArbitration.status === Status.Failed;
    const handleFailedDisputeCreation = asyncPipe([
      mergeOnChainOntoOffChain,
      foreignChainApi.handleFailedDisputeCreation,
      (arbitration) => ({
        action: "FAILED_DISPUTE_CREATION_HANDLED",
        payload: arbitration,
      }),
    ]);

    const requestStatusChanged = ([offChainArbitration, onChainArbitration]) =>
      offChainArbitration.status != onChainArbitration.status;
    const updateOffChainRequest = asyncPipe([
      mergeOnChainOntoOffChain,
      updateRequest,
      (arbitration) => ({
        action: "STATUS_CHANGED",
        payload: arbitration,
      }),
    ]);

    const noop = asyncPipe([
      mergeOnChainOntoOffChain,
      (arbtration) => ({
        action: "NO_OP",
        payload: arbtration,
      }),
    ]);

    const pipeline = asyncPipe([
      fetchOnChainCounterpart,
      cond([
        [requestRemovedOrRuled, removeOffChainRequest],
        [disputeCreationFailed, handleFailedDisputeCreation],
        [requestStatusChanged, updateOffChainRequest],
        [() => true, noop],
      ]),
    ]);

    const requestedArbitrations = await fetchRequestsByChainId({ chainId });

    console.info(
      { data: map(pick(["questionId", "requester"]), requestedArbitrations) },
      "Fetched requested arbitrations"
    );

    const results = await P.allSettled(map(pipeline, requestedArbitrations));

    const groupQuestionsOrErrorMessage = (acc, r) => {
      if (r.status === "rejected") {
        return [...acc, r.reason?.message];
      }

      const questionId = r.value?.payload?.questionId ?? "<not set>";
      const requester = r.value?.payload?.requester ?? "<not set>";
      return [...acc, { questionId, requester }];
    };
    const toTag = (r) => (r.status === "rejected" ? "FAILURE" : r.value?.action);
    const stats = reduceBy(groupQuestionsOrErrorMessage, [], toTag, results);

    console.info(stats, "Processed requested arbitrations");

    return stats;
  }

  async function fetchOnChainCounterpart(offChainArbitration) {
    const { questionId, requester } = offChainArbitration;

    const onChainArbitration = await foreignChainApi.getArbitrationRequest({ questionId, requester });

    return [offChainArbitration, onChainArbitration];
  }
}