DEV Community

Discussion on: Decorators and Code Reuse

Collapse
lietux profile image
Janne "Lietu" Enberg • Edited on

I think these are some pretty poor examples of efficient decorator use.

A common actual use-case is caching:

function getItem(id) {
    console.log("Querying database for item " + id)
    return database.query({id: id}) // Any heavy operation
}

function cached(scope, fn) {
    var _cache = {};
    return function() {
        var key = JSON.stringify(arguments)
        if (!_cache[key]) {
            _cache[key] = fn.apply(scope, arguments)
        }

        return _cache[key]
    }   
}

itemCached = cached(undefined, getItem)

console.log(itemCached(1))
console.log(itemCached(2))
console.log(itemCached(1))

Another easy example I can think of is "promisifying" Node.js functions, i.e. changing the functions that take a callback function to use promises instead.

var fs = require('fs')

function promisify(scope, fn) {
    return function() {
        var args = Array.prototype.slice.apply(arguments)
        return new Promise(function(resolve, reject) {
            args.push(function(err, result) {
                if (err) {
                    reject(err)
                } else {
                    resolve(result)
                }
            })
            fn.apply(scope, args)
        })
    }   
}

var readFilePromise = promisify(fs, fs.readFile)
readFilePromise("test.json").then(function(result) {
    console.log(result.toString('utf8'))
}).catch(function(err) {
    throw err
})