term.dart 1.54 KB
Newer Older
1
// Copyright 2016 The Chromium Authors. All rights reserved.
Chinmay Garde's avatar
Chinmay Garde committed
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7
import 'equation_member.dart';
import 'expression.dart';
import 'param.dart';
Chinmay Garde's avatar
Chinmay Garde committed
8

9 10
/// Represents a single term in an expression. This term contains a single
/// indeterminate and has degree 1.
11
class Term extends EquationMember {
12
  /// Creates term with the given [Variable] and coefficient.
Ian Hickson's avatar
Ian Hickson committed
13 14
  Term(this.variable, this.coefficient);

15 16 17 18 19
  /// The [Variable] (or indeterminate) portion of this term. Variables are
  /// usually tied to an opaque object (via its `context` property). On a
  /// [Solver] flush, these context objects of updated variables are returned by
  /// the solver. An external entity can then choose to interpret these values
  /// in what manner it sees fit.
Chinmay Garde's avatar
Chinmay Garde committed
20
  final Variable variable;
21

22 23
  /// The coefficient of this term. Before addition of the [Constraint] to the
  /// solver, terms with a zero coefficient are dropped.
Chinmay Garde's avatar
Chinmay Garde committed
24
  final double coefficient;
25

26
  @override
27
  Expression asExpression() =>
28
      new Expression(<Term>[new Term(this.variable, this.coefficient)], 0.0);
29

30
  @override
31
  bool get isConstant => false;
Chinmay Garde's avatar
Chinmay Garde committed
32

33
  @override
34
  double get value => coefficient * variable.value;
35

36
  @override
37 38 39 40 41 42 43 44 45 46 47 48 49 50
  String toString() {
    StringBuffer buffer = new StringBuffer();

    buffer.write(coefficient.sign > 0.0 ? "+" : "-");

    if (coefficient.abs() != 1.0) {
      buffer.write(coefficient.abs());
      buffer.write("*");
    }

    buffer.write(variable);

    return buffer.toString();
  }
Chinmay Garde's avatar
Chinmay Garde committed
51
}