@lumjs/core 1.0.0-beta.6 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,8 +15,9 @@ The documentation is written in [JSDoc 3](https://jsdoc.app/) format.
15
15
  You can compile the documentation using `npm run build-docs`
16
16
  which will put the generated docs into the `./docs/api` folder.
17
17
 
18
- ### [Changelog](./docs/changelogs/1.0-beta.md)
18
+ ### [Changelog](./docs/changelogs/1.x.md)
19
19
  ### [TODO](TODO.md)
20
+ ### [Homepage](https://supernovus.github.io/)
20
21
 
21
22
  ## Official URLs
22
23
 
@@ -6,12 +6,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.1.1] - 2022-08-02
10
+ ### Fixed
11
+ - A couple missing constants in some functions.
12
+
13
+ ## [1.1.0] - 2022-07-29
14
+ ### Added
15
+ - `types.doesDescriptorTemplate()` method.
16
+ - `obj.getProperty()` method (used to be in the `descriptors` sub-module.)
17
+ ### Changed
18
+ - Tweaked documentation for:
19
+ - `obj.getObjectPath()`
20
+ - `obj.setObjectPath()`
21
+ - `obj.getNamespace()`
22
+ - `obj.setNamespace()`
23
+ - Updated error messages in `obj.setObjectPath()`
24
+ - Made `obj.setObjectPath()` use `types.doesDescriptorTemplate()` for validation of `opts.desc` option.
25
+ - Changed `obj.getObjectPath()` and `obj.setObjectPath()` to support `function` parent objects.
26
+ - Enhanced `types.stringify()` to support `RegExp` as well as supporting custom extensions down the road.
27
+
9
28
  ## [1.0.0] - 2022-07-27
10
29
  ### Changed
11
30
  - Initial *stable* release.
12
31
  - See [1.0-beta.md](1.0-beta.md) for the beta versions of `1.0`
13
32
  - See [lum.js](https://github.com/supernovus/lum.js) for the original library this is replacing.
14
33
 
15
- [Unreleased]: https://github.com/supernovus/lum.core.js/compare/v1.0.0...HEAD
34
+ [Unreleased]: https://github.com/supernovus/lum.core.js/compare/v1.1.1...HEAD
35
+ [1.1.1]: https://github.com/supernovus/lum.core.js/compare/v1.1.0...v1.1.1
36
+ [1.1.0]: https://github.com/supernovus/lum.core.js/compare/v1.0.0...v1.1.0
16
37
  [1.0.0]: https://github.com/supernovus/lum.core.js/releases/tag/v1.0.0
17
38
 
package/lib/arrays.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Array helper functions.
3
- * @module module:@lumjs/core/arrays
3
+ * @module @lumjs/core/arrays
4
4
  */
5
5
 
6
6
  /**
@@ -0,0 +1,38 @@
1
+ const types = require('../types');
2
+ const {isComplex,isObj} = types;
3
+
4
+ /**
5
+ * Get a property descriptor.
6
+ *
7
+ * This is like `Object.getOwnPropertyDescriptor`, except that method
8
+ * fails if the property is inhereted. This method will travel through
9
+ * the entire prototype chain until it finds the descriptor.
10
+ *
11
+ * @param {object|function} obj - Object to find a property in.
12
+ * @param {string} prop - Name of the property we want the descriptor of.
13
+ * @param {mixed} [defval] The fallback value if no descriptor is found.
14
+ *
15
+ * @returns {mixed} - The descriptor if found, `defval` if not.
16
+ */
17
+ function getProperty(obj, prop, defval)
18
+ {
19
+ if (!isComplex(obj)) throw new TypeError("Target must be an object or function");
20
+ // Yeah it looks like an infinite loop, but it's not.
21
+ while (true)
22
+ {
23
+ const desc = Object.getOwnPropertyDescriptor(obj, prop);
24
+ if (isObj(desc))
25
+ { // Found it.
26
+ return desc;
27
+ }
28
+
29
+ // Didn't find it, so let's try the next object in the prototype chain.
30
+ obj = Object.getPrototypeOf(obj);
31
+ if (!isComplex(obj))
32
+ { // We've gone as far up the prototype chain as we can, bye now!
33
+ return defval;
34
+ }
35
+ }
36
+ }
37
+
38
+ module.exports = getProperty;
package/lib/obj/index.js CHANGED
@@ -9,6 +9,7 @@ const {CLONE,clone,addClone,cloneIfLocked} = require('./clone');
9
9
  const {lock,addLock} = require('./lock');
10
10
  const {mergeNested,syncNested} = require('./merge');
11
11
  const ns = require('./ns');
12
+ const getProperty = require('./getproperty');
12
13
  const
13
14
  {
14
15
  getObjectPath,setObjectPath,
@@ -20,4 +21,5 @@ module.exports =
20
21
  CLONE, clone, addClone, cloneIfLocked, lock, addLock,
21
22
  mergeNested, syncNested, copyProps, copyAll, ns,
22
23
  getObjectPath, setObjectPath, getNamespace, setNamespace,
24
+ getProperty,
23
25
  }
package/lib/obj/ns.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // Import required bits here.
2
2
  const
3
3
  {
4
- B, root, isObj, needObj, def, nonEmptyArray, notNil
4
+ B, S,
5
+ root, isObj, needObj, def, nonEmptyArray, notNil,
6
+ doesDescriptorTemplate,
5
7
  } = require('../types');
6
8
 
7
9
  /**
@@ -75,16 +77,20 @@ exports.nsArray = nsArray;
75
77
  /**
76
78
  * Get a (nested) property from an object with a given path.
77
79
  *
78
- * @param {object} obj - Object we're looking in.
80
+ * @param {(object|function)} obj - Object we're looking in.
79
81
  * @param {(string|Array)} proppath - Property path we're looking for.
80
82
  * Generally a string of dot (`.`) separated nested property names.
81
- * @param {object} [opts] TBD.
83
+ * @param {(object|boolean)} [opts] Options changing the behaviours.
84
+ * If this is a `boolean` it's assumed to be the `opts.log` option.
85
+ * @param {boolean} [opts.log=false] Log errors for missing namespaces?
86
+ * @param {*} [opts.default] A default value if the namespace is not found.
87
+ *
82
88
  * @return {*} The property if found, or `opts.default` if not.
83
89
  * @alias module:@lumjs/core/obj.getObjectPath
84
90
  */
85
91
  function getObjectPath(obj, proppath, opts={})
86
92
  {
87
- needObj(obj);
93
+ needObj(obj, true);
88
94
 
89
95
  if (typeof opts === B)
90
96
  opts = {log: opts};
@@ -116,20 +122,32 @@ exports.getObjectPath = getObjectPath;
116
122
  /**
117
123
  * Create a nested property path if it does not exist.
118
124
  *
119
- * @param {object} obj - Object the property path is for.
125
+ * @param {(object|function)} obj - Object the property path is for.
120
126
  * @param {(string|Array)} proppath - Property path to create.
121
- * @param {object} [opts] TBD.
122
- * @return {*} Generally the last object in the nested path.
123
- * However the output may vary depending on the options.
127
+ * @param {object} [opts] Options changing the behaviours.
128
+ * @param {*} [opts.value] A value to assign to the last property path.
129
+ * @param {boolean} [opts.overwrite=false] Allow overwriting property paths.
130
+ * Only applicable if `opts.value` was also specified.
131
+ * @param {object} [opts.desc] Descriptor rules for defining the properties.
132
+ * Must NOT contain `value`, `get`, or `set` properties.
133
+ * Only, `configurable`, `enumerable`, and `writable` are supported.
134
+ * Will be ignored if `opts.assign` is `true`.
135
+ * @param {boolean} [opts.assign=false] Use direct assignment instead of `def()`.
136
+ * @param {boolean} [opts.returnThis=false] Return `this` variable.
137
+ * @param {boolean} [opts.returnObj=false] Return the `obj` parameter.
138
+ * @return {*} Generally the last object in the nested property paths.
139
+ * Unless one of `opts.returnThis` or `opts.returnObj` was `true`.
124
140
  * @alias module:@lumjs/core/obj.setObjectPath
125
141
  */
126
142
  function setObjectPath(obj, proppath, opts={})
127
143
  {
128
- needObj(obj); needObj(opts);
144
+ needObj(obj, true, 'obj parameter must be an object or function');
145
+ needObj(opts, 'opts parameter must be an object');
146
+
129
147
  proppath = nsArray(proppath);
130
148
 
131
149
  let assign;
132
- if (isObj(opts.desc))
150
+ if (doesDescriptorTemplate(opts.desc))
133
151
  { // An explicit descriptor.
134
152
  assign = (o,p,v={}) =>
135
153
  {
@@ -218,8 +236,7 @@ exports.getNamespace = getNamespace;
218
236
  *
219
237
  * @param {(string|Array)} proppath - Property path to create.
220
238
  * @param {object} [opts] See `setObjectPath()` for details.
221
- * @return {*} Generally the last object in the nested path.
222
- * However the output may vary depending on the options.
239
+ * @return {*} See `setObjectPath()` for details.
223
240
  * @alias module:@lumjs/core/obj.setNamespace
224
241
  * @see module:@lumjs/core/obj.setObjectPath
225
242
  */
package/lib/opt.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * @module @lumjs/core/opt
4
4
  */
5
5
 
6
- const {U,needObj,needType} = require('./types');
6
+ const {U,F,S,needObj,needType} = require('./types');
7
7
 
8
8
  /**
9
9
  * See if a value is *set*, and if not, return a default value.
@@ -104,16 +104,16 @@ function isProperty(v)
104
104
  }
105
105
 
106
106
  /**
107
- * See if an object can be used as a valid descriptor.
107
+ * See if an object can be used as a valid *descriptor*.
108
108
  *
109
- * Basically in order to be considered a valid descriptor,
109
+ * Basically in order to be considered a valid *descriptor*,
110
110
  * one of the the following sets of rules must be true:
111
111
  *
112
- * - A Data Descriptor:
112
+ * - A *Data descriptor*:
113
113
  * - Has a `value` property.
114
114
  * - Does not have a `get` property.
115
115
  * - Does not have a `set` property.
116
- * - An Accessor Descriptor:
116
+ * - An *Accessor descriptor*:
117
117
  * - Has a `get` and/or `set` property.
118
118
  * - Does not have a `value` property.
119
119
  * - Does not have a `writable` property.
@@ -145,10 +145,56 @@ function isProperty(v)
145
145
  return false;
146
146
  }
147
147
 
148
- // Now export those.
149
- module.exports =
150
- {
151
- isObj, isComplex, isNil, notNil, isScalar, isArray, isTypedArray,
152
- nonEmptyArray, isArguments, isProperty, doesDescriptor,
153
- }
154
-
148
+ /**
149
+ * See if an object can be used as a valid *descriptor template*.
150
+ *
151
+ * This is similar to `doesDescriptor`, except that a *template*
152
+ * **must not** contain `value`, `get` or `set` properties.
153
+ *
154
+ * @param {object} obj - The object we are testing.
155
+ * @param {boolean} [accessor=false] Template is for an Accessor.
156
+ * If this is `true` then the `writable` property will also be forbidden.
157
+ * @param {boolean} [strict=true] Only allow valid descriptor properties.
158
+ * If this is `true` then **only** allow `configurable`, `enumerable`, and
159
+ * conditionally `writable` (only if `accessor` is `false`.)
160
+ * If this is `false` then any unknown properties will be ignored.
161
+ *
162
+ * @returns {boolean} Is the object a valid descriptor template?
163
+ * @alias module:@lumjs/core/types.doesDescriptorTemplate
164
+ */
165
+ function doesDescriptorTemplate(obj, accessor=false, strict=true)
166
+ {
167
+ if (!isObj(obj)) return false;
168
+
169
+ // Get a list of enumerable properties in the object.
170
+ const props = Object.keys(obj);
171
+
172
+ if (strict)
173
+ { // Strict enforcement, only valid descriptor properties allowed.
174
+ const valid = ['configurable', 'enumerable'];
175
+ if (!accessor) valid.push('writable');
176
+ for (const prop of props)
177
+ {
178
+ if (!valid.includes(prop)) return false;
179
+ }
180
+ }
181
+ else
182
+ { // Loose enforcement mode, reject on forbidden properties only.
183
+ const forbidden = ['value','get','set'];
184
+ if (accessor) forbidden.push('writable');
185
+ for (const prop of props)
186
+ {
187
+ if (forbidden.includes(prop)) return false;
188
+ }
189
+ }
190
+
191
+ // No tests failed, this can be used as a template.
192
+ return true;
193
+ }
194
+
195
+ // Now export those.
196
+ module.exports =
197
+ {
198
+ isObj, isComplex, isNil, notNil, isScalar, isArray, isTypedArray,
199
+ nonEmptyArray, isArguments, isProperty, doesDescriptor, doesDescriptorTemplate,
200
+ }
@@ -24,6 +24,7 @@ const
24
24
  {
25
25
  isObj, isComplex, isNil, notNil, isScalar, isArray, isTypedArray,
26
26
  nonEmptyArray, isArguments, isProperty, doesDescriptor,
27
+ doesDescriptorTemplate,
27
28
  } = require('./basics');
28
29
 
29
30
  // Root namespace helpers.
@@ -49,6 +50,7 @@ module.exports =
49
50
  isObj, isComplex, isNil, notNil, isScalar, isArray, isTypedArray,
50
51
  nonEmptyArray, isArguments, isProperty, doesDescriptor,
51
52
  isInstance, isType, isa, needObj, needType, needs, stringify,
53
+ doesDescriptorTemplate,
52
54
  }
53
55
 
54
56
  // Last but not least, this will be the module for TYPES.add()
@@ -1,8 +1,11 @@
1
1
  // Get the extended type list.
2
2
  const TYPES = require('./typelist');
3
3
  const {isObj, isArray, isTypedArray} = require('./basics');
4
+ const def = require('./def');
4
5
 
5
- const TOSTRING = [TYPES.F, TYPES.SY];
6
+ const TOSTRING_TYPES = [TYPES.F, TYPES.SY];
7
+ const TOSTRING_INSTANCES = [RegExp];
8
+ const CUSTOM = [];
6
9
 
7
10
  /**
8
11
  * Stringify a Javascript value.
@@ -30,69 +33,110 @@ const TOSTRING = [TYPES.F, TYPES.SY];
30
33
  function stringify (what, recurse=1, addNew=false)
31
34
  {
32
35
  const whatType = typeof what;
33
- if (TOSTRING.includes(whatType)) return what.toString();
34
36
 
35
- // A few formatting helpers used below.
37
+ for (const test of CUSTOM)
38
+ { // If there are custom extensions, we check them first.
39
+ const ret = test.call({stringify}, what, recurse, addNew);
40
+ if (typeof ret === TYPES.S)
41
+ { // The extension processed the item.
42
+ return ret;
43
+ }
44
+ }
36
45
 
37
- const classname = () => (addNew ? 'new ' : '') + what.constructor.name;
38
- const construct = val => `${classname()}(${val})`;
39
- const reconstruct = val => construct(stringify(val,recurse,addNew));
40
- const arrayish = vals => reconstruct(Array.from(vals));
46
+ // A few types we simply stringify right now.
47
+ if (TOSTRING_TYPES.includes(whatType)) return what.toString();
41
48
 
42
- if (isTypedArray(what))
43
- { // This one is pretty simple.
44
- return construct(what.toString());
45
- }
46
-
47
- if (what instanceof Map)
48
- {
49
- return arrayish(what.entries());
50
- }
51
-
52
- if (what instanceof Set)
53
- {
54
- return arrayish(what.values());
55
- }
49
+ if (isObj(what))
50
+ { // We support a few kinds of objects.
56
51
 
57
- if (what instanceof Error)
58
- {
59
- return construct(what.message);
60
- }
61
-
62
- if (recurse && isObj(what))
63
- { // Recursion mode enabled.
64
- let out = '';
65
- if (isArray(what))
66
- { // Stringify an array.
67
- out = '[';
68
- out += what.map(item => stringify(item, recurse-1, addNew)).join(',');
69
- out += ']';
70
- }
71
- else
72
- { // Stringify a plain object.
73
- out = '{';
74
- function add(key, pre='')
52
+ // Any class instance that we can simply call `toString()` on, let's do that.
53
+ for (const aClass of TOSTRING_INSTANCES)
54
+ {
55
+ if (what instanceof aClass)
75
56
  {
76
- out += `${pre}${key}:${stringify(what[key], recurse-1, addNew)}`
57
+ return what.toString();
77
58
  }
78
- const keys = Object.keys(what);
79
- //console.debug("keys!", keys);
80
- if (keys.length > 0)
81
- { // Let's add the first key, then all subsequent keys.
82
- add(keys.shift());
83
- for (const key of keys)
59
+ }
60
+
61
+ // A few formatting helpers used below.
62
+ const classname = () => (addNew ? 'new ' : '') + what.constructor.name;
63
+ const construct = val => `${classname()}(${val})`;
64
+ const reconstruct = val => construct(stringify(val,recurse,addNew));
65
+ const arrayish = vals => reconstruct(Array.from(vals));
66
+
67
+ if (isTypedArray(what))
68
+ { // This one is pretty simple.
69
+ return construct(what.toString());
70
+ }
71
+
72
+ if (what instanceof Map)
73
+ {
74
+ return arrayish(what.entries());
75
+ }
76
+
77
+ if (what instanceof Set)
78
+ {
79
+ return arrayish(what.values());
80
+ }
81
+
82
+ if (what instanceof Error)
83
+ {
84
+ return `${what.name}(${JSON.stringify(what.message)})`;
85
+ }
86
+
87
+ if (recurse)
88
+ { // Recursion mode enabled.
89
+ let out = '';
90
+ if (isArray(what))
91
+ { // Stringify an array.
92
+ out = '[';
93
+ out += what.map(item => stringify(item, recurse-1, addNew)).join(',');
94
+ out += ']';
95
+ }
96
+ else
97
+ { // Stringify a plain object.
98
+ out = '{';
99
+ function add(key, pre='')
84
100
  {
85
- add(key, ',');
101
+ out += `${pre}${key}:${stringify(what[key], recurse-1, addNew)}`
102
+ }
103
+ const keys = Object.keys(what);
104
+ //console.debug("keys!", keys);
105
+ if (keys.length > 0)
106
+ { // Let's add the first key, then all subsequent keys.
107
+ add(keys.shift());
108
+ for (const key of keys)
109
+ {
110
+ add(key, ',');
111
+ }
86
112
  }
113
+ out += '}';
87
114
  }
88
- out += '}';
115
+ return out;
89
116
  }
90
- return out;
91
- }
92
- else
93
- { // If we reached here, there's no special methods, use JSON.
94
- return JSON.stringify(what);
95
- }
117
+
118
+ } // if isObj
119
+
120
+ // If we reached here, there's no special methods, use JSON.
121
+ return JSON.stringify(what);
96
122
  }
97
123
 
124
+ // Add a custom extension.
125
+ def(stringify, '$extend',
126
+ function(func, registration=false)
127
+ {
128
+ if (typeof func === TYPES.F)
129
+ {
130
+ if (registration)
131
+ { // Using the function to register custom behaviour.
132
+ func.call({stringify, TOSTRING_INSTANCES, TOSTRING_TYPES}, CUSTOM);
133
+ }
134
+ else
135
+ { // The function is a custom test.
136
+ CUSTOM.push(func);
137
+ }
138
+ }
139
+ });
140
+
141
+ // Export it.
98
142
  module.exports = stringify;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lumjs/core",
3
- "version": "1.0.0-beta.6",
3
+ "version": "1.1.1",
4
4
  "main": "lib/index.js",
5
5
  "exports":
6
6
  {
@@ -26,8 +26,7 @@
26
26
  },
27
27
  "devDependencies":
28
28
  {
29
- "@lumjs/tests": "^1.0.0",
30
- "jsdoc": "^3.6.10"
29
+ "@lumjs/tests": "^1.3.0"
31
30
  },
32
31
  "scripts":
33
32
  {