Mathjs: How to delete/override a unit?

Created on 20 Feb 2018  路  5Comments  路  Source: josdejong/mathjs

Since math.createUnit() throws an exception when creating a unit multiple times, we should be able to delete a unit.

Rationale + Proposal

We have a context focused unit: box. Item foo has 6 items in a box and item bar has 10 items in a box.

So we need to make the calculation in their context:

math.createUnit \item 

# make calculation for `foo`
math.createUnit \box, {definition: '6 item'}
math.eval '4 box to item'  # => 24 item 

# make calculation for `bar`
math.createUnit \box, {definition: '10 item'}  # => throws exception 

# Proposal 1
math.createUnit \box, {definition: '10 item', override: yes} # => suitable for multiple definitions

# Proposal 2
math.deleteUnit \box
math.createUnit \box, {definition: '10 item'}

math.eval '4 box to item'  # => 40 item 
feature

Most helpful comment

Absolutely. I will try to get to it this week.

All 5 comments

Thanks, good point!

The class math.type.Unit already has a static function deleteUnit, we should explose this via a new function math.deleteUnit, similar to math.createUnit.

I like your idea of passing an optional override property when creating a new unit, for example math.import uses the same mechanism.

There is already an override option for defining a new unit:

math.createUnit('mile', '1609.347218694', {override: true}});

LOL I should have checked that beforehand, sorry.

@ericman314 How do you think about exposing math.deleteUnit? I think that makes sense, that way you have a "complete" API which allows to cleanup everything you added.

Absolutely. I will try to get to it this week.

@ericman314 Let's put this here as a live example for future readers: http://jsbin.com/dimayikimu/edit?html,output

The {override: true} solves my current problem. For cleanup purposes, math.deleteUnit would be great to have.

Was this page helpful?
0 / 5 - 0 ratings