import React, { Component } from 'react'; import Assets from '@src/components/Assets'; import './index.less'; export default class Calculator extends Component { constructor(props) { super(props); this.state = { value: '0' }; this.valueList = []; this.typeList = []; this.change = false; } clear() { this.valueList = []; this.typeList = []; this.setState({ value: '0' }); } del() { const { value } = this.state; if (value.length > 1) { this.setState({ value: value.substr(0, value.length - 1) }); } else if (value !== '0') { this.setState({ value: '0' }); } } f(a, b, c) { switch (c) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: return 0; } } compute() { let { value } = this.state; for (let i = 0; i < this.typeList.length; i += 1) { if (i === 0) { value = this.f(this.valueList[0], this.valueList[1], this.typeList[0]); } else if (this.valueList[i + 1] !== undefined) { value = this.f(value, this.valueList[i + 1], this.typeList[i]); } } return value; } input(text) { const { value } = this.state; switch (text) { case '=': if (this.change && this.typeList.length > 0) { this.valueList.push(value); this.setState({ value: this.compute() }); this.change = false; } break; case '+': case '-': case '*': case '/': if (this.change) { this.valueList.push(value); this.typeList.push(text); this.change = false; if (this.valueList.length > 1) { console.log(this); this.setState({ value: this.compute() }); } } break; case '.': if (this.change && value[value.length - 1] !== '.') { this.setState({ value: `${value}${text}` }); } else if (!this.change) { this.change = true; } break; case 0: if (this.change && value !== '0') { this.setState({ value: `${value}${text}` }); } else if (!this.change) { this.change = true; this.setState({ value: '0' }); } break; default: if (this.change) { if (value !== '0') { this.setState({ value: `${value}${text}` }); } else { this.setState({ value: text }); } } else { this.setState({ value: text }); this.change = true; } break; } } render() { const { show } = this.props; const { value } = this.state; return ( ); } }