Home > Blockchain >  JS/TS func to Dart func
JS/TS func to Dart func

Time:09-14

I want to convert it to dart code but I dnt understand ternary operator in that code

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 ??

CodePudding user response:

A more idiomatic Dart implementation of the same code could be:

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. So don't do that.

If you omit the size, the size is 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.

Using a list of integers as a pair of integers is not the Dart way. I'd create a class, like here, or wait for records and use a proper (int, int) tuple.

Dart lists, and maps, are much more expensive data structures than JavaScript "objects". A small class is what corresponds to the anonymous object {from, to} in JavaScript.

CodePudding user response:

so I convert it by looking at TS play code

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

  • Related