Files

listLib.src
  • to_list = function(map)
  • list = []
  • for i in map.indexes
  • if typeof(map[i]) == "map" then
  • list.push([i, to_list(map[i])])
  • else
  • list.push([i, map[i]])
  • end if
  • end for
  • return list
  • end function
  • to_map = function(list)
  • l = list[0:]
  • map = {}
  • for i in indexes(l)
  • if typeof(l[i][1]) == "list" and l[i][1].len == 2 and typeof(l[i][1][0]) == "string" then
  • map[l[i][0]] = to_map(l[i][1])
  • else
  • map[l[i][0]] = l[i][1]
  • end if
  • end for
  • return map
  • end function
  • each = function(obj, func)
  • if typeof(obj) == "map" then
  • list = to_list(obj)
  • else
  • list = obj
  • end if
  • result = list[0:] //list copy.
  • for i in indexes(list)
  • if typeof(obj) == "map" then
  • func(result[i][0], result[i][1])
  • else
  • func(result[i])
  • end if
  • end for
  • end function
  • map = function(list, func)
  • result = list[0:] //list copy.
  • for i in indexes(list)
  • result[i] = func(result[i])
  • end for
  • return result
  • end function
  • reject = function(list, func)
  • result = list[0:] //list copy.
  • i = 0
  • while i < result.len
  • if func(result[i]) == true then
  • result.remove(i)
  • continue
  • end if
  • i = i + 1
  • end while
  • return result
  • end function
  • select = function(list, func)
  • result = list[0:] //list copy.
  • i = 0
  • while i < result.len
  • if func(result[i]) == false then
  • result.remove(i)
  • continue
  • end if
  • i = i + 1
  • end while
  • return result
  • end function
tests.src
  • import_code("/home/guest/listLib/listLib.src")
  • //to list
  • a = {"a": 1, "b": 2, "c": {"a": 1}, "d": []}
  • print(to_list(a))
  • //to map
  • a = [["a", 1], ["b", [1,2]], ["c", [["d", []]]]]
  • print(to_map(a))
  • //each
  • a = {"a": 1, "b": 2}
  • b = [1,2,3,4,5]
  • print_map = function(k,v)
  • print(k)
  • print(v)
  • end function
  • each(a, @print_map)
  • print_list = function(i)
  • print(i)
  • end function
  • each(b, @print_list)
  • //map
  • double = function(n)
  • return n * 2
  • end function
  • print(map([1,2,3,4], @double))
  • //reject
  • more_5 = function(number)
  • return number > 5
  • end function
  • print(reject([1,2,3,4,5,6,7,8], @more_5))
  • // select
  • more_5 = function(number)
  • return number > 5
  • end function
  • print(select([1,2,3,4,5,6,7,8], @more_5))