Skip to content

Commit

Permalink
Javascript math utils
Browse files Browse the repository at this point in the history
Remove prototypejs gsub usage while at it.
  • Loading branch information
nanaya committed Dec 15, 2024
1 parent 41bfbdc commit 5f33751
Showing 1 changed file with 26 additions and 22 deletions.
48 changes: 26 additions & 22 deletions app/javascript/src/utils/math.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
export clamp = (n, min, max) ->
Math.max Math.min(n, max), min
export function clamp (n, min, max) {
return Math.max(Math.min(n, max), min);
}

# Return the squared distance between two points.
export distanceSquared = (x1, y1, x2, y2) ->
(x1 - x2) ** 2 + (y1 - y2) ** 2
// Return the squared distance between two points.
export function distanceSquared (x1, y1, x2, y2) {
return (x1 - x2) ** 2 + (y1 - y2) ** 2;
}

export numberToHumanSize = (size, precision) ->
precision ?= 1
text = undefined
size = Number(size)
if size.toFixed(0) == '1'
text = '1 Byte'
else if size < 1024
text = size.toFixed(0) + ' Bytes'
else if size < 1024 * 1024
text = (size / 1024).toFixed(precision) + ' KB'
else if size < 1024 * 1024 * 1024
text = (size / (1024 * 1024)).toFixed(precision) + ' MB'
else if size < 1024 * 1024 * 1024 * 1024
text = (size / (1024 * 1024 * 1024)).toFixed(precision) + ' GB'
else
text = (size / (1024 * 1024 * 1024 * 1024)).toFixed(precision) + ' TB'
export function numberToHumanSize (size, precision) {
precision ??= 1;
size = Number(size);
let text;
if (size.toFixed(0) === '1') {
text = '1 Byte';
} else if (size < 1024) {
text = `${size.toFixed(0)} Bytes`;
} else if (size < 1024 * 1024) {
text = `${(size / 1024).toFixed(precision)} KB`;
} else if (size < 1024 * 1024 * 1024) {
text = `${(size / (1024 * 1024)).toFixed(precision)} MB`;
} else if (size < 1024 * 1024 * 1024 * 1024) {
text = `${(size / (1024 * 1024 * 1024)).toFixed(precision)} GB`;
} else {
text = `${(size / (1024 * 1024 * 1024 * 1024)).toFixed(precision)} TB`;
}

text.gsub(/([0-9]\.\d*?)0+ /, '#{1} ').gsub(/\. /, ' ')
return text.replace(/([0-9]\.\d*?)0+ /, '$1 ').replace('. ', ' ');
}

0 comments on commit 5f33751

Please sign in to comment.