• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

TotalTechGeek / json-logic-engine / 12225116622

08 Dec 2024 08:45PM UTC coverage: 91.848% (-0.4%) from 92.254%
12225116622

Pull #38

github

web-flow
Merge d5aade1e0 into 91d18201d
Pull Request #38: Modified RFC6901

780 of 885 branches covered (88.14%)

Branch coverage included in aggregate %.

5 of 8 new or added lines in 1 file covered. (62.5%)

6 existing lines in 3 files now uncovered.

786 of 820 relevant lines covered (95.85%)

32085.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.29
/defaultMethods.js
1
// @ts-check
2
'use strict'
3

4
import asyncIterators from './async_iterators.js'
5
import { Sync, isSync } from './constants.js'
6
import declareSync from './utilities/declareSync.js'
7
import { build, buildString } from './compiler.js'
8
import chainingSupported from './utilities/chainingSupported.js'
9
import InvalidControlInput from './errors/InvalidControlInput.js'
10
import { splitPathMemoized } from './utilities/splitPath.js'
11

12
function isDeterministic (method, engine, buildState) {
13
  if (Array.isArray(method)) {
23,376✔
14
    return method.every((i) => isDeterministic(i, engine, buildState))
14,880✔
15
  }
16
  if (method && typeof method === 'object') {
18,312✔
17
    const func = Object.keys(method)[0]
5,166✔
18
    const lower = method[func]
5,166✔
19

20
    if (engine.isData(method, func)) return true
5,166✔
21
    if (!engine.methods[func]) throw new Error(`Method '${func}' was not found in the Logic Engine.`)
5,082!
22

23
    if (engine.methods[func].traverse === false) {
5,082✔
24
      return typeof engine.methods[func].deterministic === 'function'
168!
25
        ? engine.methods[func].deterministic(lower, buildState)
26
        : engine.methods[func].deterministic
27
    }
28
    return typeof engine.methods[func].deterministic === 'function'
4,914✔
29
      ? engine.methods[func].deterministic(lower, buildState)
30
      : engine.methods[func].deterministic &&
2,490✔
31
          isDeterministic(lower, engine, buildState)
32
  }
33
  return true
13,146✔
34
}
35

36
function isSyncDeep (method, engine, buildState) {
37
  if (Array.isArray(method)) {
24,780✔
38
    return method.every((i) => isSyncDeep(i, engine, buildState))
13,512✔
39
  }
40

41
  if (method && typeof method === 'object') {
19,752✔
42
    const func = Object.keys(method)[0]
7,884✔
43
    const lower = method[func]
7,884✔
44
    if (engine.isData(method, func)) return true
7,884✔
45
    if (!engine.methods[func]) throw new Error(`Method '${func}' was not found in the Logic Engine.`)
7,842!
46
    if (engine.methods[func].traverse === false) return typeof engine.methods[func][Sync] === 'function' ? engine.methods[func][Sync](lower, buildState) : engine.methods[func][Sync]
7,842!
47
    return typeof engine.methods[func][Sync] === 'function' ? engine.methods[func][Sync](lower, buildState) : engine.methods[func][Sync] && isSyncDeep(lower, engine, buildState)
4,998!
48
  }
49

50
  return true
11,868✔
51
}
52

53
const defaultMethods = {
54✔
54
  '+': (data) => {
55
    if (typeof data === 'string') return +data
482,724✔
56
    if (typeof data === 'number') return +data
482,712!
57
    let res = 0
482,712✔
58
    for (let i = 0; i < data.length; i++) res += +data[i]
965,412✔
59
    return res
482,712✔
60
  },
61
  '*': (data) => {
62
    let res = 1
864✔
63
    for (let i = 0; i < data.length; i++) res *= +data[i]
1,752✔
64
    return res
864✔
65
  },
66
  '/': (data) => {
67
    let res = data[0]
300✔
68
    for (let i = 1; i < data.length; i++) res /= +data[i]
324✔
69
    return res
300✔
70
  },
71
  '-': (data) => {
72
    if (typeof data === 'string') return -data
516✔
73
    if (typeof data === 'number') return -data
504!
74
    if (data.length === 1) return -data[0]
504✔
75
    let res = data[0]
264✔
76
    for (let i = 1; i < data.length; i++) res -= +data[i]
288✔
77
    return res
264✔
78
  },
79
  '%': (data) => {
80
    let res = data[0]
504✔
81
    for (let i = 1; i < data.length; i++) res %= +data[i]
528✔
82
    return res
504✔
83
  },
84
  max: (data) => Math.max(...data),
732✔
85
  min: (data) => Math.min(...data),
336✔
86
  in: ([item, array]) => (array || []).includes(item),
456✔
87
  '>': ([a, b]) => a > b,
1,452✔
88
  '<': ([a, b, c]) => (c === undefined ? a < b : a < b && b < c),
1,680✔
89
  preserve: {
90
    traverse: false,
91
    method: declareSync((i) => i, true),
1,626✔
92
    [Sync]: () => true
462✔
93
  },
94
  if: {
95
    method: (input, context, above, engine) => {
96
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
3,234!
97

98
      if (input.length === 1) return engine.run(input[0], context, { above })
3,234✔
99
      if (input.length < 2) return null
3,006✔
100

101
      input = [...input]
2,922✔
102
      if (input.length % 2 !== 1) input.push(null)
2,922✔
103

104
      // fallback to the default if the condition is false
105
      const onFalse = input.pop()
2,922✔
106

107
      // while there are still conditions
108
      while (input.length) {
2,922✔
109
        const check = input.shift()
3,678✔
110
        const onTrue = input.shift()
3,678✔
111

112
        const test = engine.run(check, context, { above })
3,678✔
113

114
        // if the condition is true, run the true branch
115
        if (engine.truthy(test)) return engine.run(onTrue, context, { above })
3,678✔
116
      }
117

118
      return engine.run(onFalse, context, { above })
942✔
119
    },
120
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
3,612✔
121
    deterministic: (data, buildState) => {
122
      return isDeterministic(data, buildState.engine, buildState)
3,216✔
123
    },
124
    asyncMethod: async (input, context, above, engine) => {
125
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
102!
126

127
      // check the bounds
128
      if (input.length === 1) return engine.run(input[0], context, { above })
102✔
129
      if (input.length < 2) return null
66✔
130

131
      input = [...input]
54✔
132

133
      if (input.length % 2 !== 1) input.push(null)
54✔
134

135
      // fallback to the default if the condition is false
136
      const onFalse = input.pop()
54✔
137

138
      // while there are still conditions
139
      while (input.length) {
54✔
140
        const check = input.shift()
54✔
141
        const onTrue = input.shift()
54✔
142

143
        const test = await engine.run(check, context, { above })
54✔
144

145
        // if the condition is true, run the true branch
146
        if (engine.truthy(test)) return engine.run(onTrue, context, { above })
54✔
147
      }
148

149
      return engine.run(onFalse, context, { above })
18✔
150
    },
151
    traverse: false
152
  },
153
  '<=': ([a, b, c]) => (c === undefined ? a <= b : a <= b && b <= c),
696✔
154
  '>=': ([a, b]) => a >= b,
1,380✔
155
  // eslint-disable-next-line eqeqeq
156
  '==': ([a, b]) => a == b,
840✔
157
  '===': ([a, b]) => a === b,
1,608✔
158
  // eslint-disable-next-line eqeqeq
159
  '!=': ([a, b]) => a != b,
516✔
160
  '!==': ([a, b]) => a !== b,
576✔
161
  xor: ([a, b]) => a ^ b,
264✔
162
  or: (arr, _1, _2, engine) => {
163
    for (let i = 0; i < arr.length; i++) {
1,584✔
164
      if (engine.truthy(arr[i])) return arr[i]
2,556✔
165
    }
166
    return arr[arr.length - 1]
312✔
167
  },
168
  and: (arr, _1, _2, engine) => {
169
    for (let i = 0; i < arr.length; i++) {
2,112✔
170
      if (!engine.truthy(arr[i])) return arr[i]
3,564✔
171
    }
172
    return arr[arr.length - 1]
852✔
173
  },
174
  substr: ([string, from, end]) => {
175
    if (end < 0) {
720✔
176
      const result = string.substr(from)
192✔
177
      return result.substr(0, result.length + end)
192✔
178
    }
179
    return string.substr(from, end)
528✔
180
  },
181
  length: ([i]) => {
182
    if (typeof i === 'string' || Array.isArray(i)) return i.length
144✔
183
    if (i && typeof i === 'object') return Object.keys(i).length
96✔
184
    return 0
24✔
185
  },
186
  get: {
187
    method: ([data, key, defaultValue], context, above, engine) => {
188
      const notFound = defaultValue === undefined ? null : defaultValue
480✔
189

190
      const subProps = splitPathMemoized(String(key))
480✔
191
      for (let i = 0; i < subProps.length; i++) {
480✔
192
        if (data === null || data === undefined) {
480!
193
          return notFound
×
194
        }
195
        // Descending into context
196
        data = data[subProps[i]]
480✔
197
        if (data === undefined) {
480✔
198
          return notFound
48✔
199
        }
200
      }
201
      if (engine.allowFunctions || typeof data[key] !== 'function') {
432!
202
        return data
432✔
203
      }
204
    }
205
  },
206
  var: (key, context, above, engine) => {
207
    let b
208
    if (Array.isArray(key)) {
22,458✔
209
      b = key[1]
16,488✔
210
      key = key[0]
16,488✔
211
    }
212
    let iter = 0
22,458✔
213
    while (
22,458✔
214
      typeof key === 'string' &&
63,168✔
215
      key.startsWith('../') &&
216
      iter < above.length
217
    ) {
218
      context = above[iter++]
6,132✔
219
      key = key.substring(3)
6,132✔
220
      // A performance optimization that allows you to pass the previous above array without spreading it as the last argument
221
      if (iter === above.length && Array.isArray(context)) {
6,132✔
222
        iter = 0
288✔
223
        above = context
288✔
224
        context = above[iter++]
288✔
225
      }
226
    }
227

228
    const notFound = b === undefined ? null : b
22,458✔
229
    if (typeof key === 'undefined' || key === '' || key === null) {
22,458✔
230
      if (engine.allowFunctions || typeof context !== 'function') {
3,096!
231
        return context
3,096✔
232
      }
233
      return null
×
234
    }
235
    const subProps = splitPathMemoized(String(key))
19,362✔
236
    for (let i = 0; i < subProps.length; i++) {
19,362✔
237
      if (context === null || context === undefined) {
21,930✔
238
        return notFound
96✔
239
      }
240
      // Descending into context
241
      context = context[subProps[i]]
21,834✔
242
      if (context === undefined) {
21,834✔
243
        return notFound
3,144✔
244
      }
245
    }
246
    if (engine.allowFunctions || typeof context !== 'function') {
16,122✔
247
      return context
16,050✔
248
    }
249
    return null
72✔
250
  },
251
  missing: (checked, context, above, engine) => {
252
    return (Array.isArray(checked) ? checked : [checked]).filter((key) => {
2,736!
253
      return defaultMethods.var(key, context, above, engine) === null
4,656✔
254
    })
255
  },
256
  missing_some: ([needCount, options], context, above, engine) => {
257
    const missing = defaultMethods.missing(options, context, above, engine)
864✔
258
    if (options.length - missing.length >= needCount) {
864✔
259
      return []
576✔
260
    } else {
261
      return missing
288✔
262
    }
263
  },
264
  map: createArrayIterativeMethod('map'),
265
  some: createArrayIterativeMethod('some', true),
266
  all: createArrayIterativeMethod('every', true),
267
  none: {
268
    traverse: false,
269
    // todo: add async build & build
270
    method: (val, context, above, engine) => {
271
      return !defaultMethods.some.method(val, context, above, engine)
192✔
272
    },
273
    asyncMethod: async (val, context, above, engine) => {
274
      return !(await defaultMethods.some.asyncMethod(
192✔
275
        val,
276
        context,
277
        above,
278
        engine
279
      ))
280
    },
281
    compile: (data, buildState) => {
282
      const result = defaultMethods.some.compile(data, buildState)
384✔
283
      return result ? buildState.compile`!(${result})` : false
384!
284
    }
285
  },
286
  merge: (arrays) => (Array.isArray(arrays) ? [].concat(...arrays) : [arrays]),
1,140!
287
  every: createArrayIterativeMethod('every'),
288
  filter: createArrayIterativeMethod('filter'),
289
  reduce: {
290
    deterministic: (data, buildState) => {
291
      return (
420✔
292
        isDeterministic(data[0], buildState.engine, buildState) &&
480✔
293
        isDeterministic(data[1], buildState.engine, {
294
          ...buildState,
295
          insideIterator: true
296
        })
297
      )
298
    },
299
    compile: (data, buildState) => {
300
      if (!Array.isArray(data)) throw new InvalidControlInput(data)
336!
301
      const { async } = buildState
336✔
302
      let [selector, mapper, defaultValue] = data
336✔
303
      selector = buildString(selector, buildState)
336✔
304
      if (typeof defaultValue !== 'undefined') {
336!
305
        defaultValue = buildString(defaultValue, buildState)
336✔
306
      }
307
      const mapState = {
336✔
308
        ...buildState,
309
        extraArguments: 'above',
310
        avoidInlineAsync: true
311
      }
312
      mapper = build(mapper, mapState)
336✔
313
      const aboveArray = mapper.aboveDetected ? '[null, context, above]' : 'null'
336!
314

315
      buildState.methods.push(mapper)
336✔
316
      if (async) {
336✔
317
        if (!isSync(mapper) || selector.includes('await')) {
168!
318
          buildState.detectAsync = true
×
319
          if (typeof defaultValue !== 'undefined') {
×
320
            return `await asyncIterators.reduce(${selector} || [], (a,b) => methods[${
×
321
              buildState.methods.length - 1
322
            }]({ accumulator: a, current: b }, ${aboveArray}), ${defaultValue})`
323
          }
324
          return `await asyncIterators.reduce(${selector} || [], (a,b) => methods[${
×
325
            buildState.methods.length - 1
326
          }]({ accumulator: a, current: b }, ${aboveArray}))`
327
        }
328
      }
329
      if (typeof defaultValue !== 'undefined') {
336!
330
        return `(${selector} || []).reduce((a,b) => methods[${
336✔
331
          buildState.methods.length - 1
332
        }]({ accumulator: a, current: b }, ${aboveArray}), ${defaultValue})`
333
      }
334
      return `(${selector} || []).reduce((a,b) => methods[${
×
335
        buildState.methods.length - 1
336
      }]({ accumulator: a, current: b }, ${aboveArray}))`
337
    },
338
    method: (input, context, above, engine) => {
339
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
432✔
340
      let [selector, mapper, defaultValue] = input
408✔
341
      defaultValue = engine.run(defaultValue, context, {
408✔
342
        above
343
      })
344
      selector =
408✔
345
        engine.run(selector, context, {
456✔
346
          above
347
        }) || []
348
      const func = (accumulator, current) => {
408✔
349
        return engine.run(
1,410✔
350
          mapper,
351
          {
352
            accumulator,
353
            current
354
          },
355
          {
356
            above: [selector, context, above]
357
          }
358
        )
359
      }
360
      if (typeof defaultValue === 'undefined') {
408✔
361
        return selector.reduce(func)
54✔
362
      }
363
      return selector.reduce(func, defaultValue)
354✔
364
    },
365
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
408✔
366
    asyncMethod: async (input, context, above, engine) => {
367
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
24!
368
      let [selector, mapper, defaultValue] = input
24✔
369
      defaultValue = await engine.run(defaultValue, context, {
24✔
370
        above
371
      })
372
      selector =
24✔
373
        (await engine.run(selector, context, {
24!
374
          above
375
        })) || []
376
      return asyncIterators.reduce(
24✔
377
        selector,
378
        (accumulator, current) => {
379
          return engine.run(
102✔
380
            mapper,
381
            {
382
              accumulator,
383
              current
384
            },
385
            {
386
              above: [selector, context, above]
387
            }
388
          )
389
        },
390
        defaultValue
391
      )
392
    },
393
    traverse: false
394
  },
395
  '!': (value, _1, _2, engine) => Array.isArray(value) ? !engine.truthy(value[0]) : !engine.truthy(value),
816!
396
  '!!': (value, _1, _2, engine) => Boolean(Array.isArray(value) ? engine.truthy(value[0]) : engine.truthy(value)),
324!
397
  cat: (arr) => {
398
    if (typeof arr === 'string') return arr
912!
399
    let res = ''
912✔
400
    for (let i = 0; i < arr.length; i++) res += arr[i]
2,244✔
401
    return res
912✔
402
  },
403
  keys: ([obj]) => typeof obj === 'object' ? Object.keys(obj) : [],
48✔
404
  pipe: {
405
    traverse: false,
406
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
168✔
407
    method: (args, context, above, engine) => {
408
      if (!Array.isArray(args)) throw new Error('Data for pipe must be an array')
108!
409
      let answer = engine.run(args[0], context, { above: [args, context, above] })
108✔
410
      for (let i = 1; i < args.length; i++) answer = engine.run(args[i], answer, { above: [args, context, above] })
108✔
411
      return answer
108✔
412
    },
413
    asyncMethod: async (args, context, above, engine) => {
414
      if (!Array.isArray(args)) throw new Error('Data for pipe must be an array')
60!
415
      let answer = await engine.run(args[0], context, { above: [args, context, above] })
60✔
416
      for (let i = 1; i < args.length; i++) answer = await engine.run(args[i], answer, { above: [args, context, above] })
96✔
417
      return answer
60✔
418
    },
419
    compile: (args, buildState) => {
420
      let res = buildState.compile`${args[0]}`
48✔
421
      for (let i = 1; i < args.length; i++) res = buildState.compile`${build(args[i], { ...buildState, extraArguments: 'above' })}(${res}, [null, context, above])`
48✔
422
      return res
48✔
423
    },
424
    deterministic: (data, buildState) => {
425
      if (!Array.isArray(data)) return false
192!
426
      data = [...data]
192✔
427
      const first = data.shift()
192✔
428
      return isDeterministic(first, buildState.engine, buildState) && isDeterministic(data, buildState.engine, { ...buildState, insideIterator: true })
192✔
429
    }
430
  },
431
  eachKey: {
432
    traverse: false,
433
    [Sync]: (data, buildState) => isSyncDeep(Object.values(data[Object.keys(data)[0]]), buildState.engine, buildState),
30✔
434
    method: (object, context, above, engine) => {
435
      const result = Object.keys(object).reduce((accumulator, key) => {
78✔
436
        const item = object[key]
138✔
437
        Object.defineProperty(accumulator, key, {
138✔
438
          enumerable: true,
439
          value: engine.run(item, context, { above })
440
        })
441
        return accumulator
138✔
442
      }, {})
443
      return result
78✔
444
    },
445
    deterministic: (data, buildState) => {
446
      if (data && typeof data === 'object') {
192!
447
        return Object.values(data).every((i) => {
192✔
448
          return isDeterministic(i, buildState.engine, buildState)
252✔
449
        })
450
      }
451
      throw new InvalidControlInput(data)
×
452
    },
453
    compile: (data, buildState) => {
454
      // what's nice about this is that I don't have to worry about whether it's async or not, the lower entries take care of that ;)
455
      // however, this is not engineered support yields, I will have to make a note of that & possibly support it at a later point.
456
      if (data && typeof data === 'object') {
168!
457
        const result = `({ ${Object.keys(data)
168✔
458
          .reduce((accumulator, key) => {
459
            accumulator.push(
240✔
460
              // @ts-ignore Never[] is not accurate
461
              `${JSON.stringify(key)}: ${buildString(data[key], buildState)}`
462
            )
463
            return accumulator
240✔
464
          }, [])
465
          .join(',')} })`
466
        return result
168✔
467
      }
468
      throw new InvalidControlInput(data)
×
469
    },
470
    asyncMethod: async (object, context, above, engine) => {
471
      const result = await asyncIterators.reduce(
18✔
472
        Object.keys(object),
473
        async (accumulator, key) => {
474
          const item = object[key]
30✔
475
          Object.defineProperty(accumulator, key, {
30✔
476
            enumerable: true,
477
            value: await engine.run(item, context, { above })
478
          })
479
          return accumulator
30✔
480
        },
481
        {}
482
      )
483
      return result
18✔
484
    }
485
  }
486
}
487

