ALSD Minecraft ALSD Minecraft - 7 months ago 35
Javascript Question

Convert function into jQuery plugin

I have this function:

function abbrNum(number){
var decPlaces = Math.pow(10, 3);
var abbrev = ["k", "m", "b", "t", "qd", "qi", "sx", "sp", "oc", "n", "d"];
for (var i = abbrev.length-1; i>=0; i--){
var size = Math.pow(10, (i+1) * 3);
if(size <= number){
number = Math.round(number*decPlaces/size)/decPlaces;
if((number == 1000) && (i < abbrev.length - 1)){
number = 1;
i++
}
number += abbrev[i];
break;
}
}
return number;
}


I want to convert it into a plugin called for example
format
, which gets some text from a span, runs it through this function, set the text of the same span the result it gets from the function.

So, now if you run the function it works like this:

abbrNum(123456); //123.456k
abbrNum(12345678); //12.345m


So I want to be able to select a span, change it's text, and then format it, something like:

$('span').text(1234).format(); //set span text to 1.234k


How can I do this?

Answer

Create a plugin from the function you have, using jQuery's text() method

$.fn.format = function(){
    this.text(function(_, number) {
        var decPlaces = Math.pow(10, 3);
        var abbrev = ["k", "m", "b", "t", "qd", "qi", "sx", "sp", "oc", "n", "d"];
        for (var i = abbrev.length-1; i>=0; i--){
            var size = Math.pow(10, (i+1) * 3);
            if(size <= number){
                number = Math.round(number*decPlaces/size)/decPlaces;
                if((number == 1000) && (i < abbrev.length - 1)){
                    number = 1;
                    i++
                }
                number += abbrev[i];
                break;
            }           
        }
        return number;
    });
}

$('span').text(1234).format();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>