aneka 0.4.0 → 0.6.0

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/CHANGES.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changes
2
2
 
3
+ ## 2025-12-13
4
+
5
+ - [0.6.0] Export functions as named export as well as default export
6
+ - [0.6.0] Add ```setImmediate()```
7
+ - [0.6.0] Add ```formatText()```
8
+ - [0.6.0] Add ```resolvePath()```
9
+ - [0.6.0] Add ```parseEnv()```
10
+ - [0.6.0] Add ```parseArgsArgv()```
11
+ - [0.6.0] Add ```parseDuration()```
12
+
13
+ ## 2025-12-11
14
+
15
+ - [0.5.0] Add ```mergeObjectsByKey(inputs, key)```
16
+
3
17
  ## 2025-12-10
4
18
 
5
19
  - [0.3.0] Add ```filterIndex(inputs, matcher)```
package/index.js CHANGED
@@ -14,13 +14,54 @@ import paginate from './src/paginate.js'
14
14
  import pascalCase from './src/pascal-case.js'
15
15
  import round from './src/round.js'
16
16
  import secToHms from './src/sec-to-hms.js'
17
+ import setImmediate from './src/set-immediate.js'
17
18
  import titleize from './src/titleize.js'
19
+ import mergeObjectsByKey from './src/merge-objects-by-key.js'
20
+ import formatText from './src/format-text.js'
21
+ import resolvePath from './src/resolve-path.js'
22
+ import shim from './src/shim.js'
23
+ import currentLoc from './src/current-loc.js'
24
+ import parseArgsArgv from './src/parse-args-argv.js'
25
+ import parseEnv from './src/parse-env.js'
26
+ import parseDuration from './src/parse-duration.js'
27
+
28
+ export {
29
+ arrangeArray,
30
+ currentLoc,
31
+ defaultsDeep,
32
+ delay,
33
+ extractText,
34
+ formatText,
35
+ filterDuplicate,
36
+ filterIndex,
37
+ getIndex,
38
+ getKeyByValue,
39
+ includes,
40
+ isClass,
41
+ isSet,
42
+ log,
43
+ logError,
44
+ mergeObjectsByKey,
45
+ paginate,
46
+ parseArgsArgv,
47
+ parseDuration,
48
+ parseEnv,
49
+ pascalCase,
50
+ resolvePath,
51
+ round,
52
+ secToHms,
53
+ setImmediate,
54
+ shim,
55
+ titleize
56
+ }
18
57
 
19
58
  export default {
20
59
  arrangeArray,
60
+ currentLoc,
21
61
  defaultsDeep,
22
62
  delay,
23
63
  extractText,
64
+ formatText,
24
65
  filterDuplicate,
25
66
  filterIndex,
26
67
  getIndex,
@@ -30,9 +71,15 @@ export default {
30
71
  isSet,
31
72
  log,
32
73
  logError,
74
+ mergeObjectsByKey,
33
75
  paginate,
76
+ parseArgsArgv,
77
+ parseDuration,
78
+ parseEnv,
34
79
  pascalCase,
80
+ resolvePath,
35
81
  round,
36
82
  secToHms,
83
+ shim,
37
84
  titleize
38
85
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aneka",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Some usefull function helper for daily use",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -23,8 +23,13 @@
23
23
  },
24
24
  "homepage": "https://github.com/ardhi/aneka#readme",
25
25
  "dependencies": {
26
+ "dotenv": "^17.2.3",
27
+ "dotenv-parse-variables": "^2.0.0",
28
+ "flat": "^6.0.1",
26
29
  "lodash-es": "^4.17.21",
27
- "sprintf-js": "^1.1.3"
30
+ "ms": "^2.1.3",
31
+ "sprintf-js": "^1.1.3",
32
+ "yargs": "^18.0.0"
28
33
  },
29
34
  "devDependencies": {
30
35
  "chai": "^6.2.1",
@@ -0,0 +1,31 @@
1
+ import path from 'path'
2
+ import resolvePath from './resolve-path.js'
3
+ import { fileURLToPath } from 'url'
4
+
5
+ /**
6
+ * Get current directory & file.
7
+ * An attempt to brings back the old ```__dirname``` and ```__filename``` to the ES6 era.
8
+ *
9
+ * Returns object with the following keys:
10
+ * - ```__dirname``` (aliases to ```dir```) - current directory name
11
+ * - ```__filename``` (aliases to ```file```) - current file path
12
+ *
13
+ * Example:
14
+ * ```javascript
15
+ * const { importModule } = this.app.bajo
16
+ * const currentLoc = await importModule('bajo:/lib/current-loc.js')
17
+ *
18
+ * const { __dirname, __filename } = currentLoc(import.meta)
19
+ * console.log(__dirname, __filename)
20
+ * ```
21
+ *
22
+ * @param {Object} metaImport - ```import.meta``` object
23
+ * @returns {Object}
24
+ */
25
+ const currentLoc = (metaImport) => {
26
+ const file = resolvePath(fileURLToPath(metaImport.url))
27
+ const dir = path.dirname(file)
28
+ return { dir, file, __dirname: dir, __filename: file }
29
+ }
30
+
31
+ export default currentLoc
@@ -0,0 +1,88 @@
1
+ import { sprintf } from 'sprintf-js'
2
+ import pascalCase from './pascal-case.js'
3
+ import secToHms from './sec-to-hms.js'
4
+ import {
5
+ camelCase,
6
+ capitalize,
7
+ escape,
8
+ kebabCase,
9
+ toLower,
10
+ toUpper,
11
+ lowerFirst,
12
+ upperFirst,
13
+ snakeCase,
14
+ startCase,
15
+ trim,
16
+ unescape,
17
+ keys,
18
+ find
19
+ } from 'lodash-es'
20
+
21
+ const modifier = {
22
+ camelCase,
23
+ capitalize,
24
+ escape,
25
+ kebabCase,
26
+ toLower,
27
+ toUpper,
28
+ lowerFirst,
29
+ upperFirst,
30
+ snakeCase,
31
+ startCase,
32
+ trim,
33
+ unescape,
34
+ pascalCase,
35
+ secToHms
36
+ }
37
+
38
+ const modifiers = keys(modifier)
39
+
40
+ const pipe = '|'
41
+ const tokens = ['b', 'c', 'd', 'i', 'e', 'u', 'f', 'g', 'o', 's', 't', 'T', 'v', 'x', 'X', 'j']
42
+
43
+ /**
44
+ * Format text according using sprintf with extra ability to run its arguments through a serie of modifiers
45
+ * Modifier must be place right after a token prepended with pipe ``|``` symbols.
46
+ * You can put as many mofifiers as you want.
47
+ *
48
+ * E.g:
49
+ * ```javascript
50
+ * const text = 'Collected %s|toLower|upperFirst: %d'
51
+ * const result = this.app.lib.formatText(text, 'iTeMs', 10)
52
+ * console.log(result) // Collected Items: 10
53
+ * ```
54
+ *
55
+ * @param {string} text - Text to be formatted
56
+ * @param {...any} args - Argumennts
57
+ * @returns {string} Formatted text
58
+ */
59
+ function formatText (text, ...args) {
60
+ if (!text.includes(pipe)) return sprintf(text, ...args)
61
+ const items = text.split('%')
62
+ let newText = text.replaceAll('%%', '\t\t')
63
+ const newArgs = ['', ...args]
64
+ for (const idx in items) {
65
+ const item = items[idx]
66
+ if (tokens.includes(item[0])) {
67
+ const parts = item.split(pipe)
68
+ parts.shift()
69
+ for (const part of parts) {
70
+ let mod = modifier[part]
71
+ if (!mod) {
72
+ const fn = find(modifiers, name => part.slice(0, name.length) === name)
73
+ if (fn) mod = modifier[fn]
74
+ }
75
+ if (mod) newArgs[idx] = mod(newArgs[idx])
76
+ }
77
+ }
78
+ }
79
+ newText = newText.replaceAll('\t\t', '%%')
80
+ for (const key of keys(modifier)) {
81
+ newText = newText.replaceAll(`${pipe}${key}`, '')
82
+ }
83
+ newText = newText.replace(pipe, '')
84
+ newArgs.shift()
85
+ return sprintf(newText, ...newArgs)
86
+ }
87
+
88
+ export default formatText
@@ -0,0 +1,17 @@
1
+ function mergeObjectsByKey(inputs, key) {
2
+ const uniqueMap = new Map()
3
+
4
+ for (const item of inputs) {
5
+ const keyValue = item[key]
6
+ if (uniqueMap.has(keyValue)) {
7
+ const existingObject = uniqueMap.get(keyValue)
8
+ uniqueMap.set(keyValue, { ...existingObject, ...item })
9
+ } else {
10
+ uniqueMap.set(keyValue, item)
11
+ }
12
+ }
13
+
14
+ return Array.from(uniqueMap.values())
15
+ }
16
+
17
+ export default mergeObjectsByKey
@@ -0,0 +1,79 @@
1
+ import yargs from 'yargs'
2
+ import { Parser } from 'yargs/helpers'
3
+ import { unflatten } from 'flat'
4
+ import dotenvParseVariables from 'dotenv-parse-variables'
5
+ import { find, each, set, camelCase, forOwn } from 'lodash-es'
6
+ import fs from 'fs'
7
+ import path from 'path'
8
+
9
+ const delimiter = '-'
10
+ const splitter = ':'
11
+
12
+ const parseItem = (data, delimiter) => {
13
+ return unflatten(data, {
14
+ delimiter,
15
+ safe: true,
16
+ overwrite: true
17
+ })
18
+ }
19
+
20
+ async function parseWithParser () {
21
+ return Parser(process.argv.slice(2), {
22
+ configuration: {
23
+ 'camel-case-expansion': false
24
+ }
25
+ })
26
+ }
27
+
28
+ async function parseWithYargs () {
29
+ const pkgFile = `${process.cwd}/package.json`
30
+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'))
31
+ let name = `node ${pkg.main}`
32
+ if (pkg.bin) name = path.basename(pkg.bin, '.js')
33
+ const cli = yargs(process.argv.slice(2))
34
+ .usage('Usage: $0 [args...]')
35
+ .scriptName(name)
36
+ .positional('args', {
37
+ describe: 'Optional one or more arguments'
38
+ })
39
+ .parserConfiguration({
40
+ 'camel-case-expansion': false
41
+ })
42
+ .version(pkg.version).alias('version', 'v')
43
+ .help().alias('help', 'h')
44
+ .alias('applet', 'a')
45
+ if (pkg.homepage) cli.epilog(`For more information please visit ${pkg.homepage}`)
46
+ return cli.argv
47
+ }
48
+
49
+ /**
50
+ * Parse program arguments (args) & options (argv)
51
+ *
52
+ * @async
53
+ * @param {function(Object): Object} [sanitizer] - If provided, result will be sanitized with this function
54
+ * @param {boolean} [useParser] - If ```true```, skip {@link https://github.com/yargs/yargs|yargs}
55
+ * @returns {{args: Array, argv: Object}} An object containing ```args``` and ```argv```
56
+ * @see App#args
57
+ * @see App#argv
58
+ */
59
+ async function parseArgsArgv (sanitizer, useParser) {
60
+ if (!useParser) useParser = find(process.argv, a => a.startsWith('--spawn'))
61
+ let argv = useParser ? await parseWithParser.call() : await parseWithYargs.call()
62
+ const args = argv._
63
+ delete argv._
64
+ delete argv.$0
65
+ argv = dotenvParseVariables(argv)
66
+ const all = { _: {} }
67
+ each(argv, (v, k) => {
68
+ const parts = k.split(splitter)
69
+ if (!parts[1]) all._[parts[0]] = v
70
+ else set(all, `${camelCase(parts[0])}.${parts[1]}`, v)
71
+ })
72
+ const result = {}
73
+ forOwn(all, (v, k) => {
74
+ result[k] = parseItem(v, delimiter)
75
+ })
76
+ return { args, argv: sanitizer ? sanitizer(result) : result }
77
+ }
78
+
79
+ export default parseArgsArgv
@@ -0,0 +1,14 @@
1
+ import { isNumber } from 'lodash-es'
2
+ import ms from 'ms'
3
+ /**
4
+ * Parse duration to its millisecond value. Use {@link https://github.com/vercel/ms|ms} under the hood
5
+ *
6
+ * @param {(number|string)} dur - If string is given, parse this to its millisecond value. Otherwise returns as is
7
+ * @returns {number}
8
+ * @see {@link https://github.com/vercel/ms|ms}
9
+ */
10
+ function parseDuration (dur) {
11
+ return isNumber(dur) ? dur : ms(dur)
12
+ }
13
+
14
+ export default parseDuration
@@ -0,0 +1,47 @@
1
+ import dotenvParseVariables from 'dotenv-parse-variables'
2
+ import { unflatten } from 'flat'
3
+ import dotEnv from 'dotenv'
4
+ import { each, set, camelCase, forOwn } from 'lodash-es'
5
+
6
+ const parse = (data, delimiter) => {
7
+ return unflatten(data, {
8
+ delimiter,
9
+ safe: true,
10
+ overwrite: true,
11
+ transformKey: k => {
12
+ return camelCase(k.toLowerCase())
13
+ }
14
+ })
15
+ }
16
+
17
+ const delimiter = '__'
18
+ const splitter = '.'
19
+
20
+ /**
21
+ * Parse environment variables
22
+ *
23
+ * @param {function(Object): Object} [sanitizer] - If provided, result will be sanitized with this function
24
+ * @returns {Object}
25
+ */
26
+ function parseEnv (sanitizer) {
27
+ let env
28
+ try {
29
+ env = dotEnv.config({ quiet: true })
30
+ } catch (err) {
31
+ }
32
+ env = dotenvParseVariables(process.env, { assignToProcessEnv: false })
33
+ const all = { _: {} }
34
+ each(env, (v, k) => {
35
+ const parts = k.split(splitter)
36
+ if (!parts[1]) all._[parts[0]] = v
37
+ else set(all, `${camelCase(parts[0])}.${parts[1]}`, v)
38
+ })
39
+ const result = {}
40
+ forOwn(all, (v, k) => {
41
+ result[k] = parse(v, delimiter)
42
+ })
43
+ if (result._.lang) result._.lang = result._.lang.split('.')[0].replaceAll('_', '-')
44
+ return sanitizer ? sanitizer(result) : result
45
+ }
46
+
47
+ export default parseEnv
@@ -0,0 +1,23 @@
1
+ import path from 'path'
2
+ import { fileURLToPath } from 'url'
3
+ import os from 'os'
4
+
5
+ /**
6
+ * Resolve file name to filesystem's path. Windows path separator ```\```
7
+ * is normalized to Unix's ```/```
8
+ *
9
+ * @param {string} file - File to resolve
10
+ * @param {boolean} [asFileUrl=false] - Return as file URL format ```file:///<name>```
11
+ * @returns {string}
12
+ */
13
+ function resolvePath (item, asFileUrl) {
14
+ if (item.startsWith('file://')) item = fileURLToPath(item)
15
+ item = path.resolve(item)
16
+ if (os.platform() === 'win32') {
17
+ item = item.replace(/\\/g, '/')
18
+ }
19
+ if (asFileUrl) item = `file:///${item}`
20
+ return item
21
+ }
22
+
23
+ export default resolvePath
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Async/await wrapper for setImmediate
3
+ */
4
+ async function setImmediate () {
5
+ return new Promise((resolve) => {
6
+ setImmediate(() => resolve())
7
+ })
8
+ }
9
+
10
+ export default setImmediate
package/src/shim.js ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Function to attach some of the methods needed but probably not provided by your node installation:
3
+ *
4
+ * - ```String.prototype.replaceAll```
5
+ * - ```String.prototype.splice```
6
+ *
7
+ * @memberof module:Lib
8
+ */
9
+ function shim () {
10
+ // taken from: https://vanillajstoolkit.com/polyfills/stringreplaceall/
11
+ if (!String.prototype.replaceAll) {
12
+ String.prototype.replaceAll = function(str, newStr) { // eslint-disable-line
13
+ if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') {
14
+ return this.replace(str, newStr)
15
+ }
16
+ return this.replace(new RegExp(str, 'g'), newStr)
17
+ }
18
+ }
19
+ if (!String.prototype.splice) {
20
+ String.prototype.splice = function(index, count, add) { // eslint-disable-line
21
+ if (index < 0) {
22
+ index += this.length
23
+ if (index < 0) index = 0
24
+ }
25
+ return this.slice(0, index) + (add || '') + this.slice(index + count)
26
+ }
27
+ }
28
+ }
29
+
30
+ export default shim
@@ -0,0 +1,21 @@
1
+ import { expect } from 'chai'
2
+ import fn from '../src/merge-objects-by-key.js'
3
+
4
+ describe('mergeObjectsByKey', function () {
5
+ it('Should return the expected result', function () {
6
+ const items = [
7
+ { id: 1, name: 'Apple', count: 1 },
8
+ { id: 2, name: 'Banana', count: 2 },
9
+ { id: 1, color: 'Red', price: 0.99 },
10
+ { id: 3, name: 'Cherry', count: 5 },
11
+ { id: 2, color: 'Yellow', weight: '100g' }
12
+ ]
13
+ const expected = [
14
+ { id: 1, name: 'Apple', count: 1, color: 'Red', price: 0.99 },
15
+ { id: 2, name: 'Banana', count: 2, color: 'Yellow', weight: '100g' },
16
+ { id: 3, name: 'Cherry', count: 5 }
17
+ ]
18
+ const result = fn(items, 'id')
19
+ expect(result).to.eql(expected)
20
+ })
21
+ })