488
function createArrayIterativeMethod (name, useTruthy = false) {
162✔
489
  return {
270✔
490
    deterministic: (data, buildState) => {
491
      return (
2,496✔
492
        isDeterministic(data[0], buildState.engine, buildState) &&
3,042✔
493
        isDeterministic(data[1], buildState.engine, {
494
          ...buildState,
495
          insideIterator: true
496
        })
497
      )
498
    },
499
    [Sync]: (data, buildState) => isSyncDeep(data, buildState.engine, buildState),
1,326✔
500
    method: (input, context, above, engine) => {
501
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
1,890✔
502
      let [selector, mapper] = input
1,866✔
503
      selector =
1,866✔
504
        engine.run(selector, context, {
1,914✔
505
          above
506
        }) || []
507

508
      return selector[name]((i, index) => {
1,866✔
509
        const result = engine.run(mapper, i, {
4,530✔
510
          above: [{ item: selector, index }, context, above]
511
        })
512
        return useTruthy ? engine.truthy(result) : result
4,530✔
513
      })
514
    },
515
    asyncMethod: async (input, context, above, engine) => {
516
      if (!Array.isArray(input)) throw new InvalidControlInput(input)
642!
517
      let [selector, mapper] = input
642✔
518
      selector =
642✔
519
        (await engine.run(selector, context, {
642!
520
          above
521
        })) || []
522
      return asyncIterators[name](selector, (i, index) => {
642✔
523
        const result = engine.run(mapper, i, {
1,110✔
524
          above: [{ item: selector, index }, context, above]
525
        })
526
        return useTruthy ? engine.truthy(result) : result
1,110✔
527
      })
528
    },
529
    compile: (data, buildState) => {
530
      if (!Array.isArray(data)) throw new InvalidControlInput(data)
1,602!
531
      const { async } = buildState
1,602✔
532
      const [selector, mapper] = data
1,602✔
533

534
      const mapState = {
1,602✔
535
        ...buildState,
536
        avoidInlineAsync: true,
537
        iteratorCompile: true,
538
        extraArguments: 'index, above'
539
      }
540

541
      const method = build(mapper, mapState)
1,602✔
542
      const aboveArray = method.aboveDetected ? buildState.compile`[{ item: null }, context, above]` : buildState.compile`null`
1,602✔
543

544
      if (async) {
1,602✔
545
        if (!isSyncDeep(mapper, buildState.engine, buildState)) {
810✔
546
          buildState.detectAsync = true
18✔
547
          return buildState.compile`await asyncIterators[${name}](${selector} || [], async (i, x) => ${method}(i, x, ${aboveArray}))`
18✔
548
        }
549
      }
550

551
      return buildState.compile`(${selector} || [])[${name}]((i, x) => ${method}(i, x, ${aboveArray}))`
1,584✔
552
    },
553
    traverse: false
554
  }
555
}
556
defaultMethods['?:'] = defaultMethods.if
54✔
557
// declare all of the functions here synchronous
558
Object.keys(defaultMethods).forEach((item) => {
54✔
559
  if (typeof defaultMethods[item] === 'function') {
2,268✔
560
    defaultMethods[item][Sync] = true
1,566✔
561
  }
562
  defaultMethods[item].deterministic =
2,268✔
563
    typeof defaultMethods[item].deterministic === 'undefined'
2,268✔
564
      ? true
565
      : defaultMethods[item].deterministic
566
})
567
// @ts-ignore Allow custom attribute
568
defaultMethods.var.deterministic = (data, buildState) => {
54✔
569
  return buildState.insideIterator && !String(data).includes('../../')
16,092✔
570
}
571
Object.assign(defaultMethods.missing, {
54✔
572
  deterministic: false
573
})
574
Object.assign(defaultMethods.missing_some, {
54✔
575
  deterministic: false
576
})
577
// @ts-ignore Allow custom attribute
578
defaultMethods['<'].compile = function (data, buildState) {
54✔
579
  if (!Array.isArray(data)) return false
600✔
580
  if (data.length === 2) return buildState.compile`(${data[0]} < ${data[1]})`
576✔
581
  if (data.length === 3) return buildState.compile`(${data[0]} < ${data[1]} && ${data[1]} < ${data[2]})`
72!
582
  return false
×
583
}
584
// @ts-ignore Allow custom attribute
585
defaultMethods['<='].compile = function (data, buildState) {
54✔
586
  if (!Array.isArray(data)) return false
168✔
587
  if (data.length === 2) return buildState.compile`(${data[0]} <= ${data[1]})`
144✔
588
  if (data.length === 3) return buildState.compile`(${data[0]} <= ${data[1]} && ${data[1]} <= ${data[2]})`
48!
589
  return false
×
590
}
591
// @ts-ignore Allow custom attribute
592
defaultMethods.min.compile = function (data, buildState) {
54✔
593
  if (!Array.isArray(data)) return false
120✔
594
  return `Math.min(${data
96✔
595
    .map((i) => buildString(i, buildState))
240✔
596
    .join(', ')})`
597
}
598
// @ts-ignore Allow custom attribute
599
defaultMethods.max.compile = function (data, buildState) {
54✔
600
  if (!Array.isArray(data)) return false
264✔
601
  return `Math.max(${data
144✔
602
    .map((i) => buildString(i, buildState))
336✔
603
    .join(', ')})`
604
}
605
// @ts-ignore Allow custom attribute
606
defaultMethods['>'].compile = function (data, buildState) {
54✔
607
  if (!Array.isArray(data)) return false
384✔
608
  if (data.length !== 2) return false
360!
609
  return buildState.compile`(${data[0]} > ${data[1]})`
360✔
610
}
611
// @ts-ignore Allow custom attribute
612
defaultMethods['>='].compile = function (data, buildState) {
54✔
613
  if (!Array.isArray(data)) return false
456✔
614
  if (data.length !== 2) return false
432!
615
  return buildState.compile`(${data[0]} >= ${data[1]})`
432✔
616
}
617
// @ts-ignore Allow custom attribute
618
defaultMethods['=='].compile = function (data, buildState) {
54✔
619
  if (!Array.isArray(data)) return false
240✔
620
  if (data.length !== 2) return false
216!
621
  return buildState.compile`(${data[0]} == ${data[1]})`
216✔
622
}
623
// @ts-ignore Allow custom attribute
624
defaultMethods['!='].compile = function (data, buildState) {
54✔
625
  if (!Array.isArray(data)) return false
96✔
626
  if (data.length !== 2) return false
72!
627
  return buildState.compile`(${data[0]} != ${data[1]})`
72✔
628
}
629
// @ts-ignore Allow custom attribute
630
defaultMethods.if.compile = function (data, buildState) {
54✔
631
  if (!Array.isArray(data)) return false
1,416!
632
  if (data.length < 3) return false
1,416✔
633

634
  data = [...data]
1,272✔
635
  if (data.length % 2 !== 1) data.push(null)
1,272✔
636
  const onFalse = data.pop()
1,272✔
637

638
  let res = buildState.compile``
1,272✔
639
  while (data.length) {
1,272✔
640
    const condition = data.shift()
1,896✔
641
    const onTrue = data.shift()
1,896✔
642
    res = buildState.compile`${res} engine.truthy(${condition}) ? ${onTrue} : `
1,896✔
643
  }
644

645
  return buildState.compile`(${res} ${onFalse})`
1,272✔
646
}
647
// @ts-ignore Allow custom attribute
648
defaultMethods['==='].compile = function (data, buildState) {
54✔
649
  if (!Array.isArray(data)) return false
240✔
650
  if (data.length !== 2) return false
216!
651
  return buildState.compile`(${data[0]} === ${data[1]})`
216✔
652
}
653
// @ts-ignore Allow custom attribute
654
defaultMethods['+'].compile = function (data, buildState) {
54✔
655
  if (Array.isArray(data)) {
786✔
656
    return `(${data
762✔
657
      .map((i) => `(+${buildString(i, buildState)})`)
1,578✔
658
      .join(' + ')})`
659
  } else if (typeof data === 'string' || typeof data === 'number') {
24!
660
    return `(+${buildString(data, buildState)})`
×
661
  } else {
662
    return `([].concat(${buildString(
24✔
663
      data,
664
      buildState
665
    )})).reduce((a,b) => (+a)+(+b), 0)`
666
  }
667
}
668

669
// @ts-ignore Allow custom attribute
670
defaultMethods['%'].compile = function (data, buildState) {
54✔
671
  if (Array.isArray(data)) {
168✔
672
    return `(${data
144✔
673
      .map((i) => `(+${buildString(i, buildState)})`)
288✔
674
      .join(' % ')})`
675
  } else {
676
    return `(${buildString(data, buildState)}).reduce((a,b) => (+a)%(+b))`
24✔
677
  }
678
}
679

680
// @ts-ignore Allow custom attribute
681
defaultMethods.or.compile = function (data, buildState) {
54✔
682
  if (!buildState.engine.truthy.IDENTITY) return false
384✔
683
  if (Array.isArray(data)) {
24!
684
    return `(${data.map((i) => buildString(i, buildState)).join(' || ')})`
×
685
  } else {
686
    return `(${buildString(data, buildState)}).reduce((a,b) => a||b, false)`
24✔
687
  }
688
}
689

690
// @ts-ignore Allow custom attribute
691
defaultMethods.in.compile = function (data, buildState) {
54✔
692
  if (!Array.isArray(data)) return false
216!
693
  return buildState.compile`(${data[1]} || []).includes(${data[0]})`
216✔
694
}
695

696
// @ts-ignore Allow custom attribute
697
defaultMethods.and.compile = function (data, buildState) {
54✔
698
  if (!buildState.engine.truthy.IDENTITY) return false
528✔
699
  if (Array.isArray(data)) {
24!
700
    return `(${data.map((i) => buildString(i, buildState)).join(' && ')})`
×
701
  } else {
702
    return `(${buildString(data, buildState)}).reduce((a,b) => a&&b, true)`
24✔
703
  }
704
}
705

706
// @ts-ignore Allow custom attribute
707
defaultMethods['-'].compile = function (data, buildState) {
54✔
708
  if (Array.isArray(data)) {
216✔
709
    return `${data.length === 1 ? '-' : ''}(${data
192✔
710
      .map((i) => `(+${buildString(i, buildState)})`)
264✔
711
      .join(' - ')})`
712
  }
713
  if (typeof data === 'string' || typeof data === 'number') {
24!
714
    return `(-${buildString(data, buildState)})`
×
715
  } else {
716
    return `((a=>(a.length===1?a[0]=-a[0]:a)&0||a)([].concat(${buildString(
24✔
717
      data,
718
      buildState
719
    )}))).reduce((a,b) => (+a)-(+b))`
720
  }
721
}
722
// @ts-ignore Allow custom attribute
723
defaultMethods['/'].compile = function (data, buildState) {
54✔
724
  if (Array.isArray(data)) {
120✔
725
    return `(${data
96✔
726
      .map((i) => `(+${buildString(i, buildState)})`)
192✔
727
      .join(' / ')})`
728
  } else {
729
    return `(${buildString(data, buildState)}).reduce((a,b) => (+a)/(+b))`
24✔
730
  }
731
}
732
// @ts-ignore Allow custom attribute
733
defaultMethods['*'].compile = function (data, buildState) {
54✔
734
  if (Array.isArray(data)) {
336✔
735
    return `(${data
312✔
736
      .map((i) => `(+${buildString(i, buildState)})`)
624✔
737
      .join(' * ')})`
738
  } else {
739
    return `(${buildString(data, buildState)}).reduce((a,b) => (+a)*(+b))`
24✔
740
  }
741
}
742
// @ts-ignore Allow custom attribute
743
defaultMethods.cat.compile = function (data, buildState) {
54✔
744
  if (typeof data === 'string') return JSON.stringify(data)
384!
745
  if (!Array.isArray(data)) return false
384✔
746
  let res = buildState.compile`''`
288✔
747
  for (let i = 0; i < data.length; i++) res = buildState.compile`${res} + ${data[i]}`
648✔
748
  return buildState.compile`(${res})`
288✔
749
}
750

