Giter Club home page Giter Club logo

computer-science-in-javascript's Introduction

Computer Science in JavaScript

by Nicholas C. Zakas

If you find this useful, please consider supporting my work with a donation.

Description

Collection of classic computer science paradigms, algorithms, and approaches written in JavaScript. This is the source code for the series of blog posts on my website.

Folder Structure

The most recent packages are found in these directories:

  • src - the implementation source code
  • tests - tests for the implementation source code

These directories contain old implementations that will be replaced eventually, they are just here to avoid confusing people who find this repo through the old blog posts:

  • data-structures - data structure implementations that have not been updated yet
  • encodings - encoding implementations that have not been updated yet
  • algorithms - miscellanous algorithm implementations that have not been updated yet

As I update these, implementations will move from these folders into src.

Branches

  • 2009 - the branch containing all of the original implementations as reflected in my 2009 blog post series.
  • master - the branch where I'm updating the original implementations to use ECMAScript 2018 and later features.

Installing

You must be using Node.js v8 or later.

First, clone the repo:

$ git clone git://github.com/humanwhocodes/computer-science-in-javascript.git
$ cd computer-science-in-javascript

Then install the dependencies:

$ npm install

You can then run tests like this:

$ npm test

Updated Blog Posts (2019)

These are the most recent blog posts covering the most recent version of the code.

Data Structures

Original Blog Posts

At some point I will update these blog posts for the new implementations. For now, they still refer only to the 2009 version of this code.

Data Structures

Sorting Algorithms

Other Algorithms

Note on Code Style

You may find the code style of this module to be overly verbose with a lot of comments. That is intentional, as the primary use of this module is intended to be for educational purposes. There are frequently more concise ways of implementing the details of this class, but the more concise ways are difficult for newcomers who are unfamiliar with linked lists as a concept or JavaScript as a whole.

Issues and Pull Requests

As this is part of series of tutorials I'm writing, only bug fixes will be accepted. No new functionality will be added to this module.

License

MIT

computer-science-in-javascript's People

Contributors

devinrhode2 avatar kevinwestern avatar lpmtsf avatar nzakas avatar xelad1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

computer-science-in-javascript's Issues

merge-sort-inplace.js is not In Place

merge-sort-inplace.js is not an example of an in place Merge Sort because arrays are being created and concatenated. Here's an example of an in place merge sort...

const mergeSort = (array, left = 0, right = array.length - 1) => {
    
    if (left >= right) return array

    let mid = Math.floor((left + right) / 2),
        i = mid + 1
    
    mergeSort(array, left, mid)
    mergeSort(array, i, right)

    while (left <= mid && i <= right) {
        if (array[left] < array[i]) left++
        else {
            array.splice(left, 0, array.splice(i, 1)[0])
            left++
            mid++
            i++
        }
    }

    return array
}

A little confused about the While condition in `doubly-linked-list.js` insertBefore and insertAfter

~/computer-science-in-javascript/src/data-structures/doubly-linked-list/doubly-linked-list.js

    insertBefore(data, index) {
            // ...omit other lines util here
            // line 183
            while ((current.next !== null) && (i < index)) {
                current = current.next;
                i++;
            }
        }
    insertAfter(data, index) {
        // ...omit other lines util here
        // line 259
        while ((current !== null) && (i < index)) {
            current = current.next;
            i++;
        }

I am confused about the difference of while condition between line 183 and 259,

and do a test in node for the insertAfter method:

const { DoublyLinkedListi } = require( "./doubly-linked-list.js");
const doublyLinkedList = new DoublyLinkedList();

doublyLinkedList.add(1);
doublyLinkedList.insertAfter(1, 1);

and it will throw an the error below, it's not a expected error throw by the doubly Linked List class.

            current.next.previous = newNode;
                    ^
TypeError: Cannot read property 'next' of null

So I think current.next !== null in insertBefore method is right for insertAfter, instead of current !== null

Question about Base64Decode

//ignore white space
text = text.replace(/\s/g,"");

//first check for any unexpected input
if(!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text)) || text.length % 4 > 0){
    throw new Error("Not a base64-encoded string.");
} 
// Q : 
// if there is no space in the String text.
// Why not change RegExp to [a-z0-9\+\/] instead of [a-z0-9\+\/\s] ?

