I'm writing a function to time how long it takes other functions to run. The code works with some functions, but not others.
When it fails, the errors are like:
Uncaught TypeError: this.query is not a function
I've found the documentation for .apply(), .bind(), and .call() which talk about changing this
. It seems like a solution is there, but I haven't been able to puzzle one out.
Here's a sample that demonstrates the issue. It's with lunr (via npm install -D lunr
) in an Electron app. It's running in the index.html browser page with electron setup to allow node integration on that part of the app. I'd make it more generic, but I don't know how.
const fs = require('fs')
const lunr = require('lunr')
const timeFunctionExecution = (func, args) => {
const t0 = performance.now()
const payload = func(args)
const t1 = performance.now()
const time = t1 - t0
const report = {
"payload": payload,
"time": time
}
return report
}
function createLunrSearchIndex(contentDir) {
const searchIndex = lunr(function () {
this.ref('filename')
this.field('content')
let fileList = fs.readdirSync(contentDir)
fileList.forEach(function(filename) {
let content = fs.readFileSync(`${contentDir}/${filename}`, 'utf8')
this.add(
{
'filename': filename,
'content': content
}
)
}, this)
})
return searchIndex
}
// This works and verifies the basic timer works
let report1 = timeFunctionExecution(createLunrSearchIndex, 'data')
console.log(report1)
// This works and verifies the search index works
let basicResults = report1.payload.search("chicken")
console.log(basicResults)
// Combine the two though, and it fails
let report2 = timeFunctionExecution(report1.payload.search, "chicken")
console.log(report2)
The first set of results from timeFunctionExecution
work if you call them directly, but when I pass it through the timeFunctionExecution
again, I get the error.
Inspecting the console.log(report1)
call shows the query function exists
basicResults
has valid data so .query()
would seem to be working in general but not when passed through the timing function.
Is there a way to pass functions like this while retaining the ability to call functions inside them (assuming that's the problem)?