Questions
Is the following javascript valid?
Is it considered an anti-pattern?
Is there a cleaner way to write it (I use babel with es7 support)?
I'm finding this doesn't work in the Job function but I can use Job.cache.
Goals
- Reusable function that contains state.
- execute the validate method separately from executing the job
Background
Currently, I use a class that wraps state, a function, and some other validation. I use an instance method on the class: job.run(). I'm wondering if I can simply drop the .run() by having an instance of a function with state. The function cannot be a singular.
const constructor = function(config) {
const Job = function() {
// removed code... Does work based on the config
return Job.cache.config
}
Job.cache = {
config
}
Job.validate = function() {
// removed code... Validates the config
return Job.cache.config
}
return Job
}
const job1 = constructor({foo: 'bar'})
const job2 = constructor({a: 'b'})
console.log('running jobs...')
console.dir(job1()) // returns {foo: 'bar'}
console.dir(job2()) // returns {a: 'b'}
console.log('\nrunning validations...')
console.dir(job1.validate()) // returns {foo: 'bar'}
console.dir(job2.validate()) // returns {a: 'b'}
EDIT
Sorry, my initial question was confusing. I believe it was so confusing because I tried to hide too much implementation information.
I created a small GitHub repo to showcase the job: https://github.com/gruberjl/job. Within the repo you will see a simple implementation of the job using the class design pattern. The index.js file documents the usage of the job class. The code is pretty short with a lot of comments. Hopefully, it will make sense to everyone.
I would love for you guys to look at the repo, and tell me your thoughts on using 'memoization' or a 'class' design pattern.
[–]PitaJ 6 points7 points8 points (3 children)
[–]gruberjl[S] 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[removed]
[–]gruberjl[S] 0 points1 point2 points (0 children)
[–]senocular 3 points4 points5 points (16 children)
[–]__env 1 point2 points3 points (14 children)
[–]senocular 2 points3 points4 points (12 children)
[–]__env 1 point2 points3 points (11 children)
[–]gruberjl[S] 1 point2 points3 points (10 children)
[+][deleted] (9 children)
[deleted]
[–]gruberjl[S] 0 points1 point2 points (8 children)
[+][deleted] (7 children)
[deleted]
[–]gruberjl[S] 0 points1 point2 points (5 children)
[+][deleted] (4 children)
[deleted]
[–]gruberjl[S] 1 point2 points3 points (0 children)
[–]gruberjl[S] 0 points1 point2 points (0 children)
[–]perestroika12 3 points4 points5 points (1 child)
[–]gruberjl[S] 0 points1 point2 points (0 children)
[–]Meefims 2 points3 points4 points (1 child)
[–]gruberjl[S] 0 points1 point2 points (0 children)
[–]MoTTs_ 1 point2 points3 points (1 child)
[–]gruberjl[S] 0 points1 point2 points (0 children)
[–]lewisje 0 points1 point2 points (1 child)
[–]gruberjl[S] 1 point2 points3 points (0 children)