ramda#keys JavaScript Examples

The following examples show how to use ramda#keys. 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: staking_payouts.js    From sdk with MIT License 4 votes vote down vote up
/**
 * Sends staking payouts for recent eras using the given sender account.
 *
 * @param {DockAPI} dock
 * @param {ErasInfo} erasInfo
 * @param {*} initiator - account to send tx from
 * @param {number} batchSize
 * @returns {Promise<boolean>} - `true` if some unpaid eras were found, `false` otherwise
 */
async function sendStakingPayouts(dock, erasInfo, initiator, batchSize) {
  const validators = pipe(
    values,
    pluck("validators"),
    chain(keys),
    (values) => new Set(values)
  )(erasInfo.pointsByEra);

  if (!validators.size) {
    console.log("- Validator set is empty.");
    return false;
  }

  console.log("- Retrieving validator eras...");
  const erasToBePaid = await lastValueFrom(
    from(validators).pipe(
      getUnclaimedStashesEras(dock.api, erasInfo),
      toArray()
    )
  );

  const rewards = pipe(buildValidatorRewards, toPairs)(erasInfo, erasToBePaid);

  if (isEmpty(rewards)) {
    console.log("- No unpaid validator rewards found for recent eras.");
    return false;
  }

  console.log("- Payouts need to be made:");

  for (const [stashId, eras] of rewards) {
    const total = eras.reduce(
      (total, { reward }) => (total != null ? total.add(reward) : reward),
      null
    );

    console.log(` * To \`${stashId}\`: ${formatDock(total)}`);
  }

  const logResult = ({ result, tx }) => {
    // Ther's a much better way to check this...
    const isBatch = tx.method.args?.[0]?.[0] instanceof Map;

    let msg = " * ";
    if (isBatch) msg += `Batch transaction`;
    else msg += `Transaction`;

    if (FinalizeTx) {
      msg += ` finalized at block \`${result.status.asFinalized}\`: `;
    } else {
      msg += ` included at block \`${result.status.asInBlock}\`: `;
    }

    const payoutsSummary = (isBatch ? tx.method.args[0] : [tx.method])
      .map((payout) => payout.get("args"))
      .map(
        ({ validator_stash, era }) =>
          `\`${validator_stash}\` rewarded for era ${era}`
      )
      .join(isBatch ? ",\n    " : ",");

    msg += isBatch ? `[\n    ${payoutsSummary}\n ]` : payoutsSummary;

    console.log(msg);
  };

  const payoutTxs$ = from(rewards).pipe(
    concatMap(([stashId, eras]) => from(eras.map(assoc("stashId", stashId)))),
    mapRx(({ stashId, era }) =>
      dock.api.tx.staking.payoutStakers(stashId, era)
    ),
    batchExtrinsics(dock.api, batchSize),
    signAndSendExtrinsics(dock, initiator),
    tap(logResult)
  );

  await new Promise((resolve, reject) =>
    payoutTxs$.subscribe({
      error: reject,
      complete: resolve,
    })
  );

  return true;
}
Example #2
Source File: osk-detector.js    From on-screen-keyboard-detector with MIT License 4 votes vote down vote up
/**
 *
 * @param {function(String)} userCallback
 * @return {function(): void}
 */
