Easily Convert Between HTML and RGB Colors using JavaScript

24. October 2009

To make things easier for converting between HTML Colors and RGB Colors using JavaScript I wrote the below “ColorConverter” object. This object has 2 methods that easily allow you to convert between HTML Colors (ex: #FF33C2) and RGB Colors (ex: 255, 0, 233). There isn’t anything built into JavaScript for doing this, and it can come in very handing when working with the Bing Maps VEColor object.

Usage Examples:

var rgb = ColorConverter.toRGB("#FF000A"); // returns {r:255, g:0, b:10}

var htmlColor = ColorConverter.toHTML(255,0,14); // returns "FF0021"

// Also supports 3 character HTML color values like the Web Browsers and CSS do
rgb = ColorConverter.toRGB("#DDD"); // returns {r:255, g:255, b:255}

Full Code for the “ColorConverter”:

(function(){
    window.ColorConverter = {
        toHTML: function(r, g, b){
            return $ensureHexLength(r.toString(16)) + $ensureHexLength(g.toString(16)) + $ensureHexLength(b.toString(16));
        },
        toRGB: function(color){
            var r, g, b;
            var html = color;
            
            // Parse out the RGB values from the HTML Code
            if (html.substring(0, 1) == "#")
            {
                html = html.substring(1);
            }
            
            if (html.length == 3)
            {
                r = html.substring(0, 1);
                r = r + r;
                
                g = html.substring(1, 2);
                g = g + g;
                
                b = html.substring(2, 3);
                b = b + b;
            }
            else if (html.length == 6)
            {
                r = html.substring(0, 2);
                g = html.substring(2, 4);
                b = html.substring(4, 6);
            }
        
            // Convert from Hex (Hexidecimal) to Decimal
            r = parseInt(r, 16);
            g = parseInt(g, 16);
            b = parseInt(b, 16);
        
            return {r: r, g: g, b: b};
        }
    };
    
    function $ensureHexLength(str){
        if (str.length == 1){
            str = "0" + str;
        }
        return str;
    }
})();

JavaScript, Bing Maps ,

Simplovation Web.Maps.VE v3.0 Now With FREE Edition!

26. August 2009

Simplovation Web.Maps.VE v3.0!Today, I just posted the latest Web.Maps.VE v3.0 release. The coolest thing about this new version is that is has a FREE Edition for non-commercial use!

Download Web.Maps.VE v3.0 FREE Edition!

There are a few new things in this latest release, but the most significant are the following performance updates:

  • Microsoft CDN (Content Delivery Network) Support Added. This helps improve the Bing Maps content delivery speed by up to 82%
  • JavaScript Performance Optimizations. All the JavaScript code internally within the control has been optimized to increase the overall speed of the Web.Maps.VE Map controls functionality.


Check out the following link to see what has all been included in this release:
https://simplovation.com/page/webmapsve30/roadmap.aspx

Also, this new version release is a completely FREE upgrade to all existing customers who have already purchased Web.Maps.VE v2.0. If you have previously purchased v2.0, then there is nothing required to obtain your v3.0 license other than going to the "My Licenses" page to download the DLL and License Activation File. If for some reason you have trouble obtaining your Free Upgrade to v3.0, please let us know and we'll get it activated as soon as possible.

asp.net, Bing Maps, JavaScript , , , , ,

jHtmlArea – Adding Custom Toolbar Buttons

18. August 2009

I’ve gotten a couple questions lately about extending the jHtmlArea WYSIWYG editor, so I thought I’d post a little bit about how to add your own custom toolbar buttons to it. There is one example that is included with the component, but that doesn’t cover inserting some html into the editor, so I’m going to cover that here.

You can download the jHtmlArea Editor here: http://jhtmlarea.codeplex.com/Release/ProjectReleases.aspx

This article was written with jHtmlArea v0.6.0 in mind, but it will work with newer releases.

Add a simple Custom Toolbar Button

As the jHtmlArea samples show you can specify your own list of toolbar buttons to display at the time of initializing the editor. You do this by passing in the “toolbar” option with an array of toolbar button groups (“Arrays”) that include the toolbar buttons. The editor has a bunch of buttons built in and those are specified by name. But, to add a custom toolbar button, you just need to pass in a simple JavaScript object that defines the button.

Here’s an example object literal that can be used to create the custom toolbar button:

{
    css: "custombutton", // The CSS class used to Style the <A> tag of the Toolbar Button
    test: "Custom Button Tooltip", // The text to use as the <A> tags "Alt" attribute, or tooltip
    action: function(btn) { // The function to execute when the Toolbar Button is Clicked
        // 'this' = jHtmlArea Object
        // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

        // Take some action or Do Something Here
    }
}

 

As you can see it’s really pretty straight forward to define a custom toolbar button. Now to include the Custom Toolbar Button, you can send it in the “toolbar” option with all the other buttons you want displayed. Here’s an example that specifies a few of the built in toolbar buttons along with a new Custom Toolbar Button:

$("textarea").htmlarea({
    // Override/Specify the Toolbar buttons to show
    toolbar: [
        ["html"], ["bold", "italic", "underline", "|", "forecolor"],
        ["h1", "h2", "h3", "h4", "h5", "h6"],
        ["link", "unlink", "|", "image"],
        [{
            // This is how to add a completely custom Toolbar Button
            css: "datebutton",
            text: "Today's Date",
            action: function(btn) {
                // 'this' = jHtmlArea object
                // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

                // Take some action or Do Something Here
            }
        }]
    ]
});

 

A couple things to note when specifying the custom set of Toolbar Buttons to display:

  • A Custom Toolbar Button is specified by passing in a JavaScript Object that has the “css”, “text” and “action” properties set accordingly. As shown above.
  • The “toolbar” option accespts an Array of Arrays. This allows for you to specify as many Toolbar Button Groups as you want. These Toolbar Button Groups will auto-wrap to the next line if they cannot all be displayed on the same line because of the width of the editor being too small. If you include ALL your buttons in a single group, then they will not wrap.
  • You can specify the “built in” Toolbar Buttons by “name”. To look what the names are, just reference the “jHtmlArea.defaultOptions” objects “toolbar” property as this is a full list of all the “built in” buttons.
  • To specify a “Separator” or vertical line to display in between the buttons within the same group, just specify a vertical pipe (“|”) character as the “name” of the toolbar button to display, and the editor will take care of the rest.
    Also do not forget to specify the CSS class you are telling the editor to use for the Custom Toolbar Button. You can see an example of this with the Custom “Save” Toolbar Button that is contained within the “default.htm” file that comes with the jHtmlArea editor download zip file.

Performing Basic Actions from a Custom Toolbar Button

Something that was omitted from the above example was how to actually perform some action on the editor. You can actually call any of the jHtmlArea objects methods from within the Custom Toolbar Buttons “action” method to perform some kind of manpulation or action on the editor. The jHtmlArea editor object is passed to the “action” method as the “this” keyword so it can be accessed directly without needing to curry any variables.

Here are some of the methods that you can call with a note as to what they do. You can find more within the jHtmlArea’s script file, or with documentation comments within the “-vsdoc.js” file.

{
    css: "custombutton",
    text: "Custom Toolbar Button",
    action: function(btn) {

        // Paste some specific HTML / Text value into the Editor
        this.pasteHTML("<p></p>");

        // Get the currently selected HTML / Text within the Editor
        var s = this.getSelectedHTML();

        // Set the current selection to Bold
        this.bold();

        // Set the current selection to Italic
        this.italic();

        // Set the current selection to Underline
        this.underline();

        // Center Justify the current selection
        this.justifyCenter();

        // Indent the current selection
        this.indent();

        // Insert horizontal rule or <hr> tag
        this.insertHorizontalRule();

        // Insert an Image by URL
        this.image("http://domain/image.png");

        // Set the Forecolor / Text Color of the current selection
        this.forecolor("#336699");

        // Get the Full HTML that's contained within the Editor
        var html = this.toHtmlString();
    }
}

 

One thing to note about using “pasteHTML” to insert your own custom HTML string into the editor, is because of the way the browsers handle comment tag (“<!-- -->”) they wont pasted/inserted and no exceptions will be raised. The reason I mention this is because I got a question from someone about inserting “<!—more—>” into the Editor.

Also the “btn” argument that’s passed to the “action” method is a reference to the jQuery object for the <A> “anchor” tag that is contained within the Custom Toolbar Button. This allows you to modify it’s CSS styles or absolute position an element near it, similarly to how the “jHtmlArea.ColorPickerMenu” extension does.

Append the Custom Toolbar Button to the “Default” Toolbar Button Set

You can append any Custom Toolbar Buttons you want to the “Default” Toolbar Button Set if you wish for those Custom Toolbar Buttons to be shown on ALL jHtmlArea editors on the Page. To do this you can just append a new Toolbar Button Group to the “jHtmlArea.defaultOptions.toolbar” array. However, make sure you do this before initializing an instance of jHtmlArea, otherwise the button will not be displayed.

Here’s an example that demonstrates appending a Custom Toolbar Button that  pasted the current days date into the editor when clicked:

jHtmlArea.defaultOptions.toolbar.push([
    {
        // This is how to add a completely custom Toolbar Button
        css: "datebutton",
        text: "Today's Date",
        action: function(btn) {
            // 'this' = jHtmlArea object
            // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

            var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

            var d = new Date();
            var curr_date = d.getDate();
            var curr_month = d.getMonth();
            var curr_year = d.getFullYear();
            this.pasteHTML(m_names[curr_month] + " " + curr_date + ", " + curr_year);
        }
    }
]);

jquery, JavaScript , ,

OpenStreetMap: Get FREE Web Mapping with Road Maps for your Applications

3. August 2009

OpenStreetMapScreenshotOpenStreetMap has been around for awhile and provides free geographic data that can be used by anyone. The data is all community created/contributed and that’s why it’s free to use. Other mapping services such as Bing Maps for Enterprise and Google Maps license their geographic data from some other third party and that’s why they cost thousands of dollars per year to use within commercial applications.

Using OpenStreetMap with JavaScript

The screenshot on the left is showing an example of embedding OpenStreetMap imagery within a web page using OpenLayers. OpenLayers is an open-source, JavaScript-based Map control similar to the Bing Maps for Enterprise JavaScript Control and the Google Maps API; except it’s free to use and offers some decent mapping when combined with OpenStreetMap.

You can find examples of using OpenStreetMap with OpenLayers here: http://wiki.openstreetmap.org/wiki/OpenLayers

Using OpenStreetMap with Silverlight

Unfortunately, there aren’t any open-source Silverlight controls like OpenLayers, but you can easily use OpenStreetMap imagery with the Bing Maps for Enterprise Silverlight Control. Here’s an example of how to do this using the current Bing Maps for Enterprise Silverlight Control Beta release:

Virtual Earth Silverlight: Overlay OpenStreetMap, OpenAerialMap and Yahoo Map Imagery using Custom Tile Layers!

JavaScript, Silverlight , , ,

JavaScript: Easily "Extend" an Object/Element

29. July 2009

If you use jQuery then you may be familiar with its "jQuery.extend" method. The "jQuery.extend" method allows you to easily extend one object with one or more others. This is something that can really come in handy, especially when dealing with passing in "options" to a method, and needing to have them "default" to certain values.

For Example:

// "Default" to showing both Toolbar and Footer
var defaultOptions = { showToolbar: true, showFooter: true };

function MyObject = function(options){
    // Create a new "opts" variable that is a copy of "defaultOptions", then apply all values from "options"
    var opts = jQuery.extend({}, defaultOptions, options);

    // Now you have the "opts" variable that has all the "defaultOptions" values merged with the
    // "options" that were passed in to the function.

    // Do Stuff According to "opts" defined

}
MyObject.prototype = {};

// Example of creating new MyObject and passing it only the values you want to override the defaults
var obj = new MyObject({ showFooter: false });
// The above line will tell the new "MyObject" to show the toolbar, but not the footer.

Why use this?

As you can probably tell from the above example of doing this with jQuery, this really helps to simplify and reduce the amount of code you write. The benefits are smaller .js files for the browser to download, and it's just easier to read/maintain the code.

If you still have questions about this, then the following non-jQuery example of doing the same thing should help clear things up for you.

What if I'm Not using jQuery?

As you can probably see, the above example can really help to keep things simple. However, if you're not using jQuery how would you do this?

Now the "jQuery.extend" method has some logic to make sure the resulting object is only a copy and doesn't contain any references to the original so you don't mess things up, but below is really simplified version that will get the job done in most cases.

// Create Global "extend" method
var extend = function(obj, extObj) {
    if (arguments.length > 2) {
        for (var a = 1; a < arguments.length; a++) {
            extend(obj, arguments[a]);
        }
    } else {
        for (var i in extObj) {
            obj[i] = extObj[i];
        }
    }
    return obj;
};

Here's some examples of using the above "extend" method:

var Person = function() {
};
Person.prototype = {
    FirstName: null,
    LastName: null
};       

var person1 = new Person();
// Set multiple object properties with a single line of code
extend(person1, { FirstName: "John", LastName: "Doe" });
alert(person1.FirstName + " " + person1.LastName);

// Create a new Person instance and set it's properties in 1 line
var person2 = extend(new Person(), { FirstName: "John", LastName: "Doe" });
alert(person2.FirstName);

// "clone" person2
var person3 = extend(new Person(), person2);
alert(person3.LastName);

// "clone" person2 and add new properties
var person4 = extend(new Person(), person2, { Age: 18 });
alert(person4.FirstName + " :: " + person4.Age);

This can also be used to more easily add new HTML Elements to a page:


var js = extend(document.createElement("script"), { type: "text/javascript", src: "test.js" });
document.body.appendChild(js);

//As you can see the above is simpler than the traditional method of creating a new <script> Element
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "test.js";
document.body.appendChild(js);

Conclusion

Now the use of the above method is actually really simple, and the end result is pretty much identical to the "jQuery.extend" method for simple tasks. If you want to have a cleaner "cloning" of the object values that get merged, then you'll probably want to use the "jQuery.extend" method or just copy it into your project if you aren't using jQuery.

Enjoy.

JavaScript, jquery ,

jHtmlArea 0.6.0 Update with Improved Functionality

24. July 2009

I just posted a pretty good update the the jHtmlArea project that includes quite a few more toolbar buttons and a new Color Picker Menu extension/plugin (jHtmlAreaColorPickerMenu) that adds a nice, simple color picker when using the "forecolor" toolbar button.

jHtmlArea is a simple, light weight, extensible WYSIWYG HTML Editor built on top of jQuery. This component allows you to easily display a WYSIWYG HTML Editor in place of any TextArea DOM Elements on the page. The minified script alone is 8.7kb, and with css and image files it's a total of 22k.

Download: jHtmlArea Project Home

To the right is an updated screenshot of the latest release, plus below is a full change log for this update release:

- Hide All Toolbar buttons except the "html" button when entering
HTML Source view (via clicking "html" button or executing
jHtmlArea.showHTMLView). When toggling view back to the WYSIWYG editor
all other buttons will then be shown again.

- Added jHtmlArea.dispose method - Allows you to remove the WYSIWYG

editor, and go back to having a plain TextArea. Beware, there is a
memory leak when using this method; it's not too bad, but you want
to call this as few a number of times if you can. The memory leak
is due to the way the browsers handle removing DOM Elements.

- Added Indent and Outdent functionality - This includes toolbar buttons
and jHtmlArea.indent and jHtmlArea.outdent buttons.

- Added justifyLeft, justifyCenter, justifyRight functionality and toolbar
buttons.

- Added insertHorizontalRule functionality and toolbar button. This adds a
<hr> tag to the currently selected area.

- Added an "alias" method for jHtmlArea.execCommand named "ec" to help reduce the
file size of the script.

- Added increaseFontSize and decreaseFontSize functionality and toolbar buttons.
The increaseFontSize and decreaseFontSize doesn't currently work in Safari.

- Added forecolor functionality - Changes a font color for the selection or at the
insertion point. Requires a color value string to be passed in as a value argument.

- Fixed bug in jHtmlArea.toString method

- Added jHtmlArea.queryCommandValue method and it's alias "jHtmlArea.qc"

- Added the jHtmlAreaColorPickerMenu plugin/extension that resides within the
"jHtmlAreaColorPickerMenu.js" file. This file includes a somewhat generic color
picker menu that can be used for any purpose, plus it includes the code to wire
up and override the "stock" jHtmlColor.forecolor functionality and inject the new
Color Picker Menu functionality in it's place when you click on the "forecolor"
toolbar button.

- Changed the "execCommand" and "ec" second parameter to default to "false" if not
specified, and third parameter to default to "null" if not specified. This helps to
reduce the overall file size of the script.

- Added support for Toolbar Button Grouping, now with the additional buttons included
in this release, or even when any custom buttons are used, they will be able to display
nicely by "auto-wrapping" to the next line.

- Added a gradient background to the Toolbar Button Groups, with a slight reverse
gradient on the Buttons when the mouse is hovered over.

 

JavaScript, jquery , , ,

jHtmlArea - The all NEW HTML WYSIWYG Editor for jQuery

21. July 2009

The last couple days I spent time working on a new simple, lightweight, extensible HTML WYSIWYG editor that's built on top of jQuery. I know there are a ton of existing editors, but I couldn't seem to find any with a truely simple, lightweight design that allowed for really easy extensibility, and that's built on top of jQuery to take advantage of the cross-platform capabilities that jQuery has to offer. I feel that I've come up with a really nice HTML editor component that has some pretty usefull extensibility points. Allow me to introduce you to jHTMLArea.

You can download jHtmlArea and some examples of using it over at the official project page on CodePlex: http://jhtmlarea.codeplex.com

To the right there's a screenshot of two instances of jHtmlArea in action. The first one is using the "default" configuration, and the second uses a couple of different custom options, including a completely custom "Save" button that's added using one of jHtmlArea's extensibility points.

Using jHtmlArea is As Simple As 1.2.3.

Follow these 3 steps and you'll have jHtmlArea implemented within your application in no time.

1. Add a <TextArea> to your HTML page

2. Add the "jHtmlArea.js", "jHtmlArea.css" and "jHtmlArea.png" files to your website

3. Add the following JavaScript code to your page to turn all TextArea elements into jHtmlArea's:

$(function(){
    $("textarea").htmlarea();
});

It can be as simple as that to use jHtmlArea within your pages to turn any TextArea DOM Elements into nice jHtmlArea WYSIWYG Editors.

Easily Configure Toolbar Buttons

jHtmlArea makes it extremely simple to define your own custom set of Toolbar buttons; just in case you don't want to show the full set of "default" buttons.

You can easily specify them by name within an array that's passed in as one of the options specified when you call the "htmlarea" method:

$("#txtCustomHtmlArea").htmlarea({
    toolbar: ["bold", "italic", "underline", "|", "h1", "h2", "h3", "h4", "h5", "h6", "|", "link", "unlink"]
});

This example will specify the same buttons displayed in the lower screenshot to the right; minus the "Save" button on the far right of the toolbar. I'll show you how to add this button in the next example.

Add Custom Toolbar Buttons

One of the extensibility points that I was wanting to have in an HTML WYSIWYG editor is the ability to easily add any custom buttons to the toolbar. For instance, some times it may be nice to have a "Save" button in the toolbar to allow your users to easily save the contents of the editor.

Here's an example using the above "custom" toolbar buttons list, with a custom "Save" button added:

$("#txtCustomHtmlArea").htmlarea({
    toolbar: ["bold", "italic", "underline", "|", "h1", "h2", "h3", "h4", "h5", "h6", "|", "link", "unlink", "|",
        // This is how to add a completely custom Toolbar Button
        {
            // The CSS Class to assign the Button <a> tag
            css: "custom_disk_button",

            // The Text to display in the buttons alt text / tooltip
            text: "Save",

            // The function to execute when the button is clicked
            action: function(btn) {
                // 'this' = jHtmlArea object
                // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

                alert('SAVE!\n\n' + this.toHtmlString());

                // Add any Ajax Code here to save the contents of the editor

            }
        }
    ]
});

Once the JavaScript code is entered to add the custom "Save" button, we then need to add the buttons display image to the website, and then include the necessary CSS to allow it to be displayed:

What about Localization?

Well, the jHtmlEditor currently only comes with English text for all the button names / tooltips. However, it is extremely simple to specify your own text to use when calling the "htmlarea" to create jHtmlArea editors within the page. You set the Text to be displayed for each button by referencing it by "name". This is the same "name" that is used in the first example to specify which buttons are displayed in the toolbar.

$("#txtCustomHtmlArea").htmlarea({
    // Override any of the toolbarText values - these are the Alt Text / Tooltips shown
    // when the user hovers the mouse over the Toolbar Buttons
    // Here are a couple translated to German, thanks to Google Translate.
    toolbarText: $.extend({}, jHtmlArea.defaultOptions.toolbarText, {
            "bold": "fett",
            "italic": "kursiv",
            "underline": "unterstreichen"
        })
});

Specify CSS File to be used by the Editor

You can also specify a specify CSS file to be used within the Editor itself.

$("#txtCustomHtmlArea").htmlarea({
    css: "style//jHtmlArea.Editor.css"
});

Specify a Callback when the Editor Finishes Loading

It may be nice in some instances to get notified when the editor has finsihed loading in the page so you can perform some kind of action. This is also really simple to do.

$("#txtCustomHtmlArea").htmlarea({
    // Do something once the editor has finished loading
    loaded: function() {
        //// 'this' is equal to the jHtmlArea object

        alert("jHtmlArea has loaded!");

        //this.showHTMLView(); // show the HTML view once the editor has finished loading
    }
});

Call any jHtmlArea object methods easily from jQuery

Another thing is that the jQuery object doesn't directly expose the different jHtmlArea object's methods. However, you can use the "htmlarea" method to call any of them you need to. All you need to do is specify the method by name that you want to call and pass any additional parameters to the "htmlarea" method and it'll return the results.

// Get the HTML string value from within the editor
var html = $("#txtCustomHtmlArea").htmlarea("toHtmlString");

// Insert a specify Image that you want
$("#txtCustomHtmlArea").htmlarea("image", "image.jpg");

The jHtmlArea object has a few more methods, you can find out what they are by referencing the Visual Studio JavaScript Intellisense File ("jHtmlArea-0.5.0-vsdoc.js") or the un-minified source code itself.

Conclusion

As you can see the jHtmlEditor has some really simple extensibility points. I hope you enjoy using this editor as much as I do. Also, if you have any suggestions/issues, please go to the official jHtmlArea project's Issue Tracker and let me know.

JavaScript, JavaScript, jquery, jquery , , , , , , ,

Adding a DotNetKicks Image/Badge via jQuery

20. July 2009

A while ago Jon Galloway posted a short article titled "Adding a DotNetKicks image via JavaScript" which contains the small amount of JavaScript code necessary to add a DotNetKicks.com Image / Badge to your web pages. The DotNetKicks Badge is essentially a link that allows users to go to DotNetKicks.com to vote for you web page, and the badge also displays the total number of "kicks" that your page has received. Since jQuery has become insanely popular since Jon originally posted his JavaScript code, I thought I would post a jQuery version of his code.

Here's a simple demonstration of the DotNetKicks.com Badge that the below jQuery/JavaScript code will generate:

kick it on DotNetKicks.com

To use the below code you just need to follow the following steps:

  1. Create a <DIV> element wher you want the badge to be displayed.
  2. Set the <DIV>'s ID to 'postToolbar'.
  3. Make sure that the jQuery Library is included within the page.
  4. Include the below jQuery / JavaScript code within the page.

 

Here's the jQuery / JavaScript code:

$(function() {
    var currentPageUrl = document.location.protocol + "//" + document.location.host + document.location.pathname;
    $('#postToolbar').append(
            $('<a/>').
                    attr('href', 'http://www.dotnetkicks.com/kick/?url=' + currentPageUrl).
                    css({ border: 'none' }).
                append(
                    $('<img/>').
                        attr('src', 'http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=' + currentPageUrl).
                        css({ border: 'none' })
                )
        );
});

JavaScript, jquery ,

Creating Ruby-like "Extensions" in JavaScript

16. July 2009

I've been spending a little time here and there learning Ruby. I haven't dug much into Rails yet, but have mostly been just focusing on the Ruby language and what it has to offer. Ruby has some nice "helper" methods attached to it's base data types that make iterations and other simple operations even simpler. I've ported a couple of these methods over to JavaScript so I could play around with using some of these "Ruby-isms" with my favorite web-based, dynamic programming language.

Below are some example usages of each of the methods I ported over to JavaScript. Below are methods that extend the JavaScript "Array", "Number" and "String" data types. The Array "pop" and "join" methods are already Native to JavaScript and don't need any additional coding to be able to utilize them.

My favorite of these methods has to be the Array.times and String.times methods that allow you to more easily iterate over an array or repeat a string a certain number of times.

var test = "";

(10).times(function(i) { test += i; }); // outputs - test = "0123456789"

test = "Chris".reverse(); // outputs "sirhC"

test = "Chris".upcase(); // outputs "CHRIS"
test = "ChRiS".downcase(); // outputs "chris"

test = "";
(5).upto(10, function(start, end) {
    test += this;
}); // outputs - test = "5678910"

test = "";
(10).downto(5, function(start, end) {
    test += this;
}); // outputs - test = "1098765"

test = "";
(0).step(10, 5, function(start, end, step) {
    test += this;
}); // outputs - test = "0510"

test = "";
(10).step(0, 5, function(start, end, step) {
    test += this;
}); // outputs - test = "1050"

test = "Chris".chop(); // outputs "Chri"

test = "Fish".times(3); // outputs "FishFishFish"


var a = ["Chris", "John", "Joe", "Steve"];
test = a.pop(); // <-- native JavaScript feature, same as in Ruby
test = a.join(); // <-- native JavaScript feature, same as in Ruby
test = a.join(","); // <-- native JavaScript feature, same as in Ruby


test = "";
[1, 2, "3", "Chris"].each(function(array, index) {
    test = test + this + ",";
}); // outputs - test = "1,2,3,Chris,"

test = [1, 2, 3, 4, 5].collect(function(array, index) {
    return this * 2;
}); // outputs [2, 4, 6, 8, 10]


test = [].empty(); // outputs - true
test = [1, 2].empty(); // outputs - false

// These "first" and "last" examples use the "a" array defined above
test = a.first(); // outputs "Chris"
test = a.first(2); // outputs ["Chris", "John"]
test = a.last(); // outputs "Steve"
test = a.last(2); // outputs ["Steve", "Joe"]
test = a.last(15);  // <-- if array is shorter than the length specified, it just returns the entire array
test = a.first(15); // <-- if array is shorter than the length specified, it just returns the entire array

test = a.reverse(); // <-- both Arrays and Strings can be reversed

Here's the code for the JavaScript "extensions" that are demonstrated above:

Array.prototype.collect = function(f) {
    var newArray = [];
    this.each(function(array, index) {
        newArray[index] = f.apply(array[index], [array, index]);
    });
    return newArray;
};

Array.prototype.each = function(f) {
    for (var i =  0; i < this.length; i++) {
        f.apply(this[i], [this, i]);
    }
};

Array.prototype.empty = function() {
    return (this.length === 0);
};

Array.prototype.first = function(n) {
    if (n) {
        if (n > this.length) {
            return this;
        } else {
            var r = []
            for (var i = 0; i < n; i++) {
                r.push(this[i]);
            }
            return r;
        }
    } else {
        return this[0];
    }
};

Array.prototype.last = function(n) {
    if (n) {
        if (n > this.length) {
            return this;
        } else {
            var r = [];
            for (var i = this.length - n; i < this.length; i++) {
                r.push(this[i]);
            }
            return r;
        }
    } else {
        return this[this.length - 1];
    }
};

Array.prototype.reverse = function() {
    var r = [];
    for (var i = this.length - 1; i >= 0; i--) {
        r.push(this[i]);
    }
    return r;
};



Number.prototype.times = function(f) {
    for (var i = 0; i < this; i++) {
        f.apply(i, [this]);
    }
};

Number.prototype.upto = function(end, f) {
    this.step(end, 1, f);
};

Number.prototype.downto = function(end, f) {
    this.step(end, 1, f);
};

Number.prototype.step = function(end, step, f) {
    if (this <= end) {
        for (var i = this; i <= end; i += step) {
            f.apply(i, [this, end, step]);
        }
    } else {
        for (var i = this; i >= end; i -= step) {
            f.apply(i, [this, end, step]);
        }
    }
};



String.prototype.chop = function() {
    return this.substr(0, this.length - 1);
};

String.prototype.downcase = function() {
    return this.toLowerCase();
};

String.prototype.reverse = function() {
    var r = "";
    for (var i = this.length - 1; i >= 0; i--) {
        r += this.charAt(i);
    }
    return r;
};

String.prototype.times = function(n) {
    var r = "";
    for (var i = 1; i <= n; i++) {
        r += this;
    }
    return r;
};

String.prototype.upcase = function() {
    return this.toUpperCase();
};

 

This is just something that I was playing around with, so I thought I'd post it to share. Also, I know these methods are pretty much getting placed within the "global namespace" of the Array, Number and String data/object types, but you can't place them within a "sub-namespace" if you want to keep them as "Ruby-like" as possible. I even think that the JavaScript / ECMAScript language could probably benefit from some of the methods being added to the language specification and implemented directly within the web browsers.

If you have any thoughts on this, please post a comment.

JavaScript, Ruby ,

Managed JScript on the DLR from Microsoft is DEAD!! WHY?!??

12. June 2009

I’ve been questioning here and there as to what happened to Managed JScript on the Dynamic Language Runtime. The most recent preview release is really old, and it has since been taken out of any further preview releases of the DLR, where as IronRuby and IronPython continue on.

No More Managed JScript on the DLR?

For some time I never really got any good answers. Well, it’s really sad to hear that apparently Microsoft decided to drop it completely.

According the this link, a member on the DLR team has this to say:

“The DLR JScript was experimental for informing the design of the DLR (expression trees, interop, callsites, hosting, etc.). The JS we released with asp futures and the Silverlight dynamic sdk became very old and unserviceable as the DLR continued evolving for release in CLR 4.0. unfortunately, there are no plans at this time to develop and release a DLR hostable JScript.”

“Experimental for informing the design”??

I understand what this means, but since Managed JScript was used to help build the DLR from the beginning then “Why didn’t they keep it up to date?”

Plus if you go read the Initial Announcement of Managed JScript over on the JScript Blog you will see the following statement:

“We are working to make sure that Managed JScript is a first class language on top of DLR.”

What part of that post and the above statement specify that it’s only “experimental” and not to actually ever get released?

I’m really curious to find out who actually made the decision to drop it, and what the real reason is. Was it you ScottGu?

Why not Open Source it?

Well, the next logical question to ask is “Why not release what was done for Managed JScript as Open Source under a Public License?” At least this way it would allow the community to take it and run with it.

Are there Alternative Implementations?

None that I could find for .NET and/or the DLR. If you know of any, please let me know!

I did however find the Rhino project from Mozilla, but it’s for Java. According to Mozilla, “Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.”  I guess this could be a start at building one for .NET/DLR, but…

Update: I did find the MyJScript project on CodePlex; it’s not a complete implemenation, but it does show the basics on how to create your own scripting language on the DLR. There is also an companion article to the MyJScript project: http://www.dotnetguru.org/us/dlrus/DLR2.htm

Further Info

Here’s a few links that have some small bits of info in addition to that linked above:

http://dlr.codeplex.com/Thread/View.aspx?ThreadId=58121

http://dlr.codeplex.com/Thread/View.aspx?ThreadId=41990

http://channel9.msdn.com/posts/Charles/Jimmy-Schementi-Inside-IronRuby/?CommentID=472955

http://channel9.msdn.com/shows/Going+Deep/John-Lam-and-Martin-Maly-Deep-DLR/?CommentID=472957

http://blogs.msdn.com/jscript/archive/2007/05/04/managed-jscript-announced.aspx

Conclusion

I’ve very disappointed to hear this sad news. However, I guess I could always work on building my own Managed JScript compiler/library for the DLR; if I could only find the time in between my other open source work and other paying gigs.

Until then, I guess I can only hope that Microsoft (or would it be ScottGu) decides to reconsider.

JavaScript, General , ,