A sample comparison of Applescript and Javascript (ES6, as in Drafts 5, and in macOS Sierra onwards):
range
It can be useful to have a function which returns a rising list of integers, in exchange for start and end integers. In Python you might write range(5,15)
, in Haskell [5..15]
, and in AppleScript perhaps something like:
-- range :: Int -> Int -> [Int]
on range(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end range
-- TEST --------------------------------
range(0, 9)
--> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
range(5, 15)
--> {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
Here are three ways of defining a reusable function like this for Javascript (range, range2, range3)
(() => {
'use strict';
// Declaring a function with 'function'
// (Slightly more bells and whistles -
// 1. Makes a special array-like 'arguments' value available
// in the body of the function
// 2. locally redefines the special 'this' value
// 3. lifts the function definition to the top of the code
// in terms of evaluation sequence,
// so that it is available even to other functions defined before it.
// range :: Int -> Int -> [Int]
function range(m, n) {
if (m <= n) {
let lst = [];
for (let i = m; i <= n; i++) {
lst.push(i)
}
return lst;
} else {
return [];
}
}
// Declaring a function as a constant value, using the => 'arrow' pattern.
// a bit more light-weight:
// - No array-like 'arguments' value created
// - No local redefinition of 'this'
// - Not lifted to the top of the file during evaluation, so available only
// from the point of definition onwards.
// range2 :: Int -> Int -> [Int]
const range2 = (m, n) => {
if (m <= n) {
let
lst = [],
i = m;
while (i <= n) {
lst.push(i);
i++
}
return lst;
} else {
return [];
};
};
// Using:
// 1. Array.from (See the Mozilla page),
// 2. the conditional ternary operator (which returns a value),
// rather than an if ... else statement, which returns no value
// 3. and no variable declarations, so we need no braces or 'return'.
// range3 :: Int -> Int -> [Int]
const range3 = (m, n) =>
m <= n ? (
Array.from({
length: (n - m) + 1
}, (x, i) => m + i)
) : [];
return {
range: range(5, 15), //--> [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
range2: range2(5, 15), //--> [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
range3: range3(5, 15) //--> [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
};
})();