// initWithCallback :: (String -> *) -> (... -> undefined)
function initWithCallback(userCallback) {
	if(isIOS) {
		return subscribeOnIOS(userCallback);
	}
	
	const
		INPUT_ELEMENT_FOCUS_JUMP_DELAY = 700,
		SCREEN_ORIENTATION_TO_WINDOW_RESIZE_DELAY = 700,
		RESIZE_QUIET_PERIOD = 500,
		LAYOUT_RESIZE_TO_LAYOUT_HEIGHT_FIX_DELAY =
			Math.max(INPUT_ELEMENT_FOCUS_JUMP_DELAY, SCREEN_ORIENTATION_TO_WINDOW_RESIZE_DELAY) - RESIZE_QUIET_PERIOD + 200,
		
		[ induceUnsubscribe, userUnsubscription ] = createAdapter(),
		scheduler = newDefaultScheduler(),
		
		// assumes initially hidden OSK
		initialLayoutHeight = window.innerHeight,
		// assumes initially hidden OSK
		approximateBrowserToolbarHeight = screen.availHeight - window.innerHeight,
		// Implementation note:
		// On Chrome window.outerHeight changes together with window.innerHeight
		// They seem to be always equal to each other.
		
		focus =
			merge(focusin(document.documentElement), focusout(document.documentElement)),
		
		documentVisibility =
			applyTo(domEvent('visibilitychange', document))(pipe(
				map(() => document.visibilityState),
				startWith(document.visibilityState)
			)),
		
		isUnfocused =
			applyTo(focus)(pipe(
				map(evt =>
					evt.type === 'focusin' ? now(false) : at(INPUT_ELEMENT_FOCUS_JUMP_DELAY, true)
				),
				switchLatest,
				startWith(!isAnyElementActive()),
				skipRepeats,
				multicast
			)),
		
		layoutHeightOnOSKFreeOrientationChange =
			applyTo(change(screen.orientation))(pipe(
				// The 'change' event hits very early BEFORE window.innerHeight is updated (e.g. on "resize")
				snapshot(
					unfocused => unfocused || (window.innerHeight === initialLayoutHeight),
					isUnfocused
				),
				debounce(SCREEN_ORIENTATION_TO_WINDOW_RESIZE_DELAY),
				map(isOSKFree => ({
					screenOrientation: getScreenOrientationType(),
					height: isOSKFree ? window.innerHeight : screen.availHeight - approximateBrowserToolbarHeight
				}))
			)),
		
		layoutHeightOnUnfocus =
			applyTo(isUnfocused)(pipe(
				filter(identical(true)),
				map(() => ({screenOrientation: getScreenOrientationType(), height: window.innerHeight}))
			)),
		
		// Difficulties: The exact layout height in the perpendicular orientation is only to determine on orientation change,
		// Orientation change can happen:
		// - entirely unfocused,
		// - focused but w/o OSK, or
		// - with OSK.
		// Thus on arriving in the new orientation, until complete unfocus, it is uncertain what the current window.innerHeight value means
		
		// Solution?: Assume initially hidden OSK (even if any input has the "autofocus" attribute),
		// and initialize other dimension with screen.availWidth
		// so there can always be made a decision on the keyboard.
		layoutHeights =
			// Ignores source streams while documentVisibility is 'hidden'
			// sadly visibilitychange comes 1 sec after focusout!
			applyTo(mergeArray([layoutHeightOnUnfocus, layoutHeightOnOSKFreeOrientationChange]))(pipe(
				delay(1000),
				rejectCapture(map(equals("hidden"), documentVisibility)),
				scan(
					(accHeights, {screenOrientation, height}) =>
						assoc(screenOrientation, height, accHeights),
					{
						[getScreenOrientationType()]: window.innerHeight
					}
				),
				skipAfter(compose(isEmpty, difference(['portrait', 'landscape']), keys))
			)),
		
		layoutHeightOnVerticalResize =
			applyTo(resize(window))(pipe(
				debounce(RESIZE_QUIET_PERIOD),
				map(evt => ({ width: evt.target.innerWidth, height: evt.target.innerHeight})),
				scan(
					(prev, size) =>
						({
							...size,
							isJustHeightResize: prev.width === size.width,
							dH: size.height - prev.height
						}),
					{
						width: window.innerWidth,
						height: window.innerHeight,
						isJustHeightResize: false,
						dH: 0
					}
				),
				filter(propEq('isJustHeightResize', true))
			)),
		
		osk =
			applyTo(layoutHeightOnVerticalResize)(pipe(
				delay(LAYOUT_RESIZE_TO_LAYOUT_HEIGHT_FIX_DELAY),
				snapshot(
					(layoutHeightByOrientation, {height, dH}) => {
						const
							nonOSKLayoutHeight = layoutHeightByOrientation[getScreenOrientationType()];
						
						if (!nonOSKLayoutHeight) {
							return (dH > 0.1 * screen.availHeight) ? now("hidden")
								: (dH < -0.1 * screen.availHeight) ? now("visible")
									: empty();
						}
						
						return (height < 0.9 * nonOSKLayoutHeight) && (dH < 0) ? now("visible")
							: (height === nonOSKLayoutHeight) && (dH > 0) ? now("hidden")
							: empty();
					},
					layoutHeights
				),
				join,
				merge(applyTo(isUnfocused)(pipe(
					filter(identical(true)),
					map(always("hidden"))
				))),
				until(userUnsubscription),
				skipRepeats
			));
	
	runEffects(tap(userCallback, osk), scheduler);
	
	return induceUnsubscribe;
}