ramda#map TypeScript Examples
The following examples show how to use
ramda#map.
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: substitute.ts From interpreters with MIT License | 6 votes |
renameExps = (exps: CExp[]): CExp[] => {
const varGen = makeVarGen();
const replace = (e: CExp): CExp =>
isIfExp(e) ? makeIfExp(replace(e.test), replace(e.then), replace(e.alt)) :
isAppExp(e) ? makeAppExp(replace(e.rator), map(replace, e.rands)) :
isProcExp(e) ? replaceProc(e) :
e;
// Rename the params and substitute old params with renamed ones.
// First recursively rename all ProcExps inside the body.
const replaceProc = (e: ProcExp): ProcExp => {
const oldArgs = map((arg: VarDecl): string => arg.var, e.args);
const newArgs = map(varGen, oldArgs);
const newBody = map(replace, e.body);
return makeProcExp(map(makeVarDecl, newArgs), substitute(newBody, oldArgs, map(makeVarRef, newArgs)));
};
return map(replace, exps);
}
Example #2
Source File: useNextQuestion.tsx From nosgestesclimat-site with MIT License | 6 votes |
export function getNextSteps(
missingVariables: Array<MissingVariables>
): Array<DottedName> {
const byCount = ([, [count]]: [unknown, [number]]) => count
const byScore = ([, [, score]]: [unknown, [unknown, number]]) => score
const missingByTotalScore = reduce<MissingVariables, MissingVariables>(
mergeWith(add),
{},
missingVariables
)
const innerKeys = flatten(map(keys, missingVariables)),
missingByTargetsAdvanced = Object.fromEntries(
Object.entries(countBy(identity, innerKeys)).map(
// Give higher score to top level questions
([name, score]) => [
name,
score + Math.max(0, 4 - name.split('.').length),
]
)
)
const missingByCompound = mergeWith(
pair,
missingByTargetsAdvanced,
missingByTotalScore
),
pairs = toPairs<number>(missingByCompound),
sortedPairs = sortWith([descend(byCount), descend(byScore) as any], pairs)
return map(head, sortedPairs) as any
}
Example #3
Source File: L5-eval.ts From interpreters with MIT License | 6 votes |
evalLetrec = (exp: LetrecExp, env: Env): Result<Value> => {
const vars = map((b) => b.var.var, exp.bindings);
const vals = map((b) => b.val, exp.bindings);
const extEnv = makeExtEnv(vars, repeat(undefined, vars.length), env);
// @@ Compute the vals in the extended env
const cvalsResult = mapResult((v: CExp) => applicativeEval(v, extEnv), vals);
const result = mapv(cvalsResult, (cvals: Value[]) =>
zipWith((bdg, cval) => setFBinding(bdg, cval), extEnv.frame.fbindings, cvals));
return bind(result, _ => evalSequence(exp.body, extEnv));
}
Example #4
Source File: annotations.ts From checkstyle-github-action with MIT License | 6 votes |
export function annotationsForPath(resultFile: string): Annotation[] {
core.info(`Creating annotations for ${resultFile}`)
const root: string = process.env['GITHUB_WORKSPACE'] || ''
const result: CheckstyleReport = parser.parse(
fs.readFileSync(resultFile, 'UTF-8' as BufferEncoding),
XML_PARSE_OPTIONS
)
return chain(file => {
return map(violation => {
const annotation: Annotation = {
annotation_level: getWarningLevel(violation.severity),
path: path.relative(root, file.name),
start_line: Number(violation.line || 1),
end_line: Number(violation.line || 1),
title: violation.source,
message: decode(violation.message)
}
return annotation
}, asArray(file.error))
}, asArray<File>(result.checkstyle?.file))
}
Example #5
Source File: L4-ast.ts From interpreters with MIT License | 6 votes |
parseBindings = (bindings: Sexp): Result<Binding[]> => {
if (!isGoodBindings(bindings)) {
return makeFailure(`Invalid bindings: ${JSON.stringify(bindings, null, 2)}`);
}
const vars = map(b => b[0], bindings);
const valsResult = mapResult(binding => parseL4CExp(second(binding)), bindings);
return bind(valsResult,
(vals: CExp[]) => makeOk(zipWith(makeBinding, vars, vals)));
}
Example #6
Source File: utils.ts From notabug with MIT License | 6 votes |
listingNodesToIds = pipe<
readonly GunNode[],
ReadonlyArray<readonly string[]>,
readonly string[]
>(
map(listingNodeToIds),
reduce<readonly string[], readonly string[]>(union, [])
)
Example #7
Source File: L5-typecheck.ts From interpreters with MIT License | 6 votes |
typeofLet = (exp: LetExp, tenv: TEnv): Result<TExp> => {
const vars = map((b) => b.var.var, exp.bindings);
const vals = map((b) => b.val, exp.bindings);
const varTEs = map((b) => b.var.texp, exp.bindings);
const constraints = zipWithResult((varTE, val) => bind(typeofExp(val, tenv), (typeOfVal: TExp) =>
checkEqualType(varTE, typeOfVal, exp)),
varTEs, vals);
return bind(constraints, _ => typeofExps(exp.body, makeExtendTEnv(vars, varTEs, tenv)));
}
Example #8
Source File: user.service.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
public async assignRoles(userUuid: string, roleUuids: string[]): Promise<void> {
await this.userRoleRepository.delete({
userUuid,
});
await Promise.all(roleUuids.map((roleUuid) => this.userRoleRepository.save({
uuid: uuid.v4(),
roleUuid,
userUuid,
})))
this.server.emit('user-role-updated');
return;
}
Example #9
Source File: L3-normal.ts From interpreters with MIT License | 6 votes |
L3normalApplyProc = (proc: Value, args: CExp[], env: Env): Result<Value> => {
if (isPrimOp(proc)) {
const argVals: Result<Value[]> = mapResult((arg) => L3normalEval(arg, env), args);
return bind(argVals, (args: Value[]) => applyPrimitive(proc, args));
} else if (isClosure(proc)) {
// Substitute non-evaluated args into the body of the closure
const vars = map((p) => p.var, proc.params);
const body = renameExps(proc.body);
return L3normalEvalSeq(substitute(body, vars, args), env);
} else {
return makeFailure(`Bad proc applied ${JSON.stringify(proc, null, 2)}`);
}
}
Example #10
Source File: SaiditIngestStore.ts From notabug with MIT License | 6 votes |
function idRange(
kind: string,
lastId: string,
count: number
): readonly string[] {
const firstIdNum = parseInt(lastId, ID_BASE) + 1
const lastIdNum = firstIdNum + count
const idNums = range(firstIdNum, lastIdNum)
return idNums.map(idNum => `${kind}_${idNum.toString(ID_BASE)}`)
}
Example #11
Source File: L7-eval.ts From interpreters with MIT License | 5 votes |
letVars = (exp: LetExp | LetrecExp): string[] =>
map((b) => b.var.var, exp.bindings)
Example #12
Source File: dashboard-item-selector.component.ts From radiopanel with GNU General Public License v3.0 | 5 votes |
public ngOnInit(): void {
this.items = map(omit(['component']) as any)(DASHBOARD_COMPONENTS);
}
Example #13
Source File: L7b-eval.ts From interpreters with MIT License | 5 votes |
applyClosure = (proc: Closure, args: Value[], cont: Cont): Result<Value> => {
const vars = map((v: VarDecl) => v.var, proc.params);
return evalSequence(proc.body, makeExtEnv(vars, args, proc.env), cont);
}
Example #14
Source File: base.ts From reskript with MIT License | 5 votes |
constructDynamicDefines = (context: DefineContext): Record<string, any> => {
const staticDefines = constructDefines(context);
return map(v => DefinePlugin.runtimeValue(() => v, true), staticDefines);
}
Example #15
Source File: Flickr.tsx From react-js-tutorial with MIT License | 5 votes |
mediaUrls = compose<FlickrResponse, FlickrResponseItem[], string[]>(
map(mediaUrl),
prop("items")
)
Example #16
Source File: SaiditIngestStore.ts From notabug with MIT License | 5 votes |
getListingThings = pipe(
pathOr<readonly any[]>([], ['data', 'children']),
map(item => ({
...item.data,
kind: item.kind
})),
filter(d => !!d)
)
Example #17
Source File: user.service.ts From radiopanel with GNU General Public License v3.0 | 5 votes |
public async getRoles(userUuid: string): Promise<Role[]> {
const roleRelations = await this.userRoleRepository.find({
userUuid,
});
return roleRelations.map((role) => role.role);
}
Example #18
Source File: L3-ast.ts From interpreters with MIT License | 5 votes |
parseProcExp = (vars: Sexp, body: Sexp[]): Result<ProcExp> =>
isArray(vars) && allT(isString, vars) ? mapv(mapResult(parseL3CExp, body), (cexps: CExp[]) =>
makeProcExp(map(makeVarDecl, vars), cexps)) :
makeFailure(`Invalid vars for ProcExp ${JSON.stringify(vars, null, 2)}`)
Example #19
Source File: processDatabase.ts From kanel with MIT License | 4 votes |
processDatabase = async ({
connection,
preDeleteModelFolder = false,
customTypeMap = {},
modelHooks = [],
modelNominator = nameIdentity,
propertyNominator = (propertyName) =>
propertyName.indexOf(' ') !== -1 ? `'${propertyName}'` : propertyName,
initializerNominator = (modelName) => `${modelName}Initializer`,
idNominator = (modelName) => `${modelName}Id`,
makeIdType = (innerType, modelName) =>
`${innerType} & { " __flavor"?: '${modelName}' };`,
typeHooks = [],
typeNominator = nameIdentity,
fileNominator = identity,
resolveViews = false,
schemas,
...unknownProps
}: Config) => {
if (!isEmpty(unknownProps)) {
logger.warn(
`Unknown configuration properties: ${Object.keys(unknownProps).join(
', '
)}`
);
}
const typeMap = { ...defaultTypeMap, ...customTypeMap };
/** @type {import('./Config').Nominators} */
const nominators = {
modelNominator,
propertyNominator,
initializerNominator,
idNominator,
typeNominator,
fileNominator,
};
const modelProcessChain = [...defaultHooks, ...modelHooks];
const typeProcessChain = [...defaultHooks, ...typeHooks];
if (typeof connection === 'string') {
logger.log(`Connecting to ${chalk.greenBright(connection)}`);
} else {
logger.log(
`Connecting to ${chalk.greenBright(connection.database)} on ${
connection.host
}`
);
}
const schemaFolderMap = map(
(s: SchemaConfig) => path.resolve(s.modelFolder),
indexBy((s) => s.name, schemas)
) as Record<string, string>;
for (const schemaConfig of schemas) {
const schema = await extractSchema(
schemaConfig.name,
connection,
schemaConfig.resolveViews !== undefined
? schemaConfig.resolveViews
: resolveViews
);
if (preDeleteModelFolder) {
logger.log(` - Clearing old files in ${schemaConfig.modelFolder}`);
await rmfr(schemaConfig.modelFolder, { glob: true });
}
if (!fs.existsSync(schemaConfig.modelFolder)) {
fs.mkdirSync(schemaConfig.modelFolder, { recursive: true });
}
await processSchema(
schemaConfig,
schema,
typeMap,
nominators,
modelProcessChain,
typeProcessChain,
schemaFolderMap,
makeIdType
);
}
}
Example #20
Source File: base.ts From reskript with MIT License | 4 votes |
factory: ConfigurationFactory = async entry => {
const {
usage,
cwd,
srcDirectory,
hostPackageName,
mode,
features,
buildTarget,
buildVersion,
buildTime,
entries,
cache = 'persist',
cacheDirectory,
projectSettings: {
build: {
publicPath,
thirdParty,
reportLintErrors,
style: {
extract,
},
},
},
} = entry;
const tasks = [
computeCacheKey(entry),
Promise.all(Object.values(rules).map(rule => rule(entry))),
resolve('eslint'),
resolve('stylelint'),
resolve('regenerator-runtime'),
] as const;
const [cacheKey, moduleRules, eslintPath, stylelintPath, regeneratorRuntimePath] = await Promise.all(tasks);
const defines: DefineContext = {
features,
mode,
buildVersion,
buildTarget,
buildTime,
env: process.env,
};
const eslintOptions = {
eslintPath,
baseConfig: getScriptLintBaseConfig({cwd}),
exclude: ['node_modules', 'externals'],
extensions: ['js', 'cjs', 'mjs', 'jsx', 'ts', 'tsx'],
emitError: true,
emitWarning: usage === 'devServer',
};
const styleLintOptions = {
stylelintPath,
config: getStyleLintBaseConfig({cwd}),
emitErrors: true,
allowEmptyInput: true,
failOnError: mode === 'production',
files: `${srcDirectory}/**/*.{css,less}`,
};
const htmlPlugins = thirdParty ? [] : createHtmlPluginInstances(entry);
const cssOutput = thirdParty ? 'index.css' : '[name].[contenthash].css';
const plugins = [
...htmlPlugins,
createTransformHtmlPluginInstance(entry),
(usage === 'build' && extract) && new MiniCssExtractPlugin({filename: cssOutput}),
new ContextReplacementPlugin(/moment[\\/]locale$/, /^\.\/(en|zh-cn)$/),
new DefinePlugin(constructDynamicDefines(defines)),
new InterpolateHTMLPlugin(process.env),
// @ts-expect-error
reportLintErrors && usage === 'build' && new ESLintPlugin(eslintOptions),
reportLintErrors && usage === 'build' && new StyleLintPlugin(styleLintOptions),
];
return {
mode,
context: cwd,
entry: entries.reduce(
(webpackEntry, appEntry) => {
const currentWebpackEntry = convertToWebpackEntry(appEntry);
webpackEntry[appEntry.name] = currentWebpackEntry;
return webpackEntry;
},
{} as EntryObject
),
output: {
path: path.join(cwd, 'dist', 'assets'),
filename: '[name].[chunkhash].js',
publicPath: publicPath || '/assets/',
},
module: {
rules: moduleRules,
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
mainFields: ['browser', 'module', 'main'],
alias: {
'@': path.join(cwd, srcDirectory),
...hostPackageName ? {[hostPackageName]: path.join(cwd, 'src')} : {},
'regenerator-runtime': path.dirname(regeneratorRuntimePath),
},
plugins: [
new ResolveTypeScriptPlugin(),
],
},
cache: cache === 'off'
? false
: (
cache === 'persist'
? {
type: 'filesystem',
version: cacheKey,
cacheDirectory: cacheDirectory ? path.join(cwd, cacheDirectory) : undefined,
name: `${paramCase(entry.usage)}-${paramCase(entry.mode)}`,
}
: {type: 'memory'}
),
snapshot: {
module: {
timestamp: usage !== 'build',
hash: usage === 'build',
},
resolve: {
timestamp: usage !== 'build',
hash: usage === 'build',
},
},
plugins: compact(plugins),
optimization: {},
};
}