ramda#compose JavaScript Examples
The following examples show how to use
ramda#compose.
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: requests.js From cross-chain-realitio-proxy with MIT License | 6 votes |
export async function saveRequests(requests) {
const createPutRequest = (item) => ({
PutRequest: {
Item: item,
},
});
const createBatchItem = compose(createPutRequest, extractStoredData, normalizeData);
return compose(batchWrite(requestsTable), map(createBatchItem))(requests);
}
Example #2
Source File: requests.js From cross-chain-realitio-proxy with MIT License | 6 votes |
export async function deleteAllRequests() {
const createDeleteRequest = (item) => ({
DeleteRequest: {
Key: item,
},
});
const data = await fetchAllRequestIds();
if (data.length === 0) {
return;
}
return compose(
batchWrite(requestsTable),
map(compose(createDeleteRequest, pick(["requestId", "chainId"], normalizeData)))
)(data);
}
Example #3
Source File: index.js From cross-chain-realitio-proxy with MIT License | 6 votes |
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: index.js From cross-chain-realitio-proxy with MIT License | 6 votes |
export function buildSetUpdateExpression(obj) {
const buildDescriptors = compose(
map(([key, value]) => ({
expr: `#${key} = :${key}`,
name: { [`#${key}`]: key },
value: { [`:${key}`]: value },
})),
toPairs
);
const descriptors = buildDescriptors(obj);
const buildExpression = compose((expr) => `SET ${expr}`, join(", "), 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 {
UpdateExpression: expression,
ExpressionAttributeNames: attrNames,
ExpressionAttributeValues: attrValues,
};
}
Example #5
Source File: index.js From cross-chain-realitio-proxy with MIT License | 6 votes |
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 #6
Source File: classNamesByBreakpoint.test.js From lundium with MIT License | 6 votes |
describe('classNamesByBreakpoint', () => {
const exampleClassNameFactory = (x, y) => `${y}-${x}`;
it('generates breakpoints classnames by provided array', () => {
expect(
classNamesByBreakpoint(exampleClassNameFactory, [1, 2, 3, 4]),
).toEqual(['xs-1', 'sm-2', 'md-3', 'lg-4']);
});
it('can accept value', () => {
expect(classNamesByBreakpoint(exampleClassNameFactory, '1')).toEqual([
'xs-1',
]);
});
it('use className factory to create output className', () => {
expect(
classNamesByBreakpoint(
compose(concat('hello-'), exampleClassNameFactory),
[1, 2],
),
).toEqual(['hello-xs-1', 'hello-sm-2']);
});
});
Example #7
Source File: fhir-references.js From discovery-mobile-ui with MIT License | 6 votes |
referenceMap = {
// each key is a "type" (but not the referenced _resource_ type, eg: "Practitioner")
// each value operates on a FHIR resource, and returns an Array of reference Objects
serviceProvider: compose(
(result) => (result ? [result] : []),
path(['serviceProvider']),
),
requester: compose(
(result) => (result ? [result] : []),
path(['requester']), // may or may not be practitioner?
),
participant: compose(
map(path(['individual'])), // may or may not be practitioner?
filter(hasPath(['individual', 'reference'])),
propOr([], 'participant'),
),
}
Example #8
Source File: createApiInstance.js From cross-chain-realitio-proxy with MIT License | 5 votes |
export default async function createApiInstance() {
const [batchSend, foreignProxy] = await Promise.all([
createBatchSend(web3, FOREIGN_TX_BATCHER_CONTRACT_ADDRESS),
getContract(web3, ForeignProxy.abi, process.env.FOREIGN_PROXY_CONTRACT_ADDRESS),
]);
async function getBlockNumber() {
return Number(await web3.eth.getBlockNumber());
}
async function getChainId() {
return Number(await web3.eth.getChainId());
}
async function getArbitrationRequest({ questionId, requester }) {
const [arbitration, chainId] = await P.all([
foreignProxy.methods.arbitrationRequests(questionId, requester).call(),
getChainId(),
]);
return {
...arbitration,
chainId,
questionId,
requester,
status: Number(arbitration.status),
};
}
async function getRequestedArbitrations({ fromBlock = 0, toBlock = "latest" } = {}) {
const events = await getPastEvents(foreignProxy, "ArbitrationRequested", { fromBlock, toBlock });
const allNotifiedRequests = await P.allSettled(
map(
({ returnValues }) =>
getArbitrationRequest({
questionId: returnValues._questionID,
requester: returnValues._requester,
}),
events
)
);
const onlyFulfilled = compose(filter(propEq("status", "fulfilled")), map(prop("value")));
return into([], onlyFulfilled, allNotifiedRequests);
}
async function handleFailedDisputeCreation(arbitration) {
await batchSend({
args: [arbitration.questionId, arbitration.requester],
method: foreignProxy.methods.handleFailedDisputeCreation,
to: foreignProxy.options.address,
});
return arbitration;
}
return {
getChainId,
getBlockNumber,
getArbitrationRequest,
getRequestedArbitrations,
handleFailedDisputeCreation,
};
}
Example #9
Source File: Box.js From lundium with MIT License | 5 votes |
omitInvalidProps = compose(
fromPairs,
// filter only event handlers and data-attributes.
// Due to backwards compatibily we can't use `elementProps`
filter(([prop]) => test(/^(on|data-|role|aria-)/, prop)),
toPairs,
)
Example #10
Source File: osk-detector.js From on-screen-keyboard-detector with MIT License | 5 votes |
// rejectCapture :: Stream Boolean -> Stream a -> Stream a
rejectCapture = curry(compose(join, snapshot((valveValue, event) => valveValue ? empty() : now(event))))
Example #11
Source File: fhir-references.js From discovery-mobile-ui with MIT License | 5 votes |
encounters = {
encounter: compose(
(result) => (result ? [result] : []),
path(['encounter']),
),
}
Example #12
Source File: createApiInstance.js From cross-chain-realitio-proxy with MIT License | 4 votes |
export default async function createApiInstance() {
const [batchSend, homeProxy, realitio] = await Promise.all([
createBatchSend(web3, HOME_TX_BATCHER_CONTRACT_ADDRESS),
getContract(web3, HomeProxy.abi, process.env.HOME_PROXY_CONTRACT_ADDRESS),
getContract(web3, RealitioInterface.abi, process.env.HOME_REALITIO_CONTRACT_ADDRESS),
]);
async function getBlockNumber() {
return Number(await web3.eth.getBlockNumber());
}
async function getChainId() {
return Number(await web3.eth.getChainId());
}
async function getRequest({ questionId, requester }) {
const [request, chainId] = await Promise.all([
homeProxy.methods.requests(questionId, requester).call(),
getChainId(),
]);
return {
...request,
chainId,
questionId,
requester,
status: Number(request.status),
};
}
async function getNotifiedRequests({ fromBlock = 0, toBlock = "latest" } = {}) {
const events = await getPastEvents(homeProxy, "RequestNotified", { fromBlock, toBlock });
const allNotifiedRequests = await P.allSettled(
map(
({ returnValues }) =>
getRequest({
questionId: returnValues._questionID,
requester: returnValues._requester,
}),
events
)
);
const onlyFulfilled = compose(filter(propEq("status", "fulfilled")), map(prop("value")));
return into([], onlyFulfilled, allNotifiedRequests);
}
async function getRejectedRequests({ fromBlock = 0, toBlock = "latest" } = {}) {
const events = await getPastEvents(homeProxy, "RequestRejected", { fromBlock, toBlock });
const allRejectedRequests = await P.allSettled(
map(
({ returnValues }) =>
getRequest({
questionId: returnValues._questionID,
requester: returnValues._requester,
}),
events
)
);
const onlyFulfilled = compose(filter(propEq("status", "fulfilled")), map(prop("value")));
return into([], onlyFulfilled, allRejectedRequests);
}
async function handleNotifiedRequest(request) {
await batchSend({
args: [request.questionId, request.requester],
method: homeProxy.methods.handleNotifiedRequest,
to: homeProxy.options.address,
});
return request;
}
async function handleChangedAnswer(request) {
await batchSend({
args: [request.questionId, request.requester],
method: homeProxy.methods.handleChangedAnswer,
to: homeProxy.options.address,
});
return request;
}
async function handleFinalizedQuestion(request) {
await batchSend({
args: [request.questionId, request.requester],
method: homeProxy.methods.handleFinalizedQuestion,
to: homeProxy.options.address,
});
return request;
}
async function handleRejectedRequest(request) {
await batchSend({
args: [request.questionId, request.requester],
method: homeProxy.methods.handleRejectedRequest,
to: homeProxy.options.address,
});
return request;
}
async function reportArbitrationAnswer(request) {
const { questionId } = request;
const { historyHash, answerOrCommitmentID, answerer } = await _getLatestAnswerParams(questionId);
await batchSend({
args: [questionId, historyHash, answerOrCommitmentID, answerer],
method: homeProxy.methods.reportArbitrationAnswer,
to: homeProxy.options.address,
});
return request;
}
async function _getLatestAnswerParams(questionId) {
const answers = await getPastEvents(realitio, "LogNewAnswer", {
filter: {
question_id: questionId,
},
});
if (answers.length == 0) {
throw new Error(`Question ${questionId} was never answered`);
}
const byMostRecentBlock = descend(prop("blockNumber"));
const sortedAnswers = sort(byMostRecentBlock, answers);
const latestAnswer = sortedAnswers[0].returnValues;
const previousAnswer = sortedAnswers[1]?.returnValues;
return {
historyHash: previousAnswer?.history_hash ?? ZERO_HASH,
answerOrCommitmentID: latestAnswer.answer,
answerer: latestAnswer.user,
};
}
return {
getBlockNumber,
getChainId,
getNotifiedRequests,
getRejectedRequests,
getRequest,
handleChangedAnswer,
handleFinalizedQuestion,
handleNotifiedRequest,
handleRejectedRequest,
reportArbitrationAnswer,
};
}
Example #13
Source File: osk-detector.js From on-screen-keyboard-detector with MIT License | 4 votes |
/**
*
* @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;
}