Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, July 02, 2021

Check if a value in two diminsion array

arr = [[1,2,3],[4,5,6],[7,8,9]] 

 For javascript: 

var result = 1 in arr.flat(); 

For python: 

var result = any(1 in sub for sub in arr);

Thursday, June 24, 2021

List

Create Empty List
JS Python
let arr = [];
arr = []

Create list with size:
let arr = new Array(5);
arr = [None] * 5


Add an item at the end
arr.push(1);
arr.append(1);

Add an item at the begin:
arr.unshift(2);
arr.splice(0, 0, 2);
arr[:0]=[2]
arr.insert(0,2)

Add items inside:
arr.splice(2,0,3,4);
arr[1:0]=[3]

Add 2 arrays:
let arr3 = arr1.concat(arr2);
arr3 = arr1 + arr2
arr = [...arr, ...otherArr];
arr = [*arr, *otherArr]
arr.extend(otherArr)

Delete Items at the end
arr.pop();
arr.pop()

Delete items at the begin:
arr.splice(0,1);
arr[0:1]=[]

Delete items at the begin and return the deleted item
arr.shift();
arr.pop(0)

Delete Items inside (delete one item in index 1):
arr.splice(1,1);
arr[1:2]=[]
arr.pop(1)

Initial values:
arr = new Array(5).fill(0);
arr = [0] * 5

Range:
[...Array(5).keys()].map(i=>i+5);
list(range(5,10)

Get first item:
arr[0]
arr[0]

Get last item:
arr.slice(-1)[0];
arr[-1]

Get first N items:
arr.slice(0, N);
arr[0: N]

Is list?
Array.isArray(arr)
isinstance(arr, list)

String to list:
arr = s.split("");
arr = [...s];
arr = list(s)

List to string
s = arr.join("");
s = "".join(arr)

Tuesday, June 22, 2021

Leetcode question 57

LeetCode Insert Interval :

Here is my solution. It's break a loop into three sections:

1. Find the new begin number to construct new interval.

2. Find the new end number to construct new interval.

3. Append the remaining items into new interval.

Hope this make sense.
Also, hope those if/else conditions can be more straight forward.


/**
 * @param {number[][]} intervals
 * @param {number[]} newInterval
 * @return {number[][]}
 */
 var insert = function(intervalsnewInterval) {
    let begin = newInterval[0];
    let end = newInterval[1];
    let result = [];
    let tmpInterval = [];
    let len = intervals.length;
    let i = 0;

    if (len == 0) {
        return [newInterval]
    }

    // 1. insert begin position
    for (i = 0i < leni++) {
        let interval = intervals[i];
        if (begin <= interval[0]) {
            tmpInterval[0] = begin;
            break;
        } if (begin > interval[0] && begin <= interval[1]) {
            tmpInterval[0] = interval[0];
            break;
        } else if (begin > interval[1]) {
            result.push(interval);
            if (i===len-1){
                result.push(newInterval);
            }
        }
    }

    // 2. insert end position
    for (; i < leni++) {
        let interval = intervals[i];
        if (end < interval[0]) {
            tmpInterval[1] = end;
            result.push(tmpInterval);
            break;
        } else if (end <= interval[1]) {
            tmpInterval[1] = interval[1];
            result.push(tmpInterval);
            i++;
            break;
        } else if (end > interval[1]) {
            if (i===len-1) {
                tmpInterval[1] = Math.max(interval[1], end);
                result.push(tmpInterval);
            }
            continue;
        }

    }

    // 3. remaining interval
    for (; i < leni++) {
        let interval = intervals[i];
        result.push(interval);
    }

    return result;
};

Try to get one step further. Now, just put newInterval into array in order.
Then swap the end number.
The logic in here is getting more straight forward.

/**
 * @param {number[][]} intervals
 * @param {number[]} newInterval
 * @return {number[][]}
 */
 var insert = function(intervalsnewInterval) {
    
    let len = intervals.length;
    // base cases
    if (len == 0) {
        return [newInterval]
    }
    if (newInterval[1] < intervals[0][0]) {
        return [newInterval, ...intervals];
    }
    if (newInterval[0] > intervals[len-1][1]) {
        return [...intervalsnewInterval];
    }

    // merge newInterval into interval in order, 
    // but the end number
    let found = false;
    let tmpIntervals=[]
    for (let i=0i<leni++) {
        let interval = intervals[i];
        if (!found && newInterval[0] <= interval[0]) {
            tmpIntervals.push([...newInterval]);
            found = true;
        }
        tmpIntervals.push([...interval]);
    }
    if (!found) {
        tmpIntervals.push([...newInterval]);
    }

    // fix the end number by swapping
    let last = tmpIntervals[0];
    let result = [last];
    for (let i=1i<tmpIntervals.lengthi++) {
        let interval = tmpIntervals[i];
        if (interval[0]<=last[1]) {
            last[1] = Math.max(last[1], interval[1]);
        } else {
            last = interval
            result.push(last);
        }
    }
    return result;
};







Sunday, June 20, 2021

Two diminsion array

Initial two dimension array with 0L

 > arr = Array(2).fill(Array(10).fill(0));
[
  [
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0
  ],
  [
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0
  ] 

However, assign a data that populate all rows in that position.

> arr[1][2]=3;
3
> arr
[
  [
    0, 0, 3, 0, 0,
    0, 0, 0, 0, 0
  ],
  [
    0, 0, 3, 0, 0,
    0, 0, 0, 0, 0
  ]
]


Initial two dimension array with sequence number:

 > arr = Array(2).fill(Array(10).fill(0)).map((a,i)=>a.map((b,j)=>i*10+j));
[
  [
    0, 1, 2, 3, 4,
    5, 6, 7, 8, 9
  ],
  [
    10, 11, 12, 13, 14,
    15, 16, 17, 18, 19
  ]
]

Reassigning a data is fine in here.

 > arr[1][2] = 77;
77
> arr
[
  [
    0, 1, 2, 3, 4,
    5, 6, 7, 8, 9
  ],
  [
    10, 11, 77, 13, 14,
    15, 16, 17, 18, 19
  ]
]



Monday, July 28, 2008

onmouseout and onmouseleave

onmouseleave is only for IE, but is helpful to suppress the event from the children nodes.

Some introduction in http://www.quirksmode.org/js/events_mouse.html.

Actually, I am looking how to have cascading menu disappear when mouse out.
I hope this example http://bytes.com/forum/thread553630.html is going to help. Got to try it later on.

Friday, July 18, 2008

File upload statistics

The syntax should like

<input type="file"
maxsize="xxx"
progressInitColor="color1"
progressFilledColor="color2"
>

Also, file object should have "progress" properties, which show what is uploading percentage. So, javascript function can read that.

For the UI, once the file is starting to upload, INPUT file area show progressInitColor as background color and progressFilledColor flooding in base on uploading percentage. Also, the upload percentage number show next to file name.

This is what I think.

I saw some of ajax implementations show the file upload status bar. They are all by stage, not really progressive. As browser security, server don't know the file size until fully upload, so there is no way to use ajax to create real progress bar.

Friday, April 18, 2008

Enable designMode, but cause IE double line break when pressing "Enter"

IE is sometime very innovation, but at one point you need to cry for bugging design.
IE came up first HTML editor (WYSIWYG) back to 5.x.

Eventually, Firefox (Mozilla) catch up this feature. And, it's in HTML 5 spec.
When you look at the Mozilla midas definition is very simple, but when you look at MSDN document that is very complicated and bloated. Mozilla implement most basic parts from IE and work perfect.
As security reason, the copy and paste are not scriptable in FF.

The line break is annoying in IE. Most of times, user experience double line break which is not user expected. To avoid double spaces, must use DIV tag as hint. If current cursor position's parent node is not DIV, then double line spaces which from P tag. This is part of developer know how.

Another interesting part is when you apply indentation (Indent), you can find out IE has DIV inside of BLOCKQUOTE. Obviously, the IE folks are trying to avoid double line break.

One time, I did handle key event to force all ENTER key BR tag. Unfortunately, it caused alignment problem. In IE, the alignment is applied to DIV, P, BLOCKQUOTE tag, but not between BR tags.

I am sure many peoples are fighting this issue. Despite, we can use SHIFT+ENTER to force as single line break, but who are going to know that.

Thursday, January 31, 2008

Spaces not displayed when adding Options to Select box

With Option object, you can add multiple spaces to IE, but Firefox.

To work around it, see my sample code.


<FORM name="myForm">
Location (building room) <SELECT name="loc" style="font-family:monospace,Courier,Courier New;font-size:12px"></SELECT>
</FORM>

[SCRIPT language="JavaScript"]
function addOption(obj, text, value) {
value += ""; //in case of number
if (!document.all) { //Firefox
text = text.replace(/\s/g, "\xA0");
}
var newOption = new Option(text,value);
obj.options[obj.options.length] = newOption;

return newOption;
}

addOption(document.myForm.loc, "Please select location" , 0);
addOption(document.myForm.loc, " City Hall          A101" , 1);
addOption(document.myForm.loc, " Governor Hall      1" , 2);
addOption(document.myForm.loc, " Constitution Hall  1" , 3);
addOption(document.myForm.loc, " State Hall         1" , 4);
[/SCRIPT]

Friday, October 26, 2007

javascript form reset()

Today, I am looking at the a problem at form.reset().

I found out form.reset() function suppose to be reset all form objects to original values.

I have problem in this situation :
If I delete an OPTION from a SELECT, reset() function won't recover original item.

I can't find any answers on the web.

Thursday, October 25, 2007

innerText and textContent

Try to use your HTML text/code for your confirm dialog message, below is my sample.



document.getElementById("msg").innerText is perfect for IE, but Firefox.

document.getElementById("msg").textContent works for Firefox, but loses all line breaks.



So I come out my solution :

<div style="display: none; visibility: hidden;" id="msg">
Deleting this category will lose all articles.
Do you really want to do it?</div>

<SCRIPT>
function confirmDeletion() {
var msg = document.getElementById("msg").innerHTML.replace(/
/ig,"\n");
if (confirm(msg) ) {
....
form.submit();
}
return false;
}
</SCRIPT>