Refactor codebase

This commit is contained in:
Aaron Smith 2023-08-22 15:50:03 +01:00
parent 07ae542e28
commit a3f03fd067
15 changed files with 228 additions and 128 deletions

View file

@ -1,22 +1,17 @@
local Instance = Instance
local typeof = typeof
if not game then
script = require "test/relative-string"
Instance = require("test/mock").Instance
typeof = require("test/mock").typeof
end
if not game then script = require "test/relative-string" end
local typeof = game and typeof or require "test/mock".typeof:: never
local Instance = game and Instance or require "test/mock".Instance :: never
local throw = require(script.Parent.throw)
local defaults = require(script.Parent.defaults)
local apply = require(script.Parent.apply)
local memoize = require(script.Parent.memoize)
local function create_instance(className: string)
local success, instance: Instance = pcall(Instance.new, className :: any)
if success == false then throw(`invalid class name, could not create instance of class { className }`) end
local function create_instance(class_name: string)
local ok, instance: Instance = pcall(Instance.new, class_name :: any)
if not ok then throw(`invalid class name, could not create instance of class { class_name }`) end
local default: { [string]: unknown }? = defaults[className]
local default: { [string]: unknown }? = defaults[class_name]
if default then
for i, v in next, default do
(instance :: any)[i] = v
@ -26,7 +21,7 @@ local function create_instance(className: string)
return function(properties: { [any]: unknown }): Instance
return apply(instance:Clone(), properties)
end
end; create_instance = memoize(create_instance)
end; create_instance = memoize(create_instance) -- always return same constructor for given class
local function clone_instance(instance: Instance)
return function(properties: { [any]: unknown }): Instance
@ -36,14 +31,15 @@ local function clone_instance(instance: Instance)
end
end
local function create(classNameOrInstance: string|Instance)
if type(classNameOrInstance) == "string" then
return create_instance(classNameOrInstance)
elseif typeof(classNameOrInstance) == "Instance" then
return clone_instance(classNameOrInstance)
local function create(class_or_instance: string|Instance)
if type(class_or_instance) == "string" then
return create_instance(class_or_instance)
elseif typeof(class_or_instance) == "Instance" then
return clone_instance(class_or_instance)
else
error("Bad argument #1, expected string or instance, got "..typeof(classNameOrInstance), 2)
throw("bad argument #1, expected string or instance, got "..typeof(class_or_instance))
end
return nil :: never
end
type Props = { [any]: any }