Peter Kellner
Peter Kellner

Reputation: 15478

Looking for a Cleaner Way To Make this Pagination Function in JavaScript

I want to write a method that takes in an offset and limit along with a passed in Array of objects. The objects always have an id column. I want to return a new Array with the result based on the offset and limit. Here is an example, followed by my implementation that I'm not happy with (too many fences and fence post like variables which are always error prone). Also, if limit == -1 then take the rest.

Maybe there is a better way with slice? Could reduce somehow help?

const baseArray = [{name: 'peter'},{name: 'terry'},{name: 'tammy'},{name: 'mary'}];
const offset = 1;
const limit = 2;
const speakerArray = getPaginatedData(baseArray,offset,limit);

speakerArray is [{name: 'terry',cursor: 'dGVycnk='},{name: 'tammy', cursor: 'dGFtbXk='];

where, the cursor's are calculated with this line of code:

console.log(Buffer.from('terry').toString("base64"));

Here is my implementation I don't like.

  const speakerArray = baseArray
    .filter((rec, index) => {
      return index > offset - 1 && (offset + limit > index || limit == -1);
    })
    .map((rec) => {
      rec.cursor = Buffer.from(rec.name.toString()).toString("base64");
      return rec;
    });

Upvotes: 1

Views: 1638

Answers (1)

AKX
AKX

Reputation: 168861

Well, the implementation with slice is

function getPaginatedData(array, offset, limit) {
  if(limit < 0) return array.slice(offset);
  return array.slice(offset, offset + limit);
}
const baseArray = [
  { name: "peter" },
  { name: "terry" },
  { name: "tammy" },
  { name: "mary" },
];
const offset = 1;
const limit = 2;
const speakerArray = getPaginatedData(baseArray, offset, limit);

Upvotes: 2

Related Questions