Skip to content

Commit

Permalink
Adds getCollectionItemIndex universal filter.
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Dec 6, 2022
1 parent 010bfd0 commit 7c935a4
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Filters/GetCollectionItemIndex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = function getCollectionItemIndex(collection, page) {
if (!page) {
page = this.page || this.ctx?.page || this.context?.environments?.page;
}

let j = 0;
for (let item of collection) {
if (
item.inputPath === page.inputPath &&
(item.outputPath === page.outputPath || item.url === page.url)
) {
return j;
}
j++;
}
};
8 changes: 8 additions & 0 deletions src/defaultConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const serverlessUrlFilter = require("./Filters/ServerlessUrl");
const slugFilter = require("./Filters/Slug");
const slugifyFilter = require("./Filters/Slugify");
const getLocaleCollectionItem = require("./Filters/GetLocaleCollectionItem");
const getCollectionItemIndex = require("./Filters/GetCollectionItemIndex");

module.exports = function (config) {
let templateConfig = this;
Expand All @@ -23,6 +24,13 @@ module.exports = function (config) {

config.addFilter("serverlessUrl", serverlessUrlFilter);

config.addFilter(
"getCollectionItemIndex",
function (collection, pageOverride) {
return getCollectionItemIndex.call(this, collection, pageOverride);
}
);

config.addFilter(
"getCollectionItem",
function (collection, pageOverride, langCode) {
Expand Down
30 changes: 30 additions & 0 deletions test/GetCollectionItemIndexTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const test = require("ava");
const getCollectionItemIndex = require("../src/Filters/GetCollectionItemIndex");

test("getCollectionItemIndex", (t) => {
let first = {
inputPath: "hello.md",
outputPath: "/hello/",
};
let second = {
inputPath: "hello2.md",
outputPath: "/hello2/",
};
let third = {
inputPath: "hello3.md",
outputPath: "/hello3/",
};
let collections = [first, second, third];

t.deepEqual(getCollectionItemIndex(collections, first), 0);
t.deepEqual(getCollectionItemIndex(collections, second), 1);
t.deepEqual(getCollectionItemIndex(collections, third), 2);

t.deepEqual(
getCollectionItemIndex(collections, {
inputPath: "unknown.md",
outputPath: "/unknown/",
}),
undefined
);
});

0 comments on commit 7c935a4

Please sign in to comment.