I’m using the Simple Books API to practice composing tests in Postman.
[
{
"id": 1,
"name": "The Russian",
"type": "fiction",
"available": true
},
{
"id": 2,
"name": "Just as I Am",
"type": "non-fiction",
"available": false
},
{
"id": 3,
"name": "The Vanishing Half",
"type": "fiction",
"available": true
},
{
"id": 4,
"name": "The Midnight Library",
"type": "fiction",
"available": true
}
]
Almost every filter example I’ve seen relies on a hard-coded attribute equalling a hard-coded value.
let response = pm.response.json();
let nonfiction_books = response.filter( (book) => book['available'] === true )
Is there any way I can abstract that filter body out to a reusable function? How would I use it?
function check_key_value(json_, key, value)
{
json_[key] === value;
}
let books_available = response.filter( ? )
Not clear to me, maybe you could wrap filter in a function?
const myFilter = (array, key, value)=> array
.filter(obj=>obj[key]===value)
For example
myF(a,"available",true)
//returns
[
{ id: 1, name: 'The Russian',
type: 'fiction', available: true },
{
id: 3,
name: 'The Vanishing Half',
type: 'fiction',
available: true
},
{
id: 4,
name: 'The Midnight Library',
type: 'fiction',
available: true
}
]
Thanks. I had to rewrite it so I could use it.
function select_key_value(array, key, value)
{
return array.filter( (obj) => obj[key]===value );
}
let books_available = select_key_value(response, 'available', true);
What is the functional difference between the const and the function definitions? Are const’s like lambdas?
If I get the question these are the basic differences…
Named and unnamed function expressions (FE)
Named FE can be executed before definition
hello() // logs hello!
function hello(){
console.log('hello')
}
hello()//also logs
Unnamed FE (anonymous function)
They won’t be available before definition.
result(1,2) //error
let result = function (p1,p2) {console.log(p1*p2)}
result(1,2)
They can be executed automatically IIFE (immediately executed function expression) :
let result = (function (p1,p2) {return 1*2})(1,2)
console.log(result) // 2
So those are functions called with function keyword, named and unnamed.
Arrow functions are always anonymous, and a compact version of an anonymous function. They look nice but have some limitations.
let arrowResult = (p1,p2) => p1*p2
system
Closed
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.