neolution-ch / javascript-utils

0 stars 3 forks source link

Function to get full path of nested object property #14

Open manni497 opened 11 months ago

manni497 commented 11 months ago

Implement a function that given an expression returns the path in the object like:

      // Act
      string actual = ExpressionUtils.PathOf<ExpressionUtilsTests>(x => x.Recursion.Recursion.Recursion.Recursion);

      // Assert
      actual.ShouldBe("Recursion.Recursion.Recursion.Recursion");

C# implementation

        public static string PathOf<T>(Expression<Func<T, object>> expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            Stack<string> memberNames = new Stack<string>();

            MemberExpression memberExp = GetMemberExpression(expression.Body);

            while (memberExp != null)
            {
                memberNames.Push(memberExp.Member.Name);
                memberExp = GetMemberExpression(memberExp.Expression);
            }

            return string.Join(".", memberNames);
        }

        public static MemberExpression GetMemberExpression(Expression toUnwrap)
        {
            if (toUnwrap is UnaryExpression unaryExpression)
            {
                return unaryExpression.Operand as MemberExpression;
            }

            return toUnwrap as MemberExpression;
        }