//
//  MPPowerTerm.m
//  MathKit
//
//  Created by Kim Wittenburg on 15.11.14.
//  Copyright (c) 2014 Kim Wittenburg. All rights reserved.
//

#import "MPPowerTerm.h"

#import "MPParsedExpression.h"



@implementation MPPowerTerm

- (NSDecimalNumber *)doEvaluation:(NSError *__autoreleasing *)error
{
    MPEvaluateExpression(exponent, 0);
    NSDecimalNumber *base = [self.baseTerm evaluate:error];
    ReturnNilIfNil(base);
    if ([base isEqualToNumber:@(0)] && [exponent isEqualToNumber:@(0)]) {
        // The C pow function returns 1 for pow(0, 0). Mathematically this should be undefined.
        if (error) {
            *error = [NSError errorWithDomain:MPMathKitErrorDomain
                                         code:101
                                     userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"0 to the power of 0 is undefined.", nil)}];
        }
        return nil;
    }
    return [[NSDecimalNumber alloc] initWithDouble:pow(base.doubleValue, exponent.doubleValue)];
}

@end
