简体   繁体   English

JS/TS 函数到 Dart 函数

[英]JS/TS func to Dart func

I want to convert it to dart code but I dnt understand ternary operator in that code我想将其转换为 dart 代码,但我不了解该代码中的三元运算符

const getPagination = (page, size) => {
  const limit = size ? +size : 3
  const from = page ? page * limit : 0
  const to = page ? from + size - 1 : size - 1

  return { from, to }
}

if you can tell me what code do line by line??如果你能告诉我一行一行的代码是什么?

A more idiomatic Dart implementation of the same code could be:相同代码的更惯用的 Dart 实现可能是:

Range getPagination([int page = 0, int size = 3]) {
  RangeError.checkNotNegative(page, "page");
  if (size <= 0) size = 3;
  var from = page * size;
  var to = from + size - 1;
  return Range(from, to);
}

class Range {
  final int from;
  final int to;
  Range(this.from, this.to);
}

This allows you to call with no arguments, but not with null as explicit argument.这允许您在没有 arguments 的情况下调用,但不能使用null作为显式参数。 So don't do that.所以不要那样做。

If you omit the size, the size is 3 .如果省略大小,则大小为3 That's more useful than finding a limit if size is null or 0 , but then use size anyway in the to computation, instead of limit .如果 size 是null0 ,这比找到一个限制更有用,但是to计算中无论如何都使用size而不是limit

Using a list of integers as a pair of integers is not the Dart way.使用整数列表作为一对整数不是 Dart 方式。 I'd create a class, like here, or wait for records and use a proper (int, int) tuple.我会像这里一样创建一个 class,或者等待记录并使用正确的(int, int)元组。

Dart lists, and maps, are much more expensive data structures than JavaScript "objects". Dart 列表和映射是比 JavaScript “对象”更昂贵的数据结构。 A small class is what corresponds to the anonymous object {from, to} in JavaScript.一个小的 class 对应于 JavaScript 中的匿名 object {from, to}

so I convert it by looking at TS play code所以我通过查看 TS 播放代码来转换它

void main() {
  List<int> getPagination(int? page, int? size) {
  int? limit = size ?? 3;
  int? from = page != null ? page * limit : 0;
  int? to = page != null ? (from + size!) - 1 : (size! - 1);

  return [from, to];
}
  print(getPagination(0, 10));
}

and its works thx to @blex及其作品感谢@blex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM