Skip to content

Instantly share code, notes, and snippets.

@kraftdorian
Last active April 4, 2021 10:36
Show Gist options
  • Save kraftdorian/1b4cc11c9d69f8dcbc8a92a5d071f2f0 to your computer and use it in GitHub Desktop.
Save kraftdorian/1b4cc11c9d69f8dcbc8a92a5d071f2f0 to your computer and use it in GitHub Desktop.
Recursive insert sort in JavaScript written in Prolog style
const allowedSortValueTypes = ['string', 'number', 'bigint'];
const usePrologStyleList = (array) => {
const [head, ...tail] = array;
return [head, tail];
};
const insertState = (value, list, acc, isInserted) => {
const [head, tail] = usePrologStyleList(list);
if (!allowedSortValueTypes.includes(typeof value)) {
throw new Error(`Value must be one of: ${allowedSortValueTypes.join(', ')}. Given: ${typeof value}`);
}
if (head === undefined) {
return [...acc].concat(isInserted ? [] : value);
}
if (value > head || (value <= head && isInserted)) {
acc = acc.concat(head);
} else if (value <= head && !isInserted) {
acc = acc.concat(value, head);
isInserted = true;
}
return insertState(value, tail, acc, isInserted);
};
const insert = (value, list) => insertState(value, list, [], false);
const insertSortState = (list, sortedList, acc) => {
const [head, tail] = usePrologStyleList(list);
if (head === undefined) {
return sortedList = acc;
}
return insertSortState(tail, sortedList, insert(head, acc));
};
const insertSort = (list) => insertSortState(list, [], []);
@kraftdorian
Copy link
Author

kraftdorian commented Apr 4, 2021

This script is based on this Prolog program.

Use case:

const sortedList = insertSort([1, 5, 3, 2, 4]);
console.log(sortedList);

Result:

[ 1, 2, 3, 4, 5 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment