ramda#sortBy TypeScript Examples
The following examples show how to use
ramda#sortBy.
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: useNextQuestion.tsx From nosgestesclimat-site with MIT License | 5 votes |
export function getNextQuestions(
missingVariables: Array<MissingVariables>,
questionConfig: SimulationConfig['questions'] = {},
answeredQuestions: Array<DottedName> = [],
situation: Simulation['situation'] = {},
engine: Engine
): Array<DottedName> {
const {
'non prioritaires': notPriority = [],
liste: whitelist = [],
'liste noire': blacklist = [],
} = questionConfig
let nextSteps = difference(getNextSteps(missingVariables), answeredQuestions)
nextSteps = nextSteps.filter(
(step) =>
(!whitelist.length || whitelist.some((name) => step.startsWith(name))) &&
(!blacklist.length || !blacklist.some((name) => step.startsWith(name)))
)
const nextQuestions = nextSteps.filter((name) => {
const rule = engine.getRule(name)
return rule.rawNode.question != null
})
const lastStep = last(answeredQuestions)
// L'ajout de la réponse permet de traiter les questions dont la réponse est
// "une possibilité", exemple "contrat salarié . cdd"
const lastStepWithAnswer =
lastStep && situation[lastStep]
? ([lastStep, situation[lastStep]]
.join(' . ')
.replace(/'/g, '')
.trim() as DottedName)
: lastStep
return sortBy((question) => {
const indexList =
whitelist.findIndex((name) => question.startsWith(name)) + 1
const indexNotPriority =
notPriority.findIndex((name) => question.startsWith(name)) + 1
const differenceCoeff = questionDifference(question, lastStepWithAnswer)
return indexList + indexNotPriority + differenceCoeff
}, nextQuestions)
}
Example #2
Source File: html-summary.ts From the-fake-backend with ISC License | 5 votes |
sortByPath = sortBy(compose(toLower, prop('path')))
Example #3
Source File: Conversation.tsx From nosgestesclimat-site with MIT License | 4 votes |
export default function Conversation({
customEndMessages,
customEnd,
orderByCategories,
}: ConversationProps) {
const dispatch = useDispatch()
const engine = useContext(EngineContext),
rules = engine.getParsedRules()
const nextQuestions = useNextQuestions()
const situation = useSelector(situationSelector)
const previousAnswers = useSelector(answeredQuestionsSelector)
const tracker = useContext(TrackerContext)
const objectifs = useSelector(objectifsSelector)
const rawRules = useSelector((state) => state.rules)
const previousSimulation = useSelector((state) => state.previousSimulation)
// orderByCategories is the list of categories, ordered by decreasing nodeValue
const questionsSortedByCategory = orderByCategories
? sortBy(
(question) =>
-orderByCategories.find((c) => question.indexOf(c.dottedName) === 0)
?.nodeValue,
nextQuestions
)
: nextQuestions
const focusedCategory = useQuery().get('catégorie')
const focusByCategory = (questions) => {
if (!focusedCategory) return questions
const filtered = questionsSortedByCategory.filter(
(q) => q.indexOf(focusedCategory) === 0
)
//this is important : if all questions of a focus have been answered
// then don't triggered the end screen, just ask the other questions
// as if no focus
if (!filtered.length) return questions
return filtered
}
const sortedQuestions = focusByCategory(questionsSortedByCategory)
const unfoldedStep = useSelector((state) => state.simulation.unfoldedStep)
const isMainSimulation = objectifs.length === 1 && objectifs[0] === 'bilan',
currentQuestion = !isMainSimulation ? nextQuestions[0] : sortedQuestions[0]
const currentQuestionIsAnswered =
currentQuestion && isMosaic(currentQuestion)
? true
: situation[currentQuestion] != null
const [dismissedRespirations, dismissRespiration] = useState([])
const [finder, setFinder] = useState(false)
useEffect(() => {
if (previousAnswers.length === 1) {
tracker.push(['trackEvent', 'NGC', '1ère réponse au bilan'])
}
}, [previousAnswers, tracker])
useEffect(() => {
// This hook lets the user click on the "next" button. Without it, the conversation switches to the next question as soon as an answer is provided.
// It introduces a state
// It is important to test for "previousSimulation" : if it exists, it's not loaded yet. Then currentQuestion could be the wrong one, already answered, don't put it as the unfoldedStep
if (
currentQuestion &&
!previousSimulation &&
currentQuestion !== unfoldedStep
) {
dispatch(goToQuestion(currentQuestion))
}
}, [dispatch, currentQuestion, previousAnswers, unfoldedStep, objectifs])
const goToPrevious = () => {
return dispatch(goToQuestion(previousQuestion))
}
// Some questions are grouped in an artifical questions, called mosaic questions, not present in publicodes
// here we need to submit all of them when the one that triggered the UI (we don't care which) is submitted, in order to see them in the response list and to avoid repeating the same n times
const mosaicQuestion = currentQuestion && isMosaic(currentQuestion)
const questionText = mosaicQuestion
? mosaicQuestion.question
: rules[currentQuestion]?.rawNode?.question
const questionsToSubmit = mosaicQuestion
? Object.entries(rules)
.filter(([dottedName, value]) =>
mosaicQuestion.isApplicable(dottedName)
)
.map(([dottedName]) => dottedName)
: [currentQuestion]
const currentQuestionIndex = previousAnswers.findIndex(
(a) => a === unfoldedStep
),
previousQuestion =
currentQuestionIndex < 0 && previousAnswers.length > 0
? previousAnswers[previousAnswers.length - 1]
: mosaicQuestion
? [...previousAnswers]
.reverse()
.find(
(el, index) =>
index < currentQuestionIndex && !questionsToSubmit.includes(el)
)
: previousAnswers[currentQuestionIndex - 1]
const submit = (source: string) => {
if (mosaicQuestion?.options?.defaultsToFalse) {
questionsToSubmit.map((question) =>
dispatch(updateSituation(question, situation[question] || 'non'))
)
}
questionsToSubmit.map((question) =>
dispatch({
type: 'STEP_ACTION',
name: 'fold',
step: question,
source,
})
)
}
const setDefault = () =>
// TODO: Skiping a question shouldn't be equivalent to answering the
// default value (for instance the question shouldn't appear in the
// answered questions).
questionsToSubmit.map((question) =>
dispatch(validateStepWithValue(question, undefined))
)
const onChange: RuleInputProps['onChange'] = (value) => {
dispatch(updateSituation(currentQuestion, value))
}
useKeypress('Escape', false, setDefault, 'keyup', [currentQuestion])
useKeypress(
'k',
true,
(e) => {
e.preventDefault()
setFinder((finder) => !finder)
},
'keydown',
[]
)
if (!nextQuestions.length)
return <SimulationEnding {...{ customEnd, customEndMessages }} />
const questionCategoryName = splitName(currentQuestion)[0],
questionCategory =
orderByCategories &&
orderByCategories.find(
({ dottedName }) => dottedName === questionCategoryName
)
const isCategoryFirstQuestion =
questionCategory &&
previousAnswers.find(
(a) => splitName(a)[0] === questionCategory.dottedName
) === undefined
const hasDescription =
((mosaicQuestion &&
(mosaicQuestion.description ||
rules[mosaicQuestion.dottedName].rawNode.description)) ||
rules[currentQuestion]?.rawNode.description) != null
return orderByCategories &&
isCategoryFirstQuestion &&
!dismissedRespirations.includes(questionCategory.dottedName) ? (
<CategoryRespiration
questionCategory={questionCategory}
dismiss={() =>
dismissRespiration([
...dismissedRespirations,
questionCategory.dottedName,
])
}
/>
) : (
<section
className="ui__ container"
css={`
@media (max-width: 800px) {
padding: 0.4rem 0 0.4rem;
}
position: relative;
padding-top: 1.2rem;
`}
>
{finder ? (
<QuestionFinder close={() => setFinder(false)} />
) : (
<div
css={`
position: absolute;
top: 0;
right: 0;
line-height: 1rem;
button {
padding: 0;
display: flex;
align-items: center;
color: var(--color);
opacity: 0.4;
}
img {
width: 1.2rem;
padding-top: 0.1rem;
}
span {
display: none;
font-weight: bold;
font-size: 70%;
margin-right: 0.3rem;
}
@media (min-width: 800px) {
span {
display: inline;
}
}
`}
>
<button
onClick={() => setFinder(!finder)}
title="Recherche rapide de questions dans le formulaire"
>
<img src={`/images/1F50D.svg`} />
<span>Ctrl-K</span>
</button>
</div>
)}
{orderByCategories && (
<Meta
title={rules[objectifs[0]].title + ' - ' + questionCategory.title}
/>
)}
<form
id="step"
style={{ outline: 'none' }}
onSubmit={(e) => {
e.preventDefault()
}}
>
{orderByCategories && questionCategory && (
<CategoryVisualisation questionCategory={questionCategory} />
)}
<div className="step">
<h2
css={`
margin: 0.4rem 0;
font-size: 120%;
`}
>
{questionText}{' '}
{hasDescription && (
<ExplicableRule
dottedName={
(mosaicQuestion && mosaicQuestion.dottedName) ||
currentQuestion
}
/>
)}
</h2>
<Aide />
<fieldset>
<RuleInput
dottedName={currentQuestion}
onChange={onChange}
onSubmit={submit}
/>
</fieldset>
</div>
<div className="ui__ answer-group">
{previousAnswers.length > 0 && currentQuestionIndex !== 0 && (
<>
<button
onClick={goToPrevious}
type="button"
className="ui__ simple small push-left button"
>
← <Trans>Précédent</Trans>
</button>
</>
)}
{currentQuestionIsAnswered ? (
<button
className="ui__ plain small button"
onClick={() => submit('accept')}
>
<span className="text">
<Trans>Suivant</Trans> →
</span>
</button>
) : (
<button
onClick={setDefault}
type="button"
className="ui__ simple small push-right button"
>
<Trans>Je ne sais pas</Trans> →
</button>
)}
</div>
<Notifications currentQuestion={currentQuestion} />
</form>
</section>
)
}
Example #4
Source File: SaiditIngestStore.ts From notabug with MIT License | 4 votes |
export function createSaiditIngest(
webca: LinguaWebcaClient = universe,
host: string = 'saidit.net'
): LinguaWebcaStore {
const app = new ExpressLikeStore()
app.get(
'/things/:lastSubmissionId/comments/:lastCommentId',
async (req, res) => {
const { lastSubmissionId, lastCommentId } = req.params
const commentIds = idRange(COMMENT_KIND, lastCommentId, COMMENTS_PER_POLL)
const submissionIds = idRange(
SUBMISSION_KIND,
lastSubmissionId,
SUBMISSIONS_PER_POLL
)
const apiRes = await webca.get(
`http://${host}/api/info.json?id=${[
...submissionIds,
...commentIds
].join(',')}`
)
const children = getListingThings(apiRes)
res.json(children)
}
)
// tslint:disable-next-line: variable-name
app.post(`/things/:kind/new`, async (_req, res) => {
// tslint:disable-next-line no-let
// let previousId = lastIds[SUBMISSION_KIND]
const config = await webca.get(
`notabug://notabug.io/me/pages/config:saidit_ingest/yaml`
)
const previousSubmissionId =
'' + (config && config[`newest_ingested_${SUBMISSION_KIND}`]) || '0'
const previousCommentId =
'' + (config && config[`newest_ingested_${COMMENT_KIND}`]) || '0'
const nativeThings = await app.client.get(
// `/things/${kind}/after/${previousId}`
`/things/${previousSubmissionId}/comments/${previousCommentId}`
)
if (
!nativeThings.length &&
parseInt(previousCommentId, ID_BASE) < parseInt('4tvm', ID_BASE)
) {
const lastIdNum =
parseInt(previousCommentId, ID_BASE) + COMMENTS_PER_POLL - 1
const lastId = lastIdNum.toString(ID_BASE)
console.log('comment drought advance')
await webca.patch(
`notabug://notabug.io/me/pages/config:saidit_ingest/yaml`,
{
[`newest_ingested_${COMMENT_KIND}`]: lastId
}
)
}
// tslint:disable-next-line: readonly-array
const things: any[] = []
for (const item of sortBy<typeof nativeThings[0]>(
propOr(0, 'created_utc'),
nativeThings
)) {
if (!item) {
continue
}
// tslint:disable-next-line: no-let
let thing: any
const nativeId = item.id
if (item.kind === SUBMISSION_KIND) {
if (item.author === '[deleted]' || item.selftext === '[removed]') {
continue
}
thing = {
author: `${item.author}@SaidIt`,
body: entities.decode(item.selftext || ''),
kind: 'submission',
timestamp: item.created_utc * 1000,
title: entities.decode(item.title),
topic: `SaidIt.${item.subreddit}`,
url: item.selftext ? '' : item.url || ''
}
} else if (item.kind === COMMENT_KIND) {
const linkId = (item.link_id || '').split('_').pop()
const [replyToKind, replyToSaiditId] = (item.parent_id || '').split('_')
const submissionThingId =
linkId &&
(await webca.get(
`notabug://notabug.io/me/lists/saidit:${SUBMISSION_KIND}/${linkId}`
))
const replyToThingId =
replyToSaiditId &&
(await webca.get(
`notabug://notabug.io/me/lists/saidit:${replyToKind}/${replyToSaiditId}`
))
if (!submissionThingId) {
// tslint:disable-next-line: no-console
console.log('skip item', item)
await webca.patch(
`notabug://notabug.io/me/pages/config:saidit_ingest/yaml`,
{
[`newest_ingested_${item.kind}`]: nativeId
}
)
continue
}
thing = {
author: `${item.author}@SaidIt`,
body: entities.decode(item.body || ''),
kind: 'comment',
opId: submissionThingId,
replyToId: replyToThingId || submissionThingId,
timestamp: item.created_utc * 1000,
topic: `SaidIt.${item.subreddit}`
}
}
if (!thing) {
console.log('wtf', item)
continue
}
things.push(thing)
const thingId = await webca.post(
`notabug://notabug.io/me/submit/${thing.kind}/${thing.topic}`,
thing
)
// tslint:disable-next-line: no-console
console.log('posted', thing.kind, thingId)
await webca.put(
`notabug://notabug.io/me/lists/saidit:${item.kind}/${nativeId}`,
thingId
)
await webca.patch(
`notabug://notabug.io/me/pages/config:saidit_ingest/yaml`,
{
[`newest_ingested_${item.kind}`]: nativeId
}
)
await new Promise(ok => setTimeout(ok, 1500))
}
res.json(things)
})
return app.request
}