带有coffescript语法的JavaScript-if条件:优化if语句结构

时间:2018-10-04 16:24:24

标签: javascript function if-statement coffeescript

我有一个函数,正在测试4个变量,我想优化if语句测试的结构,有什么可以帮助的吗? :

$scope.filterActivated = ->
    if $scope.postParams.options.scopes.report.from || $scope.postParams.options.scopes.report.to || $scope.postParams.options.template_id || $scope.displayOptions.query.length > 0
      return true
    else
      return false

2 个答案:

答案 0 :(得分:2)

您可以删除true/false并对其进行优化,如下所示:

$scope.filterActivated = ->
  options = $scope.postParams.options
  options.scopes.report.from or options.scopes.report.to or options.template_id or $scope.displayOptions.query.length > 0

编辑:适合您的JS:

$scope.filterActivated = () => {
  let options = $scope.postParams.options;
  return options.scopes.report.from || options.scopes.report.to || options.template_id || $scope.displayOptions.query.length > 0;
};

答案 1 :(得分:0)

不确定优化的含义,但是它的简写可能是:

const data$: Observable<any> = this.getAllOrdersIds().pipe(
    mergeMap((orderIds: string[]) => this.otherMethodReturningObservable(orderIds))
);

data$.subscribe(data => {
    // do something with combined data...
});

编辑:

最初,我使用三元语法,但是CoffeeScript不支持这种语法。供参考Ternary operation in CoffeeScript

编辑2:

将其减少一些,@ user633183建议使用$scope.filterActivated = -> $scope.postParams.options.scopes.report.from || $scope.postParams.options.scopes.report.to || $scope.postParams.options.template_id || $scope.displayOptions.query.length; ,但我认为这样做的结果相同。