All files / libs/amalia-lang/formula/evaluate/shared/src/functions/string/slice index.ts

100% Statements 52/52
100% Branches 1/1
100% Functions 1/1
100% Lines 52/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 531x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { AmaliaFunctionCategory, AmaliaFunctionKeys, type AmaliaFormula } from '@amalia/amalia-lang/formula/types';
import { assert } from '@amalia/ext/typescript';
 
import { AmaliaFunctionDefault } from '../../AmaliaFunction';
 
export const stringSlice = new AmaliaFunctionDefault<[string | null | undefined, number, number?], string | null>({
  name: AmaliaFunctionKeys.SLICE,
  category: AmaliaFunctionCategory.STRING,
  nbParamsRequired: 2,
  description: 'Return a part of a string',
 
  exec: (text, indexStart, indexEnd) => {
    assert(text !== null && text !== undefined, `${AmaliaFunctionKeys.SLICE}: source string is null or undefined`);
    return text.toString().slice(indexStart, indexEnd);
  },
 
  params: [
    { name: 'string', description: 'String: variables, fields, properties, string' },
    {
      name: 'startPosition',
      description: 'Position to start at. Starting at 0. Can be negative to start from the right',
    },
    {
      name: 'endPosition',
      description: 'Position to end at. By default it takes everything left in the string',
      defaultValue: null,
    },
  ],
 
  examples: [
    {
      desc: 'Returns the lazy dog. because end position is undefined.',
      formula: 'SLICE("The quick brown fox jumps over the lazy dog.", 31)' as AmaliaFormula,
      result: 'the lazy dog.',
    },
    {
      desc: 'Returns quick brown fox.',
      formula: 'SLICE("The quick brown fox jumps over the lazy dog.", 4, 19)' as AmaliaFormula,
      result: 'quick brown fox',
    },
    {
      desc: 'Returns dog. because it starts from the right since the startPosition is negative.',
      formula: 'SLICE("The quick brown fox jumps over the lazy dog.", -4)' as AmaliaFormula,
      result: 'dog.',
    },
    {
      desc: 'Returns dog. because it starts from the right at -9 and ends at -5.',
      formula: 'SLICE("The quick brown fox jumps over the lazy dog.", -9, -5)' as AmaliaFormula,
      result: 'lazy',
    },
  ],
});