-
Notifications
You must be signed in to change notification settings - Fork 13
/
factory.js
68 lines (59 loc) · 1.69 KB
/
factory.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const tags = require('html-tags')
let instances
/**
* Returns an element factory using the given createElement function.
* Adapted from `lib/create-x.js` in jxnblk's https://github.com/jxnblk/reaxe.
* Only tested with hyperscript. Not guaranteed to work with anything else.
*
* @param {Function} fn - createElement function
* @return {Function} - factory function with all HTML tag factories attached
*/
function createFactory (fn) {
function factory (tag) {
return function (props) {
return isObject(props)
? fn(tag, props, sliceKids(arguments, 1))
: fn(tag, sliceKids(arguments))
}
}
tags.forEach(function (tag) {
factory[tag] = factory(tag)
})
return factory
}
/**
* Return an element factory function, either by creating a new one or by
* getting a cached version
*
* @param {Function} fn - createElement function
* @return {Function} - factory function with all HTML tag factories attached
*/
function getFactory (fn) {
if (!instances) {
instances = new Map()
}
let factory = instances.get(fn)
if (factory) {
return factory
}
factory = createFactory(fn)
instances.set(fn, factory)
return factory
}
/**
* Turns arguments into an array, optionally slicing off a portion.
* @param {array} args - arguments object (array-like)
* @param {number} num - optional integer for Array.slice
* @return {array} - array of arguments
*/
function sliceKids (args, num) {
const arr = Array.prototype.slice.call(args, num)
return arr
}
function isObject (val) {
return val != null &&
typeof val === 'object' &&
Array.isArray(val) === false
}
module.exports.createFactory = createFactory
module.exports.getFactory = getFactory