当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript convert.default函数代码示例

本文整理汇总了TypeScript中lodash/fp/convert.default函数的典型用法代码示例。如果您正苦于以下问题:TypeScript default函数的具体用法?TypeScript default怎么用?TypeScript default使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了default函数的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: processDefinitions

async function processDefinitions(filePaths: string[], commonTypes: string[]): Promise<string[]> {
    const builder: { [name: string]: (...args: number[][]) => () => Interface[] } = {};
    const unconvertedBuilder: { [name: string]: (...args: number[][]) => () => Interface[] } = {};
    for (const filePath of filePaths) {
        const definitions = await parseFile(filePath, commonTypes);
        for (const definition of definitions) {
            if (definition.overloads.every(o => o.params.length <= 1 && o.returnType === "typeof _")) {
                // Our convert technique doesn't work well on "typeof _" functions (or at least runInContext)
                // Plus, if there are 0-1 parameters, there's nothing to curry anyways.
                unconvertedBuilder[definition.name] = (...args: number[][]) => {
                    return () => curryOverloads(definition.overloads, definition.name, args[0] || [], -1, false);
                };
            } else {
                builder[definition.name] = (...args: Array<number | number[]>) => {
                    // args were originally passed in as [0], [1], [2], [3], [4]. If they changed order, that indicates how the functoin was re-arged
                    // Return a function because some definitons (like rearg) expect to have a function return value

                    // If any argument is a number instead of an array, then the argument at that index is being spread (e.g. assignAll, invokeArgs, partial, without)
                    const spreadIndex = args.findIndex(a => typeof a === "number");
                    let isFixed = true;
                    if (spreadIndex !== -1) {
                        // If there's a spread parameter, convert() won't cap the number of arguments, so we need to do it manually
                        const arity = Math.max(spreadIndex, args[spreadIndex] as number) + 1;
                        args = args.slice(0, arity);
                    } else if (args.length > 4 || definition.name === "flow" || definition.name === "flowRight") {
                        // Arity wasn't fixed by convert()
                        isFixed = false;
                    } else {
                        // For some reason, convert() doesn't seems to tell us which functions have unchanged argument order.
                        // So we have to hard-code it.
                        const unchangedOrders = ["add", "assign", "assignIn", "bind", "bindKey", "concat", "difference", "divide", "eq",
                            "gt", "gte", "isEqual", "lt", "lte", "matchesProperty", "merge", "multiply", "overArgs", "partial", "partialRight",
                            "propertyOf", "random", "range", "rangeRight", "subtract", "zip", "zipObject", "zipObjectDeep"];
                        if (unchangedOrders.includes(definition.name))
                            args = _.sortBy(args as number[][], (a: number[]) => a[0]);
                    }

                    return () => curryOverloads(definition.overloads, definition.name, _.flatten(args), spreadIndex, isFixed);
                };
            }
        }
    }

    // Use convert() to tell us how functions will be rearged and aliased
    const builderFp = convert(builder, { rearg: true, fixed: true, immutable: false, curry: false, cap: false });
    _.defaults(builderFp, unconvertedBuilder);

    const functionNames = Object.keys(builderFp).filter(key => key !== "convert" && typeof builderFp[key] === "function");
    for (const functionName of functionNames) {
        // Assuming the maximum arity is 4. Pass one more arg than the max arity so we can detect if arguments weren't fixed.
        const outputFn: (...args: any[]) => Interface[] = builderFp[functionName]([0], [1], [2], [3], [4]);
        const commonTypeSearch = new RegExp(`\\b(${commonTypes.join("|")})\\b`, "g");
        commonTypeSearch.lastIndex;
        let importCommon = false;
        let output = outputFn([0], [1], [2], [3], [4])
            .map(interfaceToString)
            .join(lineBreak)
            .replace(commonTypeSearch, match => {
                importCommon = true;
                return `_.${match}`;
            });
        if (!importCommon && output.includes("typeof _"))
            importCommon = true;
        const interfaceNameMatch = output.match(/(?:interface|type) ([A-Za-z0-9]+)/);
        const interfaceName = (interfaceNameMatch ? interfaceNameMatch[1] : undefined) || _.upperFirst(functionName);
        output = [
            "// AUTO-GENERATED: do not modify this file directly.",
            "// If you need to make changes, modify generate-fp.ts (if necessary), then open a terminal in types/lodash/scripts, and do:",
            "// npm run fp",
            importCommon ? `${lineBreak}import _ = require("../index");${lineBreak}` : '',
            output,
            "",
            `declare const ${functionName}: ${interfaceName};`,
            `export = ${functionName};`,
            "",
        ].join(lineBreak);
        const targetFile = `../fp/${functionName}.d.ts`;
        fs.writeFile(targetFile, output, (err) => {
            if (err)
                console.error(`failed to write file: ${targetFile}`, err);
        });
    }
    return functionNames;
}
开发者ID:Q-Man,项目名称:DefinitelyTyped,代码行数:84,代码来源:generate-fp.ts

示例2: processDefinitions

async function processDefinitions(filePaths: string[], commonTypes: string[]): Promise<InterfaceGroup[]> {
    const builder: { [name: string]: (...args: number[][]) => () => Interface[] } = {};
    const unconvertedBuilder: { [name: string]: (...args: number[][]) => () => Interface[] } = {};
    for (const filePath of filePaths) {
        const definitions = await parseFile(filePath, commonTypes);
        for (const definition of definitions) {
            if (definition.overloads.every(o => o.params.length <= 1 && (o.returnType === "typeof _" || o.returnType === "LoDashStatic"))) {
                // Our convert technique doesn't work well on "typeof _" functions (or at least runInContext)
                // Plus, if there are 0-1 parameters, there's nothing to curry anyways.
                unconvertedBuilder[definition.name] = (...args: number[][]) => {
                    return () => curryDefinition(definition, args[0] || [], -1, false);
                };
            } else {
                builder[definition.name] = (...args: Array<number | number[]>) => {
                    // args were originally passed in as [0], [1], [2], [3], [4]. If they changed order, that indicates how the functoin was re-arged
                    // Return a function because some definitons (like rearg) expect to have a function return value

                    // If any argument is a number instead of an array, then the argument at that index is being spread (e.g. assignAll, invokeArgs, partial, without)
                    const spreadIndex = args.findIndex(a => typeof a === "number");
                    let isFixed = true;
                    if (spreadIndex !== -1) {
                        // If there's a spread parameter, convert() won't cap the number of arguments, so we need to do it manually
                        const arity = Math.max(spreadIndex, args[spreadIndex] as number) + 1;
                        args = args.slice(0, arity);
                    } else if (args.length > 4 || definition.name === "flow" || definition.name === "flowRight") {
                        // Arity wasn't fixed by convert()
                        isFixed = false;
                    } else {
                        // For some reason, convert() doesn't seems to tell us which functions have unchanged argument order.
                        // So we have to hard-code it.
                        const unchangedOrders = ["add", "assign", "assignIn", "bind", "bindKey", "concat", "difference", "divide", "eq",
                            "gt", "gte", "isEqual", "lt", "lte", "matchesProperty", "merge", "multiply", "overArgs", "partial", "partialRight",
                            "propertyOf", "random", "range", "rangeRight", "subtract", "zip", "zipObject", "zipObjectDeep"];
                        if (unchangedOrders.includes(definition.name))
                            args = _.sortBy(args as number[][], (a: number[]) => a[0]);
                    }

                    return () => curryDefinition(definition, _.flatten(args), spreadIndex, isFixed);
                };
            }
        }
    }

    // Use convert() to tell us how functions will be rearged and aliased
    const builderFp = convert(builder, { rearg: true, fixed: true, immutable: false, curry: false, cap: false });
    _.defaults(builderFp, unconvertedBuilder);

    const functionNames = Object.keys(builderFp).filter(key => key !== "convert" && typeof builderFp[key] === "function");
    const interfaceGroups: InterfaceGroup[] = functionNames.map((functionName): InterfaceGroup => ({
        functionName,
        // Assuming the maximum arity is 4. Pass one more arg than the max arity so we can detect if arguments weren't fixed.
        interfaces: builderFp[functionName]([0], [1], [2], [3], [4])([0], [1], [2], [3], [4]),
    }));
    for (const functionName of functionNames) {
        const output = [
            `import { ${functionName} } from "../fp";`,
            `export = ${functionName};`,
            "",
        ].join(lineBreak);
        const targetFile = `../fp/${functionName}.d.ts`;
        fs.writeFile(targetFile, output, (err) => {
            if (err)
                console.error(`failed to write file: ${targetFile}`, err);
        });
    }
    return interfaceGroups;
}
开发者ID:MichaelBuen,项目名称:DefinitelyTyped,代码行数:67,代码来源:generate-fp.ts


注:本文中的lodash/fp/convert.default函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。