[6a3a178] | 1 | 'use strict'
|
---|
| 2 |
|
---|
| 3 | var test = require('tape')
|
---|
| 4 | var reusify = require('./')
|
---|
| 5 |
|
---|
| 6 | test('reuse objects', function (t) {
|
---|
| 7 | t.plan(6)
|
---|
| 8 |
|
---|
| 9 | function MyObject () {
|
---|
| 10 | t.pass('constructor called')
|
---|
| 11 | this.next = null
|
---|
| 12 | }
|
---|
| 13 |
|
---|
| 14 | var instance = reusify(MyObject)
|
---|
| 15 | var obj = instance.get()
|
---|
| 16 |
|
---|
| 17 | t.notEqual(obj, instance.get(), 'two instance created')
|
---|
| 18 | t.notOk(obj.next, 'next must be null')
|
---|
| 19 |
|
---|
| 20 | instance.release(obj)
|
---|
| 21 |
|
---|
| 22 | // the internals keeps a hot copy ready for reuse
|
---|
| 23 | // putting this one back in the queue
|
---|
| 24 | instance.release(instance.get())
|
---|
| 25 |
|
---|
| 26 | // comparing the old one with the one we got
|
---|
| 27 | // never do this in real code, after release you
|
---|
| 28 | // should never reuse that instance
|
---|
| 29 | t.equal(obj, instance.get(), 'instance must be reused')
|
---|
| 30 | })
|
---|
| 31 |
|
---|
| 32 | test('reuse more than 2 objects', function (t) {
|
---|
| 33 | function MyObject () {
|
---|
| 34 | t.pass('constructor called')
|
---|
| 35 | this.next = null
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | var instance = reusify(MyObject)
|
---|
| 39 | var obj = instance.get()
|
---|
| 40 | var obj2 = instance.get()
|
---|
| 41 | var obj3 = instance.get()
|
---|
| 42 |
|
---|
| 43 | t.notOk(obj.next, 'next must be null')
|
---|
| 44 | t.notOk(obj2.next, 'next must be null')
|
---|
| 45 | t.notOk(obj3.next, 'next must be null')
|
---|
| 46 |
|
---|
| 47 | t.notEqual(obj, obj2)
|
---|
| 48 | t.notEqual(obj, obj3)
|
---|
| 49 | t.notEqual(obj3, obj2)
|
---|
| 50 |
|
---|
| 51 | instance.release(obj)
|
---|
| 52 | instance.release(obj2)
|
---|
| 53 | instance.release(obj3)
|
---|
| 54 |
|
---|
| 55 | // skip one
|
---|
| 56 | instance.get()
|
---|
| 57 |
|
---|
| 58 | var obj4 = instance.get()
|
---|
| 59 | var obj5 = instance.get()
|
---|
| 60 | var obj6 = instance.get()
|
---|
| 61 |
|
---|
| 62 | t.equal(obj4, obj)
|
---|
| 63 | t.equal(obj5, obj2)
|
---|
| 64 | t.equal(obj6, obj3)
|
---|
| 65 | t.end()
|
---|
| 66 | })
|
---|