Skip to content

Instantly share code, notes, and snippets.

@birarda
Created December 19, 2011 02:48
Show Gist options
  • Save birarda/1495185 to your computer and use it in GitHub Desktop.
Save birarda/1495185 to your computer and use it in GitHub Desktop.
descriptionOfTopOfStack class method
+ (NSString *)descriptionOfTopOfStack:(NSMutableArray *)stack
{
// get the last object in the program stack
id topObject = [stack lastObject];
if (topObject) [stack removeLastObject];
// if this is just a number just return it
if ([topObject isKindOfClass:[NSNumber class]]) {
return [topObject description];
}
// otherwise it's an operation or variable
else if ([topObject isKindOfClass:[NSString class]]) {
// is this a one operand operation or two operand operation
if ([CalculatorBrain isOneOperandOperation:topObject] || [CalculatorBrain isTwoOperandOperation:topObject]) {
if ([CalculatorBrain isTwoOperandOperation:topObject]) {
// setup array with two operands for this operation by recursion
NSArray *ops = [NSArray arrayWithObjects:[CalculatorBrain descriptionOfTopOfStack:stack],[CalculatorBrain descriptionOfTopOfStack:stack],nil];
// setup NSMutableArray needed to hold the checked operands
NSMutableArray *checkedOps = [NSMutableArray arrayWithCapacity:2];
// alloc init the number formatter needed to check if the operand returned is actually an operation
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
// for-in loop to go through the two operands
for (NSString *op in ops) {
// check if operand returned is an operation and put it in parentheses
if ([f numberFromString:op] == NULL && ![op isEqualToString:@"π"]) {
[checkedOps addObject:[NSString stringWithFormat:@"(%@)", op]];
} else { // otherwise just keep it the same
[checkedOps addObject:op];
}
}
// retrun a string with the two oeprands and the operation
return [NSString stringWithFormat:@"%@ %@ %@", [checkedOps objectAtIndex:1], topObject, [checkedOps objectAtIndex:0]];
} else {
// this is a one operand operation, return it like a function call
return [NSString stringWithFormat:@"%@(%@)", topObject, [CalculatorBrain descriptionOfTopOfStack:stack]];
}
}
// this is a no-operand operator or varible, just return it
else {
return topObject;
}
}
// return nil if the stack was empty or object popped of had the wrong class
return topObject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment