0

I have a string which is separated by "/", which I then split into an array. eg.

local string = 'Code/Github/Exercises'
local array = std.split(string, "/")

// ['Code', 'Github', 'Exercises']

How do I then convert array so that I can get the output:

// ['Code', 'Code/Github', 'Code/Github/Exercises']
Robert Hung
  • 165
  • 13

1 Answers1

1

Below snippet implements it, using std.foldl() as "iterator" to visit each element and build returned array

local string = 'Code/Github/Exercises';
local array = std.split(string, '/');


// If `array` length > 0 then add `elem` to last `array` element (with `sep`),
// else return `elem`
local add_to_last(array, sep, elem) = (
  local len = std.length(array);
  if len > 0 then array[len - 1] + sep + elem else elem
);

// Accumulate array elements, using std.foldl() to visit each elem and build returned array
local concat(array) = (std.foldl(function(x, y) (x + [add_to_last(x, '/', y)]), array, []));

concat(array)
jjo
  • 2,595
  • 1
  • 8
  • 16