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


TypeScript lodash.partition函数代码示例

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


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

示例1: run

  async run() {
    this.logger.info(
      `Getting exams for all modules in ${this.academicYear} semester ${this.semester}`,
    );
    const term = getTermCode(this.semester, this.academicYear);

    // Make API requests to get the exam info
    let rawExams: ModuleExam[];
    try {
      rawExams = await cacheDownload(
        'exams',
        () => this.api.getTermExams(term),
        this.examCache,
        this.logger,
      );
    } catch (e) {
      throw new TaskError('Cannot get exam data', this, e);
    }

    // Try to filter out invalid exams
    const [validExams, invalidExams] = partition(rawExams, (exam) =>
      validateExam(exam, this.logger),
    );
    if (invalidExams.length > 0) {
      this.logger.warn({ invalidExams }, `Removed invalid exams`);
    }

    const exams = mapValues(keyBy(validExams, (exam) => exam.module), mapExamInfo);
    this.logger.info(`Downloaded ${rawExams.length} exams`);

    return exams;
  }
开发者ID:nusmodifications,项目名称:nusmods,代码行数:32,代码来源:GetSemesterExams.ts

示例2: setupEvents

  /**
   * create internal objects for the given events
   */
  setupEvents(events) {
    const parts = _.partition(events, 'isRegion');
    const regions = parts[0];
    events = parts[1];

    $.each(events, (index, event) => {
      const ve = new VisualEvent(event, this._buildDiv(event));
      this._events.push(ve);
    });

    $.each(regions, (index, event) => {
      const vre = new VisualEvent(event, this._buildRegDiv(event));
      this._events.push(vre);
    });

    this._events.sort((a, b) => {
      const ao = a.getOptions(),
        bo = b.getOptions();
      if (ao.min > bo.min) {
        return 1;
      }
      if (ao.min < bo.min) {
        return -1;
      }
      return 0;
    });
  }
开发者ID:CorpGlory,项目名称:grafana,代码行数:30,代码来源:jquery.flot.events.ts

示例3:

export function orderLinks<T extends NameAndType>(links: T[]) {
  const [provided, unknown] = partition<T>(links, isProvided);
  return [
    ...sortBy(provided, link => PROVIDED_TYPES.indexOf(link.type)),
    ...sortBy(unknown, link => link.name && link.name.toLowerCase())
  ];
}
开发者ID:SonarSource,项目名称:sonarqube,代码行数:7,代码来源:utils.ts

示例4: _getBlueprints

function _getBlueprints(positional:meow.ParsedValue[]):string[] {
  const result = _.partition(_.slice(positional, 0, -1), _isValidPackage);
  if (result[1].length) {
    const prettyNames = result[1].map(n => `'${n}'`).join(', ');
    throw new StacklessError(`The following blueprints are not valid npm package name(s): ${prettyNames}`);
  }

  return result[0].map(String);
}
开发者ID:convoyinc,项目名称:opine,代码行数:9,代码来源:cli.ts

示例5: validateTimetableModules

export function validateTimetableModules(
  timetable: SemTimetableConfig,
  moduleCodes: ModuleCodeMap,
): [SemTimetableConfig, ModuleCode[]] {
  const [valid, invalid] = partition(
    Object.keys(timetable),
    (moduleCode: ModuleCode) => moduleCodes[moduleCode],
  );
  return [pick(timetable, valid), invalid];
}
开发者ID:nusmodifications,项目名称:nusmods,代码行数:10,代码来源:timetables.ts

示例6:

      .map((matches:Array<Match>) => {
        console.log('bets @ partition matches by status');

        let matchesByStatusToPlay = _.partition(matches, (match:Match) => {
          return match.status === Status.TO_PLAY;
        });

        return {
          current: MatchHelper.groupMatchesByDay(matchesByStatusToPlay[0]),
          history: MatchHelper.groupMatchesByDayOrdered(matchesByStatusToPlay[1], {iteratees: ['timestamp'], orders: ['desc']})
        };
      })
开发者ID:ojacquemart,项目名称:ng2-euro-bets,代码行数:12,代码来源:matches.service.ts

示例7: sortPrefixFirst

export function sortPrefixFirst(array: any[], prefix?: string | number, property?: string): any[] {
  if (!prefix) {
    return array;
  }
  const lowerCasePrefix = ('' + prefix).toLowerCase();

  const partitions = partition(array, entry => {
    const value = ('' + (property ? entry[property] : entry)).toLowerCase();
    return value.startsWith(lowerCasePrefix);
  });
  return [...partitions[0], ...partitions[1]];
}
开发者ID:elastic,项目名称:kibana,代码行数:12,代码来源:sort_prefix_first.ts

示例8:

      .map((matches:Array<Match>) => {
        console.log('bets @ partition matches by status');

        let matchesByStatusToPlay = _.partition(matches, (match:Match) => {
          return match.status === Status.TO_PLAY;
        });

        return {
          current: MatchHelper.groupMatchesByDay(matchesByStatusToPlay[0]),
          history: MatchHelper.groupMatchesByDay(matchesByStatusToPlay[1])
        };
      })
开发者ID:arcava,项目名称:ng2-euro-bets,代码行数:12,代码来源:matches.service.ts

示例9: getBetterWorseOrders

export async function getBetterWorseOrders(db: Knex, augur: {}, params: t.TypeOf<typeof BetterWorseOrdersParams>): Promise<BetterWorseResult> {
  const ordersQuery = db("orders").select("orderId", "price").where({ orderState: "OPEN", ..._.pick(params, ["marketId", "outcome", "orderType"])});
  const orders: Array<OrderRow> = await ordersQuery;
  const priceBN = new BigNumber(params.price);
  const [lesserOrders, greaterOrders] = _.partition(orders, (order) => order.price.isLessThan(priceBN));
  const greaterOrder = _.reduce(greaterOrders, (result, order) => (result.orderId === null || order.price.isLessThan(result.price) ? order : result), { orderId: null, price: ZERO });
  const lesserOrder = _.reduce(lesserOrders, (result, order) => (result.orderId === null || order.price.isGreaterThan(result.price) ? order : result), { orderId: null, price: ZERO });
  if (params.orderType === "buy") {
    return {
      betterOrderId: greaterOrder.orderId,
      worseOrderId: lesserOrder.orderId,
    };
  } else {
    return {
      betterOrderId: lesserOrder.orderId,
      worseOrderId: greaterOrder.orderId,
    };
  }
}
开发者ID:AugurProject,项目名称:augur_node,代码行数:19,代码来源:get-better-worse-orders.ts

示例10: dedupAnnotations

export function dedupAnnotations(annotations) {
  let dedup = [];

  // Split events by annotationId property existance
  let events = _.partition(annotations, 'id');

  let eventsById = _.groupBy(events[0], 'id');
  dedup = _.map(eventsById, eventGroup => {
    if (eventGroup.length > 1 && !_.every(eventGroup, isPanelAlert)) {
      // Get first non-panel alert
      return _.find(eventGroup, event => {
        return event.eventType !== 'panel-alert';
      });
    } else {
      return _.head(eventGroup);
    }
  });

  dedup = _.concat(dedup, events[1]);
  return dedup;
}
开发者ID:connection-reset,项目名称:grafana,代码行数:21,代码来源:events_processing.ts

示例11: retry

    const requests = input.departments.map(async (department) => {
      try {
        const getModules = () =>
          this.api.getDepartmentModules(term, department.AcademicOrganisation);
        const modules = await retry(getModules, 3, (error) => error instanceof UnknownApiError);

        // Only return modules which are visible in the system
        const [printed, hidden] = partition(
          modules,
          (module: ModuleInfo) => module.PrintCatalog === 'Y',
        );

        this.logger.debug('Downloaded %i modules from %s', printed.length, department.Description);
        if (hidden.length > 0) {
          this.logger.debug('Filtered out %i non-print modules', hidden.length);
        }

        return printed;
      } catch (e) {
        this.logger.error(e, `Cannot get modules from ${department.Description}`);
        throw new TaskError(`Cannot get modules from ${department.Description}`, this, e);
      }
    });
开发者ID:nusmodifications,项目名称:nusmods,代码行数:23,代码来源:GetSemesterModules.ts

示例12: makeRegions

export function makeRegions(annotations, options) {
  let [regionEvents, singleEvents] = _.partition(annotations, 'regionId');
  let regions = getRegions(regionEvents, options.range);
  annotations = _.concat(regions, singleEvents);
  return annotations;
}
开发者ID:connection-reset,项目名称:grafana,代码行数:6,代码来源:events_processing.ts

示例13: handleMessage

  handleMessage({ content, player, timestamp}: ClientMessage<Player.GamePlayer>): Message[] {
    let responses: Message[] = [ Messaging.createEchoMessage(content, player) ];

    const component = Actions.getComponentByText(content);

    // if we received an action command message
    if (component) {
      const action = component.parse(content, player.character, timestamp);

      const { isValid, error } = component.validate(action, this);

      if (isValid) {
        player.character.nextAction = action;
        responses.push(Messaging.createGameMessage(`Next action: ${content}`, [ player ]));
      } else {
        responses.push(Messaging.createGameMessage(`Invalid action: ${error}`, [ player ]));
      }
    } else if (_.startsWith(content, '/')) {
      const messageNameSpan = Messaging.spanMessagePlayerNames(content, this.players);

      const toPlayers: Player.GamePlayer[] = [];

      if (_.startsWith(content, '/s ')) {
        this.getNearbyAnimals(player.character).forEach(animal => {
          // do we even need to send a message?
          if (Character.isPlayerCharacter(animal)) {
            // don't send a shout to the shouter!
            if (animal.playerId !== player.id) {
              const maybePlayer = this.getPlayer(animal.playerId);
              if (maybePlayer) {
                toPlayers.push(maybePlayer);
              } else {
                throw new Error(`Got a bad or missing id: ${animal.playerId}`);
              }
            }
          }
        });
      } else {
        messageNameSpan.names.forEach(name => {
          const maybePlayer = this.getPlayerByName(name);

          if (maybePlayer) {
            toPlayers.push(maybePlayer);
          } else {
            // do nothing
          }
        });
      }

      const [ yesComm, noComm ] = _.partition(toPlayers, otherPlayer => Player.canCommunicate(player, otherPlayer));

      const noCommMessage = 'something [CANNOT COMMUNICATE]';

      const restContent = messageNameSpan.rest;

      if (_.startsWith(content, '/t ')) {
        responses.push(Messaging.createTalkMessage(player, restContent, yesComm));
        responses.push(Messaging.createTalkMessage(player, noCommMessage, noComm));
      } else if (_.startsWith(content, '/s ')) {
        responses.push(Messaging.createShoutMessage(player, restContent, yesComm));
        responses.push(Messaging.createShoutMessage(player, noCommMessage, noComm));
      } else if (_.startsWith(content, '/w ')) {
        if (toPlayers.length) {
          if (yesComm.length) {
            const whisperContent = _.drop(content.split(' '), 2).join(' ');

            responses.push(Messaging.createWhisperMessage(player, whisperContent, _.head(yesComm)));
          }

          if (noComm.length) {
            responses.push(Messaging.createWhisperMessage(player, noCommMessage, _.head(noComm)));
          }
        }
      } else {
        responses.push(Messaging.createGameMessage(`Unknown communication: "${content}`, [ player ]));
      }
    } else {
      responses.push(Messaging.createGameMessage(`Unknown command or communication: "${content}"`, [ player ]));
    }
    return responses;
  }
开发者ID:zthomae,项目名称:xanadu,代码行数:81,代码来源:game.ts


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