ramda#curry JavaScript Examples

The following examples show how to use ramda#curry. 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 sdk with MIT License 6 votes vote down vote up
parseEnv = curry((parse, name) => {
  const value = ownProp(name, process.env);

  try {
    return parse(value);
  } catch (e) {
    throw new Error(`Failed to parse \`${name}\`: ${e}`);
  }
})
Example #2
Source File: index.js    From cross-chain-realitio-proxy with MIT License 6 votes vote down vote up
buildGenericConditionExpression = curry(function _buildGenericConditionExpression(exprAttr, obj) {
  const buildDescriptors = compose(
    map(([key, value]) => ({
      expr: `#${key} = :${key}`,
      name: { [`#${key}`]: key },
      value: { [`:${key}`]: value },
    })),
    toPairs
  );
  const descriptors = buildDescriptors(obj);

  const buildExpression = compose(join(" and "), pluck("expr"));
  const buildAttrNames = compose(mergeAll, pluck("name"));
  const buildAttrValues = compose(mergeAll, pluck("value"));

  const expression = buildExpression(descriptors);
  const attrNames = buildAttrNames(descriptors);
  const attrValues = buildAttrValues(descriptors);

  return {
    [exprAttr]: expression,
    ExpressionAttributeNames: attrNames,
    ExpressionAttributeValues: attrValues,
  };
})
Example #3
Source File: index.js    From cross-chain-realitio-proxy with MIT License 6 votes vote down vote up
export function createEnhancedClient() {
  const params = process.env.IS_LOCAL
    ? {
        region: "localhost",
        endpoint: "http://localhost:8000",
      }
    : {};

  const client = new DynamoDB.DocumentClient(params);

  const writeSingleBatch = curry(function _writeSingleBatch(tableName, batch) {
    return client
      .batchWrite({
        RequestItems: {
          [tableName]: batch,
        },
      })
      .promise();
  });

  const writeAllBatches = function _writeAllBatches(tableName, items) {
    return compose(map(writeSingleBatch(tableName)), splitBatches)(items);
  };

  const batchWrite = curry(async function _batchWrite(tableName, items) {
    return flatten(await P.all(writeAllBatches(tableName, items)));
  });

  return {
    client,
    batchWrite,
  };
}
Example #4
Source File: staking_payouts.js    From sdk with MIT License 6 votes vote down vote up
signAndSendExtrinsics = curry((dock, initiator, txs$) => {
  // The first nonce to be used will come from the API call
  // To send several extrinsics simultaneously, we need to emulate increasing nonce
  return from(dock.api.rpc.system.accountNextIndex(initiator.address)).pipe(
    switchMap((nonce) => {
      const sendExtrinsic = (tx) =>
        defer(() => {
          dock.setAccount(initiator);
          const sentTx = dock.signAndSend(tx, FinalizeTx, { nonce });
          // Increase nonce by hand
          nonce = nonce.add(new BN(1));

          return from(timeout(TxFinalizationTimeout, sentTx));
        }).pipe(
          mapRx((result) => ({ tx, result })),
          catchError((error, caught) => {
            console.error(` * Transaction failed: ${error}`);
            const stringified = error.toString().toLowerCase();

            // Filter out errors related to balance and double-claim
            if (
              stringified.includes("balance") ||
              stringified.includes("alreadyclaimed") ||
              stringified.includes("invalid transaction") ||
              stringified.includes("election")
            ) {
              return EMPTY;
            } else {
              // Retry an observable after the given timeout
              return timer(RetryTimeout).pipe(concatMapTo(caught));
            }
          })
        );

      return txs$.pipe(mergeMap(sendExtrinsic, ConcurrentTxLimit));
    })
  );
})
Example #5
Source File: staking_payouts.js    From sdk with MIT License 6 votes vote down vote up
getUnclaimedStashesEras = curry((api, { eras }, stashIds$) =>
  // Concurrently get unclaimed eras for each of stashes
  stashIds$.pipe(
    mergeMap(
      (stashId) =>
        from(getUnclaimedStashEras(api, eras, stashId)).pipe(
          // Filter out stashes with no unclaimed eras
          filterRx(complement(isEmpty)),
          mapRx(assoc("eras", __, { stashId }))
        ),
      ConcurrentRequestsLimit
    )
  )
)
Example #6
Source File: staking_payouts.js    From sdk with MIT License 6 votes vote down vote up
getUnclaimedStashEras = curry(async (api, allEras, stashId) => {
  let controllerId = await api.query.staking.bonded(stashId);
  if (controllerId.isNone) {
    return [];
  } else {
    controllerId = controllerId.unwrap();
  }

  const ledger = (
    await api.query.staking.ledger(controllerId)
  ).unwrapOrDefault();

  return differenceWith((a, b) => a.eq(b), allEras, ledger.claimedRewards);
})
Example #7
Source File: helpers.js    From sdk with MIT License 6 votes vote down vote up
withDockAPI = curry((params, fn) => async (...args) => {
  console.log("Connecting...");
  let err, res;

  try {
    await dock.init(params);
    res = await fn(dock, ...args);
  } catch (e) {
    err = e;
  } finally {
    console.log("Disconnecting...");
    await dock.disconnect();

    if (err) {
      throw err;
    } else {
      return res;
    }
  }
})
Example #8
Source File: email_utils.js    From sdk with MIT License 6 votes vote down vote up
sendAlarmEmail = curry(async (toAddr, subject, body) => {
  const {
    AWS_ACCESS_KEY_ID,
    AWS_SECRET_ACCESS_KEY,
    AWS_SESSION_TOKEN,
    AWS_REGION,
  } = envObj({
    AWS_ACCESS_KEY_ID: notNilAnd(String),
    AWS_SECRET_ACCESS_KEY: notNilAnd(String),
    AWS_SESSION_TOKEN: notNilAnd(String),
    AWS_REGION: notNilAnd(String),
  });

  const ses = new SESV2({
    apiVersion: "2019-09-27",
    accessKeyId: AWS_ACCESS_KEY_ID,
    secretAccessKey: AWS_SECRET_ACCESS_KEY,
    sessionToken: AWS_SESSION_TOKEN,
    region: AWS_REGION,
  });

  toAddr = Array.isArray(toAddr) ? toAddr : [toAddr];

  const params = {
    Destination: {
      ToAddresses: toAddr,
    },
    Content: {
      Simple: {
        Body: {
          Text: {
            Data: body,
            Charset: "UTF-8",
          },
        },
        Subject: {
          Data: subject,
          Charset: "UTF-8",
        },
      },
    },
    FromEmailAddress: toAddr[0],
  };

  const res = await ses.sendEmail(params).promise();
  console.log("Email sent.");
  console.log(res);

  return res;
})
Example #9
Source File: helpers.js    From sdk with MIT License 5 votes vote down vote up
timeout = curry((time, promise) =>
  Promise.race([rejectTimeout(time), promise])
)
Example #10
Source File: staking_payouts.js    From sdk with MIT License 5 votes vote down vote up
buildValidatorRewards = curry(
  ({ pointsByEra, rewardsByEra, prefsByEra }, validatorEras) => {
    const stashErasReducer = (acc, { eras, stashId }) => {
      const eraReducer = (acc, era) => {
        const eraKey = era.toString();
        const eraPoints = pointsByEra[eraKey];
        const eraRewards = rewardsByEra[eraKey];
        const eraPrefs = prefsByEra[eraKey];

        if (
          // Points must be greater than 0
          eraPoints?.eraPoints.gt(new BN(0)) &&
          // We must have a stash as a validator in the given era
          eraPoints?.validators[stashId] &&
          // Era rewards should be defined
          eraRewards &&
          // Validator commission in the given era should be acceptable
          eraPrefs.validators[stashId]?.commission?.toBn().lte(MaxCommission)
        ) {
          const reward = eraPoints.validators[stashId]
            .mul(eraRewards.eraReward)
            .div(eraPoints.eraPoints);

          if (!reward.isZero())
            return acc.concat({
              era,
              reward,
            });
        }

        return acc;
      };

      return eras.reduce(eraReducer, acc);
    };

    return o(
      // Filter out stashes with no rewards
      reject(isEmpty),
      // Reduce given stash eras by the stash id
      reduceBy(stashErasReducer, [], prop("stashId"))
    )(validatorEras);
  }
)
Example #11
Source File: helpers.js    From sdk with MIT License 5 votes vote down vote up
batchExtrinsics = curry((api, limit, extrs$) =>
  extrs$.pipe(
    bufferCount(limit),
    mapRx((batch) =>
      batch.length === 1 ? batch[0] : api.tx.utility.batch(batch)
    )
  )
)
Example #12
Source File: Accordion.js    From lundium with MIT License 5 votes vote down vote up
clone = curry((props, elem) => cloneElement(elem, props))
Example #13
Source File: functions.js    From generator-webapp-rocket with MIT License 5 votes vote down vote up
valueOrDefault = curry(($default, value) => value ?? $default)
Example #14
Source File: functions.js    From generator-webapp-rocket with MIT License 5 votes vote down vote up
withoutItem = curry((x, xs) => xs |> without([x]))
Example #15
Source File: functions.js    From generator-webapp-rocket with MIT License 5 votes vote down vote up
addDays = curry((days, date) => {
    let localMutable = new Date(date)
    localMutable.setDate(localMutable.getDate() + days)
    return localMutable
})
Example #16
Source File: functions.js    From generator-webapp-rocket with MIT License 5 votes vote down vote up
addMilliseconds = curry((milliseconds, date) => new Date(date.getTime() + milliseconds))
Example #17
Source File: osk-detector.js    From on-screen-keyboard-detector with MIT License 5 votes vote down vote up
// rejectCapture :: Stream Boolean -> Stream a -> Stream a
	rejectCapture = curry(compose(join, snapshot((valveValue, event) => valveValue ? empty() : now(event))))
Example #18
Source File: breakDownAllNodes.js    From gatsby-startbootstrap-agency with MIT License 5 votes vote down vote up
propFilter = curry((pathList, regex) => pathSatisfies(test(regex), pathList))