Skip to content

Commit

Permalink
fix: enhance function expression
Browse files Browse the repository at this point in the history
  • Loading branch information
adyfk committed Oct 25, 2023
1 parent a9bb5ea commit 678cc6c
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
40 changes: 40 additions & 0 deletions src/createParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,46 @@ export function createParser(props: ExpressionParserConstructor = {}) {

return filteredItems;
},
unique: (state, items: any[], filterExpression?: string) => {
const filteredItems = items?.reduce(
(uniqueList: any[], item: any, index) => {
if (!filterExpression) {
if (uniqueList.includes(item)) return uniqueList;
return [...uniqueList, item]
} else {
const hasIncluded = uniqueList.some((uniqueItem) => {
const uniqueItemValue = parser.evaluate(
filterExpression,
{
...state.variables,
_item_: uniqueItem,
_index_: index
}
)
const currValue = parser.evaluate(
filterExpression,
{
...state.variables,
_item_: item,
_index_: index
}
)
return uniqueItemValue === currValue
})

if (hasIncluded) {
return uniqueList;
} else {
return [...uniqueList, item]
}
}
},
[]
);

return filteredItems;

}
}

parser.setFunctions(functions)
Expand Down
25 changes: 23 additions & 2 deletions src/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,40 @@ describe('example', () => {
})
it('array method', () => {
const parser = createParser();

expect(
parser.evaluate('unique(products)', {
products: [1, 1, 4, 5, 6, 6, 7, 7, 8, 8]
})
).toEqual([1, 4, 5, 6, 7, 8])

const products = [
{ name: 'Product 1', price: 150, quantity: 2 },
{ name: 'Product 2', price: 80, quantity: 0 },
{ name: 'Product 3', price: 200, quantity: 5 },
{ name: 'Product 4', price: 120, quantity: 1 },
{ name: 'Product 4', price: 120, quantity: 1 }
];
expect(
parser.evaluate('unique(products, "_item_.name")', {
products
})
).toEqual([
{ name: 'Product 1', price: 150, quantity: 2 },
{ name: 'Product 2', price: 80, quantity: 0 },
{ name: 'Product 3', price: 200, quantity: 5 },
{ name: 'Product 4', price: 120, quantity: 1 },
])

expect(
parser.evaluate('filter(products, "_item_.price > 100 and _item_.quantity > 0")', {
products
})
).toEqual([
{ name: 'Product 1', price: 150, quantity: 2 },
{ name: 'Product 3', price: 200, quantity: 5 },
{ name: 'Product 4', price: 120, quantity: 1 }
{ name: 'Product 4', price: 120, quantity: 1 },
{ name: 'Product 4', price: 120, quantity: 1 },
])

expect(
Expand All @@ -77,6 +97,7 @@ describe('example', () => {
'Product 2',
'Product 3',
'Product 4',
'Product 4',
])

expect(
Expand All @@ -99,7 +120,7 @@ describe('example', () => {
parser.evaluate('reduce(products, "_curr_ + _item_.price", 0)', {
products
})
).toBe(550)
).toBe(670)
})
it('object', () => {
const parser = createParser();
Expand Down

0 comments on commit 678cc6c

Please sign in to comment.