751
// @ts-ignore Allow custom attribute
752
defaultMethods['!'].compile = function (
54✔
753
  data,
754
  buildState
755
) {
756
  if (Array.isArray(data)) return buildState.compile`(!engine.truthy(${data[0]}))`
264!
757
  return buildState.compile`(!engine.truthy(${data}))`
×
758
}
759

760
defaultMethods.not = defaultMethods['!']
54✔
761

762
// @ts-ignore Allow custom attribute
763
defaultMethods['!!'].compile = function (data, buildState) {
54✔
764
  if (Array.isArray(data)) return buildState.compile`(!!engine.truthy(${data[0]}))`
96!
765
  return `(!!engine.truthy(${data}))`
×
766
}
767
defaultMethods.none.deterministic = defaultMethods.some.deterministic
54✔
768
defaultMethods.get.compile = function (data, buildState) {
54✔
769
  let defaultValue = null
396✔
770
  let key = data
396✔
771
  let obj = null
396✔
772
  if (Array.isArray(data) && data.length <= 3) {
396!
773
    obj = data[0]
396✔
774
    key = data[1]
396✔
775
    defaultValue = typeof data[2] === 'undefined' ? null : data[2]
396✔
776

777
    // Bail out if the key is dynamic; dynamic keys are not really optimized by this block.
778
    if (key && typeof key === 'object') return false
396✔
779

780
    key = key.toString()
288✔
781
    const pieces = splitPathMemoized(key)
288✔
782
    if (!chainingSupported) {
288✔
UNCOV
783
      return `(((a,b) => (typeof a === 'undefined' || a === null) ? b : a)(${pieces.reduce(
48✔
784
        (text, i) => {
UNCOV
785
          return `(${text}||0)[${JSON.stringify(i)}]`
48✔
786
        },
787
        `(${buildString(obj, buildState)}||0)`
788
      )}, ${buildString(defaultValue, buildState)}))`
789
    }
790
    return `((${buildString(obj, buildState)})${pieces
240✔
791
      .map((i) => `?.[${buildString(i, buildState)}]`)
240✔
792
      .join('')} ?? ${buildString(defaultValue, buildState)})`
793
  }
794
  return false
×
795
}
796
// @ts-ignore Allow custom attribute
797
defaultMethods.var.compile = function (data, buildState) {
54✔
798
  let key = data
7,734✔
799
  let defaultValue = null
7,734✔
800
  buildState.varTop = buildState.varTop || new Set()
7,734✔
801
  if (
7,734!
802
    !key ||
38,670✔
803
    typeof data === 'string' ||
804
    typeof data === 'number' ||
805
    (Array.isArray(data) && data.length <= 2)
806
  ) {
807
    if (Array.isArray(data)) {
7,734!
808
      key = data[0]
7,734✔
809
      defaultValue = typeof data[1] === 'undefined' ? null : data[1]
7,734✔
810
    }
811

812
    if (key === '../index' && buildState.iteratorCompile) return 'index'
7,734✔
813

814
    // this counts the number of var accesses to determine if they're all just using this override.
815
    // this allows for a small optimization :)
816
    if (typeof key === 'undefined' || key === null || key === '') return 'context'
7,686✔
817
    if (typeof key !== 'string' && typeof key !== 'number') return false
6,708✔
818

819
    key = key.toString()
6,660✔
820
    if (key.includes('../')) return false
6,660✔
821

822
    const pieces = splitPathMemoized(key)
6,318✔
823
    const [top] = pieces
6,318✔
824
    buildState.varTop.add(top)
6,318✔
825

826
    if (!buildState.engine.allowFunctions) buildState.methods.preventFunctions = a => typeof a === 'function' ? null : a
9,012✔
827
    else buildState.methods.preventFunctions = a => a
60✔
828

829
    // support older versions of node
830
    if (!chainingSupported) {
6,318✔
UNCOV
831
      return `(methods.preventFunctions(((a,b) => (typeof a === 'undefined' || a === null) ? b : a)(${pieces.reduce(
1,053✔
UNCOV
832
        (text, i) => `(${text}||0)[${JSON.stringify(i)}]`,
1,253✔
833
        '(context||0)'
834
      )}, ${buildString(defaultValue, buildState)})))`
835
    }
836
    return `(methods.preventFunctions(context${pieces
5,265✔
837
      .map((i) => `?.[${JSON.stringify(i)}]`)
6,265✔
838
      .join('')} ?? ${buildString(defaultValue, buildState)}))`
839
  }
840
  return false
×
841
}
842

843
// @ts-ignore Allowing a optimizeUnary attribute that can be used for performance optimizations
844
defaultMethods['+'].optimizeUnary = defaultMethods['-'].optimizeUnary = defaultMethods.var.optimizeUnary = defaultMethods['!'].optimizeUnary = defaultMethods['!!'].optimizeUnary = defaultMethods.cat.optimizeUnary = true
54✔
845

846
export default {
847
  ...defaultMethods
848
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc