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


TypeScript lodash.pull函数代码示例

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


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

示例1: mergeSimilarOverloads

function mergeSimilarOverloads(overloads: Overload[]): Overload[] {
    const newOverloads = _.cloneDeep(overloads);
    for (const overload of newOverloads) {
        // We can merge if all param types are the same except one, and the return types are the same.
        // Also, we can't merge a placeholder param with a non-placeholder.
        const others = newOverloads.filter(o2 => o2 !== overload
            && _.isEqual(overload.typeParams, o2.typeParams)
            && overload.params.length === o2.params.length
            && overload.params.length >= 1
            && overload.params.every((p, i) => isPlaceholder(p) === isPlaceholder(o2.params[i]))
            && overload.params.filter((p, i) => getParamType(p) !== getParamType(o2.params[i])).length <= 1
            && overload.returnType === o2.returnType);
        if (_.isEmpty(others))
            continue;

        const differingParamIndexes = _(others)
            .map(o2 => overload.params.findIndex((p, i) => getParamType(p) !== getParamType(o2.params[i])))
            .filter(i => i !== -1)
            .uniq()
            .value();
        if (differingParamIndexes.length > 1)
            continue; // Only one param is different, but it's a different param for some overloads, so we can't merge
        const similarOverloads = [overload].concat(others);
        for (let i = 0; i < overload.params.length; ++i) {
            const paramNames = _.uniq(similarOverloads.map(o => getParamName(o.params[i])));
            const newParamName = (paramNames.length > 1) ? `${paramNames[0]}Or${paramNames.slice(1).map(_.upperFirst).join("Or")}` : paramNames[0];

            const newParamType = _(similarOverloads)
                .map(o => o.params[i])
                .flatMap(p => getParamType(p).split("|"))
                .map(_.trim)
                .uniq()
                .sortBy(type => type === "undefined" ? 2 : (type === "null" ? 1 : 0))
                .join(" | ");
            overload.params[i] = `${newParamName}: ${newParamType}`;
        }
        _.pull(newOverloads, ...others);
    }
    return newOverloads;
}
开发者ID:devlato,项目名称:DefinitelyTyped,代码行数:40,代码来源:generate-fp.ts

示例2:

 request.always(() => _.pull(pendingComponents, request));
开发者ID:zipzav,项目名称:improved-initiative,代码行数:1,代码来源:Components.ts

示例3: main

async function main() {
    lineBreak = await getLineBreak();
    const commonTypes: string[] = [];
    const tsconfigPath = path.join("..", "tsconfig.json");

    const subfolders = ["common"];
    const promises: Array<Promise<string[]>> = [];
    for (const subfolder of subfolders) {
        promises.push(new Promise<string[]>((resolve, reject) => {
            fs.readdir(path.join("..", subfolder), (err, files) => {
                if (err) {
                    console.error(`failed to list directory contents for '${subfolder}': `, err);
                    reject(err);
                    return;
                }
                const filePaths = files.map(f => path.join("..", subfolder, f));
                try {
                    resolve(processDefinitions(filePaths, commonTypes));
                } catch (e) {
                    console.error(`failed to process files in '${subfolder}': `, e);
                    reject(e);
                }
            });
        }));
    }

    let functions: string;
    try {
        functions = _.flatten(await Promise.all(promises)).join(lineBreak);
    } catch (err) {
        console.error("Failed to parse all functions: ", err);
        return;
    }
    _.pull(commonTypes, "LoDashExplicitWrapper");
    const commonTypeSearch = new RegExp(`\\b(${commonTypes.join("|")})\\b`, "g");
    functions = functions.replace(commonTypeSearch, "_.$1");
    const syncFunctions = functions.replace(/\bLoDashExplicitWrapper\b/g, "LoDashExplicitSyncWrapper");
    const asyncFunctions = functions.replace(/\bLoDashExplicitWrapper\b/g, "LoDashExplicitAsyncWrapper");

    const lodashFile = [
        "// AUTO-GENERATED: do not modify this file directly.",
        "// If you need to make changes, modify types/lodash/scripts/generate-lowdb.ts (if necessary), then open a terminal in types/lodash/scripts, and do:",
        "// npm install && npm run generate",
        "",
        'import _ = require("lodash");',
        'declare module "./index" {',
        "    interface LoDashExplicitSyncWrapper<TValue> {",
        syncFunctions, // TODO: write sync?
        "    }",
        "",
        "    interface LoDashExplicitAsyncWrapper<TValue> {",
        asyncFunctions, // TODO: write async?
        "    }",
        "}",
        "",
    ].join(lineBreak);
    const lodashFilePath = path.resolve(__dirname, "..", "..", "lowdb", "_lodash.d.ts");
    fs.writeFile(lodashFilePath, lodashFile, (err) => {
        if (err)
            console.error(`Failed to write ${lodashFilePath}: `, err);
    });
}
开发者ID:MichaelBuen,项目名称:DefinitelyTyped,代码行数:62,代码来源:generate-lowdb.ts

示例4: curryOverloads

function curryOverloads(overloads: Overload[], functionName: string, paramOrder: number[], spreadIndex: number, isFixed: boolean): Interface[] {
    overloads = _.cloneDeep(overloads);

    // Remove unused type parameters
    for (const overload of overloads) {
        for (let i = 0; i < overload.typeParams.length; ++i) {
            const search = new RegExp(`\\b${overload.typeParams[i].name}\\b`);
            if (overload.params.every(p => !search.test(p)) && !search.test(overload.returnType)) {
                overload.typeParams.splice(i, 1);
                --i;
            }
        }
        if (overloads.some(o => o !== overload && _.isEqual(o, overload)))
            _.pull(overloads, overload);
    }

    if (!isFixed) {
        // Non-fixed arity functions cannot be curried.
        for (const overload of overloads)
            overload.params = overload.params.map(p => p.replace(/\?:/g, ":")); // No optional parameters
        return [{
            name: _.upperFirst(functionName),
            typeParams: [],
            overloads,
        }];
    }
    paramOrder = paramOrder.filter(p => typeof p === "number");
    const arity = paramOrder.length;

    if (spreadIndex !== -1) {
        // The parameter at this index is an array that will be spread when passed down to the actual function (e.g. assignAll, invokeArgs, partial, without).
        // For these parameters, we expect the input to be an array (so remove the "...")

        // Spread/rest parameters could be in any of the following formats:
        // 1. The rest parameter is at spreadIndex, and it is the last parameter.
        // 2. The rest parameter is immediately after spreadIndex, e.g. assign(object, ...sources[]). In this case, convert it to assignAll(...object[])
        // 3. The rest parameter is not the last parameter, e.g. assignWith(object, ...sources[], customizer)
        if (spreadIndex === arity - 1) {
            // cases 1-2
            for (let i = 0; i < overloads.length; ++i) {
                const overload = overloads[i];
                if (overload.params.length === arity && overload.params[spreadIndex] && overload.params[spreadIndex].startsWith("...")) {
                    overload.params[spreadIndex] = overload.params[spreadIndex].replace("...", "");
                } else if (overload.params.length === arity + 1 && overload.params[spreadIndex + 1] && overload.params[spreadIndex + 1].startsWith("...")) {
                    overload.params.splice(spreadIndex + 1, 1);
                    const parts = overload.params[spreadIndex].split(":").map(_.trim);
                    parts[1] = `ReadonlyArray<${parts[1]}>`;
                    overload.params[spreadIndex] = `${parts[0]}: ${parts[1]}`;
                } else {
                    _.pull(overloads, overload);
                    --i;
                }
            }
        } else {
            // case 3
            const overload = overloads[0];
            overloads = [{
                jsdoc: overload.jsdoc,
                typeParams: [],
                params: [
                    ...overload.params.slice(0, spreadIndex),
                    "args: ReadonlyArray<any>",
                    ...overload.params.slice(overload.params.length - (arity - spreadIndex - 1)),
                ],
                returnType: "any",
            }];
        }
    }

    let filteredOverloads = overloads.filter(o => o.params.length >= arity && o.params.slice(arity).every(p => p.includes("?") && !p.startsWith("iteratee"))
        && o.params.every(p => !p.startsWith("...") && !p.startsWith("guard:")));
    if (filteredOverloads.length === 0)
        filteredOverloads = overloads.filter(o => o.params.length >= arity && o.params.slice(arity).every(p => p.includes("?") || p.startsWith("..."))
            && o.params.every(p => !p.startsWith("guard:")));
    if (filteredOverloads.length === 0)
        filteredOverloads = overloads.filter(o => o.params.length > 0 && o.params.length <= arity + 1 && o.params[o.params.length - 1].startsWith("..."));
    if (filteredOverloads.length === 0)
        console.warn(`No matching overloads found for ${functionName} with arity ${arity}`);

    const restOverloads = overloads.filter(o => o.params.length > 0 && o.params[o.params.length - 1].startsWith("..."));
    for (const restOverload of restOverloads) {
        restOverload.params[restOverload.params.length - 1] = restOverload.params[restOverload.params.length - 1]
            .substring(3)
            .replace(/\[\]$/, "")
            .replace(/: Array<(.+)>$/, ": $1");
        if (restOverload.params.length < arity) {
            const paramToCopy = restOverload.params[restOverload.params.length - 1];
            const copiedParams = _.range(2, arity - restOverload.params.length + 2).map(i => paramToCopy.replace(/(^.+?):/, `$1${i}:`));
            restOverload.params.push(...copiedParams);
        }
    }

    for (const overload of filteredOverloads)
        preProcessOverload(overload, functionName, arity);

    const interfaces = _.flatMap(filteredOverloads, (o, i) => {
        const reargParams = o.params.map((p, i) => o.params[paramOrder.indexOf(i)]);
        return curryOverload({
            typeParams: o.typeParams,
            params: reargParams,
//.........这里部分代码省略.........
开发者ID:Q-Man,项目名称:DefinitelyTyped,代码行数:101,代码来源:generate-fp.ts

示例5: parseDefinitions


//.........这里部分代码省略.........
        let paramStartIndex = overloadString.indexOf("(");
        if (paramStartIndex !== -1) {
            const overload: Overload = { typeParams: [], params: [], returnType: "", jsdoc: currentDefinition.jsdoc };

            const previousLine = getPreviousLine(definitionString, overloadStartIndex).trim();
            if (previousLine.startsWith("// tslint:disable"))
                overload.tslintDisable = previousLine;

            const typeParamStartIndex = overloadString.indexOf("<");
            if (typeParamStartIndex !== -1 && typeParamStartIndex < paramStartIndex) {
                const typeParamEndIndex = overloadString.indexOf(">(", typeParamStartIndex);
                if (typeParamEndIndex !== -1) {
                    paramStartIndex = typeParamEndIndex + 1;
                    overload.typeParams = overloadString
                        .substring(typeParamStartIndex + 1, typeParamEndIndex)
                        .split(",")
                        .map((tpString): TypeParam => {
                            const typeParam: TypeParam = { name: tpString };
                            let parts = tpString.split(/=[^>]/);
                            if (parts[1])
                                typeParam.equals = parts[1].trim();
                            parts = tpString.split(" extends ");
                            if (parts[1])
                                typeParam.extends = parts[1].trim();
                            typeParam.name = parts[0].trim();
                            return typeParam;
                        });
                }
            }
            const paramEndIndex = overloadString.indexOf("):", paramStartIndex);
            if (paramEndIndex === -1) {
                console.warn(`Failed to find parameter end position in overload for '${name}' (${filePath}).`);
                continue;
            }
            overload.params = overloadString
                .substring(paramStartIndex + 1, paramEndIndex)
                .split(/,(?=[^,]+:)(?=(?:[^()]*|.*\(.*\).*)$)/m) // split on commas, but ignore Generic<T, U> and (a, b) => c
                .map(_.trim)
                .map(o => _.trim(o, ","))
                .filter(o => !!o);
            overload.returnType = overloadString.substring(paramEndIndex + 2).trim();
            currentDefinition.overloads.push(overload);
        } else {
            // This overload actually points to an interface. Try to find said interface and get the overloads from there.
            const overloadParts = overloadString.split(":");
            const interfaceName = overloadParts[1].trim();
            if (interfaceName.startsWith("typeof ") || interfaceName.startsWith("LoDashStatic[")) {
                // This is an alias (e.g. first: typeof _.head, or first: LoDashStatic['head']).
                // Ignore it since convert() will create this alias based on the original function.
                continue;
            }
            let interfaceStartIndex: number;
            let interfaceEndIndex: number;
            if (!interfaceName.startsWith("{")) {
                const ignoreInterfaceNames = ["string", "TemplateSettings", "MapCacheConstructor"];
                if (ignoreInterfaceNames.includes(interfaceName))
                    continue;
                const interfaceRegExp = new RegExp(`( *)interface ${interfaceName} {`);
                const interfaceMatch = interfaceRegExp.exec(definitionString);
                if (!interfaceMatch) {
                    const lineNumber = getLineNumber(definitionString, overloadStartIndex);
                    console.warn(`Failed to parse function '${name}': interface '${interfaceName}' not found. (${filePath} line ${lineNumber})`);
                    continue;
                }
                interfaceStartIndex = interfaceMatch.index + interfaceMatch[0].length;
                interfaceEndIndex = definitionString.indexOf(`${lineBreak}${interfaceMatch[1]}}`, interfaceStartIndex);
                if (interfaceEndIndex === -1) {
                    const lineNumber = getLineNumber(definitionString, interfaceStartIndex);
                    console.warn(`Failed to find end of interface '${interfaceName}' (starting at ${filePath} line ${lineNumber}).`);
                    continue;
                }
                _.pull(commonTypes, interfaceName);
            } else {
                // This is an inline type definition
                interfaceStartIndex = definitionString.indexOf("{", overloadStartIndex + overloadParts[0].length) + 1;
                interfaceEndIndex = definitionString.indexOf("}", interfaceStartIndex);
                if (interfaceEndIndex === -1 || interfaceEndIndex >= endIndex) {
                    console.warn(`Failed to find closing '}' character for property '${name}' (${filePath}).`);
                    continue;
                }
                overloadEndIndex = definitionString.indexOf(";", interfaceEndIndex);
                if (overloadEndIndex === -1 || overloadEndIndex >= endIndex) {
                    const lineNumber = getLineNumber(definitionString, overloadStartIndex);
                    console.warn(`Overload does not end with semicolon! ${filePath} line ${lineNumber}`);
                    continue;
                }
                overloadRegExp.lastIndex = overloadEndIndex;
            }
            const [definition] = parseDefinitions(definitionString, interfaceStartIndex, interfaceEndIndex, filePath, commonTypes, name);
            if (definition) {
                for (const overload of definition.overloads)
                    overload.jsdoc = currentDefinition.jsdoc;
                currentDefinition.overloads.push(...definition.overloads);
            }
        }
    }
    if (currentDefinition && !_.isEmpty(currentDefinition.overloads))
        definitons.push(currentDefinition);
    return definitons;
}
开发者ID:Q-Man,项目名称:DefinitelyTyped,代码行数:101,代码来源:generate-fp.ts

示例6:

 _.forEach(object, (value, property) => {
     if (!_.includes(forbidden, property)) {
         cleaned[property] = _.cloneDeep(value);
         _.pull(missing, property);
     }
 });
开发者ID:mactanxin,项目名称:gui,代码行数:6,代码来源:methodCleaner.ts

示例7: getJsRule

export const getModuleAndPlugins = (
  target: Target,
  command: Command,
  options: EnvOptions
) => {
  const rules: Rule[] = [
    getJsRule(target, command),
    getCssRule(command),
    imageRule,
    eotRule,
    woffRule,
    ttfRule
  ];
  const plugins: Plugin[] = [miniCssExtractPlugin, loaderOptionsPlugin];

  if (options.parent.env.length) {
    const definitions = options.parent.env.reduce(
      (definitions, { key, value }) => {
        definitions[`process.env.${key}`] = JSON.stringify(value);
        return definitions;
      },
      {} as { [key: string]: string }
    );
    const definePlugin = new DefinePlugin(definitions);
    plugins.push(definePlugin);
  }

  if (project.ws.tsconfig) {
    rules.push(getTsRule(target, command));
    plugins.push(forkTsCheckerPlugin);
  }

  if (target === 'spa') {
    plugins.push(indexHtmlPlugin);
  }

  // does node need a production build?
  if (command === 'build -p') {
    plugins.push(defineProductionPlugin);
    plugins.push(
      new CleanWebpackPlugin([project.ws.distReleaseDir], {
        verbose: false,
        root: process.cwd()
      })
    );
    if (project.ws.tsconfig) {
      plugins.push(new TypingsPlugin(project.ws.distReleaseDir));
    }
  } else if (command === 'build') {
    plugins.push(
      new CleanWebpackPlugin([project.ws.distDir], {
        verbose: false,
        root: process.cwd()
      })
    );
    if (project.ws.tsconfig && target === 'node') {
      plugins.push(new TypingsPlugin(project.ws.distDir));
    }
  }

  if (target === 'spa' && command === 'build -p') {
    // should this be used in non-spa's, too?
    // should we remove loaderOptionsPlugin then?
    plugins.push(productionOptionsPlugin);

    // switch css plugin
    pull(plugins, miniCssExtractPlugin);
    plugins.push(miniCssExtractPluginHashed);
  } else if (target === 'spa' && command === 'build') {
    plugins.push(new HotModuleReplacementPlugin());
  }

  return { module: { rules }, plugins };
};
开发者ID:Mercateo,项目名称:ws,代码行数:74,代码来源:options.ts

示例8: bryanTest1

 bryanTest1() {
     var array = [1, 2, 3, 1, 2, 3];
     return _.pull(array, 2, 3);
 }
开发者ID:phhoangbao,项目名称:angular2-test,代码行数:4,代码来源:app.component.ts

示例9: removePlayer

export function removePlayer(player: Player) {
  _.pull(players, player);
}
开发者ID:euoia,项目名称:node-mud,代码行数:3,代码来源:world.ts

示例10:

 onDelete: (node: INode) => {
   _.pull(this.model, node);
 }
开发者ID:yanhao1991,项目名称:shift-front,代码行数:3,代码来源:sketchpad.controller.ts


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