bubbleSort misprint

Hi, Nicholas.

There is an error (misprint) in bubbleSort algorithm that makes unnecessary comparison beyond the range of items in each iteration.
var len = items.length
should be
var len = items.length - 1.

For example, having five items in the list, the last value for j index during first iteration must be 3 and not 4. Because we need to compare fourth item in the list (index 3) with the fifth item in the list (index 4).

The easiest way to see the issue is to put console.log(j, items[j], items[j+1]) in the inner loop and observe that for the first iteration the items[j+1] prints "undefined".

The same issue is in the article at http://www.nczonline.net/blog/2009/05/26/computer-science-in-javascript-bubble-sort/

Thanks
Alexei

For quick sort program

I learn a lot from your "quick sort" program, And it makes my program run so fast ! Thank you.

Compilation error

C:\Users\AngularDev\Desktop\bot\api\node_modules@humanwhocodes\module-importer\dist
module-importer.d.cts:1
export class ModuleImporter {
^^^^^^

SyntaxError: Unexpected token 'export'
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1176:20)
at Module._compile (node:internal/modules/cjs/loader:1218:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Function.Module._load (node:internal/modules/cjs/loader:958:12)
at Module.require (node:internal/modules/cjs/loader:1141:19)
at require (node:internal/modules/cjs/helpers:110:18)
at tryToRequire (C:\Users\AngularDev\Desktop\bot\api\src\util\ImportUtils.ts:21:1
7)
at importOrRequireFile (C:\Users\AngularDev\Desktop\bot\api\src\util\ImportUtils.
ts:27:65)

es6 conversion

Enhancement....def not a bug:

@nzakas as part of tidying up on some CS type things I planned on converting these to the new syntax, just wanted to give you the heads up and see if you'd be interested in a PR (I know they point to your blog series so not sure..) or would prefer to keep in the legacy format. In any case great stuff.

-Cheers

Zac

Removing a node with two children messes up the structure

First off, thanks for sharing. This is a very clean, easy to follow implementation. Very nice.

The only issue I found is when deleting nodes with two children. Try this:
var bst = new BinarySearchTree();
bst.add(7);
bst.add(11);
bst.add(8);
bst.add(13);

At this point the structure looks like this:
7

11
/
8 13

bst.remove(11);

Expected result:
7

8

13

Actual result:
7

8
/
8

Node 8's left pointer points to itself, and the right node has been overwritten.

This line seems odd:

275: replacementParent.right = replacement.left;

This is where node 11 loses its 13 branch.

And

279: replacement.left = current.left;

assigns node 8 to itself.

Hope this helps. Thanks again.

Incorrect removal in BST?

var bst = new BinarySearchTree();

bst.add(8);
bst.add(3);
bst.add(1);
bst.add(10);

bst.add(6);
bst.add(4);
bst.add(7);
bst.add(14);
bst.add(13);

bst.remove(3);
bst.traverse(node => {
// Error
    console.log(node.value);
});

?

Bubble Sort

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted. It gets its name because smaller elements "bubble" to the top of the list with each iteration.

Time Complexity:

Best Case: O(n)
Average Case: O(n^2)
Worst Case: O(n^2)

base64

Your base64Decode fails on the following tests:
//
var tests = [
['YW55IGNhcm5hbCBwbGVhcw', 'any carnal pleas'],
['YQ', 'a'],
['YR', 'a'],
['', ''],
['YQA=', 'a\u0000'],
['YW55IGNhcm5hbCBwbGVhcw==YW55IGNhcm5hbCBwbGVhc3VyZS4=', 'any carnal pleasany carnal pleasure.'],
['YW55IGNhcm5hbCBwbGVhcw==YW55IGNhcm5hbCBwbGVhc3VyZS4', 'any carnal pleasany carnal pleasure.']
];

see https://gist.github.com/1284012

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.